0
votes

I'm getting a strange error in SQL Alchemy when I try to define both a uniqueness constraint and an index for a given table.

from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, BigInteger, \
    String, Numeric, DateTime, Boolean
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.schema import Index, UniqueConstraint
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy


Base = declarative_base()

class CommonColumns(object):

    id = Column(Integer,
        primary_key=True,
        autoincrement=True
    )
    created_at = Column(
        DateTime,
        server_default=func.now()
    )
    updated_at = Column(
        DateTime,
        server_default=func.now(),
        server_onupdate=func.now()
    )

class Example(CommonColumns, Base):

    __tablename__ = 'encoding'

    model_name = Column(String)
    model_version = Column(String)
    product_id = Column(BigInteger)
    position = Column(Integer)
    file_name = Column(String)
    image_type = Column(String)
    encoding = Column(ARRAY(Numeric))
    sku = Column(String)

    __table_args__ = (
        UniqueConstraint(
            model_name,
            model_version,
            product_id,
            position,
            file_name,
            image_type,
            name='example_unique'
        ),
        Index(
            model_name,
            model_version,
            product_id,
            position,
            file_name,
            image_type,
            name='example_index'
        ),
        {}
    )


connection_string = sqlalchemy.engine.url.URL(
    drivername='<removed>',
    username='<removed>',
    password='<removed>',
    database='<removed>',
    host='<removed>'
)
engine = create_engine(connection_string)
Session = sessionmaker(bind=engine)
session = Session()

Base.metadata.create_all(engine)
session.commit()

This code results in the following error:

Traceback (most recent call last): File "/Users/ryan.zotti/Documents/repos/recommendations/name_example.py", line 30, in class Example(CommonColumns, Base): File "/Users/ryan.zotti/Documents/repos/recommendations/name_example.py", line 60, in Example name='encoding_index' TypeError: init() got multiple values for argument 'name'

Why does the name collision occur? I define name separately for UniqueConstraint and Index.

I'm using SQLAlchemy==1.3.8 and Postgres 9.5.

1

1 Answers

0
votes

The collision was between model_name and name="example_index". The first arg of the Index __init__ method is the name, so try this:

Index(
    "example_index",
    model_name,
    model_version,
    product_id,
    position,
    file_name,
    image_type
)

From: https://docs.sqlalchemy.org/en/13/core/constraints.html#sqlalchemy.schema.Index