Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 504
Brian Bruggeman Avatar asked Dec 13 '25 05:12

Brian Bruggeman


1 Answers

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.

like image 181
Ilja Everilä Avatar answered Dec 14 '25 19:12

Ilja Everilä



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!