7

Is it possible to create a contraint on a table and specify a value on one or more of the columns? Condsider this example:

mytable = Table('mytable', meta,

    # per-column anonymous unique constraint
    Column('col1', Integer,),
    Column('col2', Integer),
    Column('col3', ENUM('ready', 'pass', 'fail'),

    UniqueConstraint('col2', 'col2', 'col3', name='uix_1')
    )

But I dont only want uniqueness when col3 is equal to something like a state of 'ready' (I WANT multiple success or failures).

    UniqueConstraint('col2', 'col2', 'col3 == ready', name='uix_1')

Is this possible in the sqlalchemy api?

Erik
  • 898
  • 2
  • 8
  • 28
  • 1
    If your database supports partial indexes, then yes: https://stackoverflow.com/questions/27976683/creating-partial-unique-index-with-sqlalchemy-on-postgres – Ilja Everilä Mar 14 '18 at 22:02

2 Answers2

12

There is a full example on this link:

class ExampleTable(Base):

    __tablename__ = 'example_table'
    __table_args__ = (
        Index(
            'ix_unique_primary_content',  # Index name
            'object_type', 'object_id',  # Columns which are part of the index
        unique=True,
        postgresql_where=Column('is_primary')),  # The condition
    )

    id = Column(Integer, primary_key=True)
    object_type = Column(Unicode(50))
    object_id = Column(Integer)
    is_primary = Column(Boolean)

so you can use something like this:

Index(
    'col1', 'col2',  # Columns which are part of the index
    unique=True,
    postgresql_where=Column("col3='ready'")),  # The condition
Zuabi
  • 1,112
  • 1
  • 13
  • 26
Mohsenasm
  • 2,916
  • 1
  • 18
  • 22
1

So from what I understand you want the group (col1, col2, col3) to be unique only if col3 has the value 'ready'?

I don't think that is possible using unique constraints. It could be done with a CheckConstraint, assuming your database supports it.

You can read up on it here

ricekab
  • 630
  • 5
  • 17