简体   繁体   中英

SQLAlchemy: Declarative ORM - build index using GIST and TSRANGE

I'd like to build an index that essentially looks like this in sql:

CREATE INDEX IF NOT EXISTS new_index ON schema.tablename USING gist (tsrange(start, "end"))

Where my declarative ORM model looks something like this:

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)

And later, I'd like to use alembic which should include a downgrade such as:

 op.drop_index('index', 'tablename', schema='schema')

Which effectively has the following SQL:

 DROP INDEX IF EXISTS schema.index

SQLAlchemy's Index supports passing SQL function expressions , given that the backend supports functional indexes:

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'}
        )

Note that if you move the __table_args__ definition after the column attribute definitions, you can use them in your SQL function expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM