Alembic:在两个值中强制实现值唯一性

时间:2016-11-11 08:56:09

标签: mysql sqlalchemy alembic

我有下表

mysql> describe table;
+----------------+-------------+------+-----+-------------------+----------------+
| Field          | Type        | Null | Key | Default           | Extra          |
+----------------+-------------+------+-----+-------------------+----------------+
| id             | int(11)     | NO   | PRI | NULL              | auto_increment |
| value1         | varchar(2)  | NO   | MUL | NULL              |                |
| value2         | varchar(2)  | YES  |     | NULL              |                |
| value3         | varchar(10) | YES  |     | NULL              |                |
+----------------+-------------+------+-----+-------------------+----------------+

我尝试创建一个简化规则,其中value1value2一起创建表中的密钥。例如,值

(id=1, value1="BA", value2="CN", value3="hello")
(id=2, value1="BA", value2="CN", value3="goodbye")

相同(value1value2匹配),但

(id=1, value1="BA", value2="CN", value3="hello")
(id=2, value1="BA", value2="US", value3="goodbye")

不是。

使用upgrade()对象的问题是downgrade()alembic.op代码是什么?

1 个答案:

答案 0 :(得分:0)

假设您的模型具有以下UniqueConstraint的定义:

class MyTable(Base):
    __tablename__ = 'mytable'

    id = Column(Integer, primary_key=True)
    value1 = Column(String(2), nullable=False)
    value2 = Column(String(2))
    value3 = Column(String(10))

    __table_args__ = (
        UniqueConstraint(value1, value2, name="mytable__uc_value1_value2"),
    )

然后,def upgrade():的alembic修订版将包含以下命令以创建此唯一约束:

def upgrade():
    op.create_unique_constraint(
        "mytable__uc_value1_value2", "mytable", ["value1", "value2"]
    )