SQLAlchemy 声明式:定义触发器和索引 (Postgres 9)
表的 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 中的索引语句。不是世界末日,但很容易忘记一步。我非常关注自动化,所以如果我能让这一切在应用程序设置期间发生,那么奖金!
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 ...
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*.
I now want to create a trigger to update "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);
Then I wanted to add that field also as an index ...
create index customers_search_vector_indx ON customers USING gin(search_vector);
Right now after i do any kind of database regeneration from my app i have to do the add column for the tsvector column, the trigger definition, and then the index statement from psql. Not the end of the world but its easy to forget a step. I am all about automation so if I can get this all to happen during the apps setup then bonus!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
索引的创建非常简单。对于具有
index=True
参数的单列,如下所示:但如果您想要对名称和选项进行更多控制,请使用显式 Index() 构造:
也可以创建触发器,但仍需要
基于 SQL 并与之挂钩
DDL
事件。有关详细信息,请参阅自定义 DDL,但代码可能类似于以下内容:旁注:我不知道如何配置 tsvector 数据类型:值得一个单独的问题。
Indicies are straight-forward to create. For single-column with
index=True
parameter like below:But if you want more control over the name and options, use the explicit Index() construct:
Triggers can be created as well, but those need to still be
SQL
-based and hooked to theDDL
events. See Customizing DDL for more info, but the code might look similar to this:Sidenote: I do not know how to configure
tsvector
datatype: deserves a separate question.