【问题标题】:Implementing Unique if not Null Constraint with SQLAlchemy and MS SQL Server使用 SQLAlchemy 和 MS SQL Server 实现 Unique if not Null 约束
【发布时间】:2016-08-13 09:03:19
【问题描述】:

我想对列强制执行唯一约束,但前提是它不为空。这是 SQLite 中的默认行为,但在 MS SQL Server 中不是。

似乎在 SQL Server 中实现此目的的方法是使用带有 where 子句的索引,如 this post 中所述。我的问题是我如何在 SQLAlchemy 中做到这一点,并让它仍然适用于 SQLite。

我想这大概就是我想要的:

class MyClass(Base):
    __tablename__ = 'myclass'
    __table_args__ = (Index('unique_index', <where clause?>, unique=True)
    my_column = Column(Integer) # The column I want unique if not null

其中&lt;where clause?&gt; 是一些将索引放在my_column 上的表达式,而不是NULL。通过阅读索引的documentation 似乎可以做到这一点,但我不知道我需要什么表达式。非常感谢您提供有关此方法或其他方法的帮助。

【问题讨论】:

  • 目前sqlalchemy 不支持开箱即用。但我认为值得在 sqlalchemy bitbucket 存储库上创建一个new issue,甚至更好地实现它。我认为它的实现应该类似于其他 RDBMS 特定参数,例如 mssql_include and mssql_clustered

标签: python sql-server sqlalchemy


【解决方案1】:

SQL Server使用过滤索引的解决方案:

CREATE TABLE tab(col INT);
CREATE UNIQUE INDEX uq_tab_col ON tab(col) WHERE col IS NOT NULL;

INSERT INTO tab(col) VALUES (1),(2),(NULL),(NULL);

-- INSERT INTO tab(col) VALUES (1);
-- Cannot insert duplicate key row in object 'dbo.tab' with unique index 'uq_tab_col'.
-- The duplicate key value is (1).

SELECT * FROM tab;

LiveDemo

【讨论】:

    【解决方案2】:

    对于以后发现此内容的其他人。 SQL Alchemy 现在支持 index documentation

    import sqlalchemy as sa
    
    sa.Table(
        sa.Column('column', sa.String(50), nullable=True),
        sa.Index('uq_column_allows_nulls', mssql_where=sa.text('column IS NOT NULL'),
    )
    

    如果您打算像我一样使用 alembic,请使用此代码。

    import sqlalchemy as sa
    import alembic as op
    
    op.create_index(
        name='uq_column_name',
        table_name='table',
        columns=['column'],
        mssql_where=sa.text('column IS NOT NULL'),
    )
    

    这将 sql expression 文本用于 sqlalchemy 和 create_indexdialect_expression key word arguments mssql_where=

    【讨论】:

      猜你喜欢
      • 2010-12-20
      • 2021-12-09
      • 1970-01-01
      • 2011-04-19
      • 2018-02-12
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 2016-04-07
      相关资源
      最近更新 更多