我想在sql中构建一个基本上看起来像这样的索引:
CREATE INDEX IF NOT EXISTS new_index ON schema.tablename USING gist (tsrange(start, "end"))
我的声明性ORM模型看起来像这样:
import sqlalchemy as sa
class Tablename(Mixins):
__table_args__ = (
sa.Index('index_name', postgresql_using="gist"), # ????
{'schema': 'schema'}
)
start = sa.Column(pg.TIMESTAMP, autoincrement=False, primary_key=True)
end = sa.Column(pg.TIMESTAMP, nullable=False)
之后,我想使用alembic
,其中应包括降级,例如:
op.drop_index('index', 'tablename', schema='schema')
实际上有以下SQL:
DROP INDEX IF EXISTS schema.index
答案 0 :(得分:5)
SQLAlchemy的索引支持传递SQL function expressions,因为后端支持功能索引:
import sqlalchemy as sa
class Tablename(Mixins):
start = sa.Column(pg.TIMESTAMP, autoincrement=False, primary_key=True)
end = sa.Column(pg.TIMESTAMP, nullable=False)
__table_args__ = (
sa.Index('index_name', sa.func.tsrange(start, end),
postgresql_using="gist"),
{'schema': 'schema'}
)
请注意,如果在列属性定义之后移动__table_args__
定义,则可以在SQL函数表达式中使用它们。