The Python Oracle

slqlalchemy UniqueConstraint VS Index(unique=True)

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC I Beethoven Sonata No 31 in A Flat M

--

Chapters
00:00 Question
01:49 Accepted answer (Score 6)
03:22 Thank you

--

Full question
https://stackoverflow.com/questions/4327...

Question links:
[docs]: http://sqlalchemy-utils.readthedocs.io/e...

Accepted answer links:
[Index]: http://docs.sqlalchemy.org/en/latest/cor...
[UniqueConstraint]: http://docs.sqlalchemy.org/en/latest/cor...
[must be defined inline in the table definition]: http://docs.sqlalchemy.org/en/latest/cor...
[Table Configuration]: http://docs.sqlalchemy.org/en/latest/orm...
[Table.append_constraint()]: http://docs.sqlalchemy.org/en/latest/cor...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mysql #database #sqlalchemy

#avk47



ACCEPTED ANSWER

Score 6


The main difference is that while the Index API allows defining an index outside of a table definition as long as it can reference the table through the passed SQL constructs, a UniqueConstraint and constraints in general must be defined inline in the table definition:

To apply table-level constraint objects such as ForeignKeyConstraint to a table defined using Declarative, use the __table_args__ attribute, described at Table Configuration.

The thing to understand is that during construction of a declarative class a new Table is constructed, if not passed an explicit __table__. In your example model class the UniqueConstraint instance is bound to a class attribute, but the declarative base does not include constraints in the created Table instance from attributes. You must pass it in the table arguments:

class MyTable(DeclBase):
    __tablename__ = 'my_table'
    ...
    # A positional argument tuple, passed to Table constructor
    __table_args__ = (
        UniqueConstraint(attr_2, attr_3, name='my_table_uidx'),
    )

Note that you must pass the constraint name as a keyword argument. You could also pass the constraint using Table.append_constraint(), if called before any attempts to create the table:

class MyTable(DeclBase):
    ...

MyTable.__table__.append_constraint(
    UniqueConstraint('attr_2', 'attr_3', name='my_table_uidx'))