在SQLAlchemy中,如何使用声明性语法定义事件以触发DDL? [英] In SQLAlchemy, how do I define an event to fire DDL using declarative syntax?
本文介绍了在SQLAlchemy中,如何使用声明性语法定义事件以触发DDL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此示例显示了如何将其与非声明性"一起使用- http://docs.sqlalchemy.org/en/latest/core/ddl.html#sqlalchemy.schema.DDL
This example shows how to use it with "non-declarative" - http://docs.sqlalchemy.org/en/latest/core/ddl.html#sqlalchemy.schema.DDL
如何将其与ORM声明语法一起使用?
How can I use it with the ORM declarative syntax?
例如,具有以下结构:
Base = declarative_base(bind=engine)
class TableXYZ(Base):
__tablename__ = 'tablexyz'
推荐答案
一个愚蠢的例子,但是认为这是您想要的,应该可以帮助您前进:
Silly example, but think this is what you're looking for, should get you going:
from sqlalchemy import event
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import create_session
from sqlalchemy.schema import Column, DDL
from sqlalchemy.types import Integer
Base = declarative_base()
engine = create_engine('sqlite:////tmp/test.db', echo=True)
class TableXYZ(Base):
__tablename__ = 'tablexyz'
id = Column(Integer, primary_key=True)
#event.listen(
# Base.metadata, 'after_create',
# DDL("""
# alter table TableXYZ add column name text
# """)
event.listen(
TableXYZ.__table__, 'after_create',
DDL("""
alter table TableXYZ add column name text
""")
)
Base.metadata.create_all(engine)
运行上述结果时-在添加的列中记下名称文字":
Running the above results in - note "name text" for the added column:
sqlite> .schema tablexyz
CREATE TABLE tablexyz (
id INTEGER NOT NULL, name text,
PRIMARY KEY (id)
);
我使用声明性代码,并使用event.listen添加触发器和其他存储过程.似乎运作良好.
I have my code in declarative and use the event.listen to add triggers and other stored procedures. Seems to work well.
这篇关于在SQLAlchemy中,如何使用声明性语法定义事件以触发DDL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文