SQLAlchemy declarative: defining triggers and indexes (Postgres 9)

前端 未结 1 1773
余生分开走
余生分开走 2020-12-13 14:15

Is there a way in the SQLAlchemy class of a table to define/create triggers and indexes for that table?

For instance if i had a basic table like ...

         


        
相关标签:
1条回答
  • 2020-12-13 15:03

    Indicies are straight-forward to create. For single-column with index=True parameter like below:

    customer_code = Column(Unicode(15),unique=True,index=True)
    

    But if you want more control over the name and options, use the explicit Index() construct:

    Index('customers_search_vector_indx', Customer.__table__.c.search_vector, postgresql_using='gin')
    

    Triggers can be created as well, but those need to still be SQL-based and hooked to the DDL events. See Customizing DDL for more info, but the code might look similar to this:

    from sqlalchemy import event, DDL
    trig_ddl = DDL("""
        CREATE TRIGGER customers_search_vector_update BEFORE INSERT OR UPDATE
        ON customers
        FOR EACH ROW EXECUTE PROCEDURE
        tsvector_update_trigger(search_vector,'pg_catalog.english',customer_code,customer_name);
    """)
    tbl = Customer.__table__
    event.listen(tbl, 'after_create', trig_ddl.execute_if(dialect='postgresql'))
    

    Sidenote: I do not know how to configure tsvector datatype: deserves a separate question.

    0 讨论(0)
提交回复
热议问题