加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – SQLAlchemy声明式:定义触发器和索引(Postgres 9)

发布时间:2020-12-13 16:37:56 所属栏目:百科 来源:网络整理
导读:在表的SQLAlchemy类中是否有一种方法来定义/创建该表的触发器和索引? 例如,如果我有一个基本的表,如… class Customer(DeclarativeBase): __tablename__ = 'customers' customer_id = Column(Integer,primary_key=True,autoincrement=True) customer_code
在表的SQLAlchemy类中是否有一种方法来定义/创建该表的触发器和索引?

例如,如果我有一个基本的表,如…

class Customer(DeclarativeBase):
    __tablename__ = 'customers'
    customer_id = Column(Integer,primary_key=True,autoincrement=True)
    customer_code = Column(Unicode(15),unique=True)
    customer_name = Column(Unicode(100))
    search_vector = Column(tsvector) ## *Not sure how do this yet either in sqlalchemy*.

我现在想创建一个触发器来更新“search_vector”

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);

然后我想添加该字段也作为索引…

create index customers_search_vector_indx ON customers USING gin(search_vector);

现在,在我从应用程序中进行任何类型的数据库重新生成后,我必须对tsvector列,触发器定义和psql中的索引语句添加列。不是世界的尽头,而是容易忘记一步。我所有关于自动化,所以如果我可以让这一切发生在应用程序设置,然后奖金!

印度直接创造。对于索引= True参数的单列,如下所示:
customer_code = Column(Unicode(15),unique=True,index=True)

但是,如果您想要更好地控制名称和选项,请使用显式的Index()构造:

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

也可以创建触发器,但这些触发器仍然需要基于SQL并挂接到DDL事件。请参阅Customizing DDL了解更多信息,但代码可能与此类似:

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,customer_name);
""")
tbl = Customer.__table__
event.listen(tbl,'after_create',trig_ddl.execute_if(dialect='postgresql'))

Sidenote:我不知道如何配置tsvector数据类型:值得一个单独的问题。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读