如何在SQLAlchemy的ExcludeConstraint中使用CAST?

时间:2015-06-10 14:30:18

标签: python postgresql sqlalchemy

在PostgreSQL中,我可以创建一个包含CAST的排除约束的表(CAST是必需的,因为UUID类型没有gist类型的默认运算符类{1}}):

CREATE EXTENSION btree_gist;
CREATE TABLE example (
  id         UUID,
  some_range INT4RANGE,
  EXCLUDE USING gist (CAST("id" AS TEXT) WITH =, some_range WITH &&)
);

我无法弄清楚如何在SQLAlchemy中完成同样的事情。我试过这个:

from sqlalchemy import *
from sqlalchemy.dialects.postgresql import (
    UUID, INT4RANGE, ExcludeConstraint, TEXT
)

class Example(Base):
    __tablename__ = 'example'
    id = Column(UUID)
    some_range = Column(INT4RANGE)
    __table_args__ = (
        ExcludeConstraint(
            (cast('id', TEXT), '='), ('some_range', '&&')
        ),
    )

但我收到错误sqlalchemy.exc.ArgumentError: Can't add unnamed column to column collection

如何让SQLAlchemy使用CAST中的ExcludeConstraint?或者,我如何使用原始SQL在表上定义排除约束?

1 个答案:

答案 0 :(得分:0)

https://bitbucket.org/zzzeek/sqlalchemy/issue/3454开始,解决方法(适用于1.0.6之前的版本)为

from sqlalchemy.sql.elements import quoted_name

    ExcludeConstraint(
        (Column(quoted_name('CAST("id" AS TEXT)', quote=False)), '='), ('some_range', '&&')
    ),