In SQLAlchemy, how do I define an event to fire DDL using declarative syntax?

我怕爱的太早我们不能终老 提交于 2019-11-30 07:36:08

问题


This example shows how to use it with "non-declarative" - http://docs.sqlalchemy.org/en/latest/core/ddl.html#sqlalchemy.schema.DDL

How can I use it with the ORM declarative syntax?

For example, with this structure:

Base = declarative_base(bind=engine)     
class TableXYZ(Base):
    __tablename__ = 'tablexyz'

回答1:


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

I have my code in declarative and use the event.listen to add triggers and other stored procedures. Seems to work well.




回答2:


It should be the same with "non-declarative" and "declarative".

You register your event by specifying (with your class and the doc's event & function) :

event.listen(TableXYZ, 'before_create', DDL('DROP TRIGGER users_trigger'))

Syntax is something like:

event.listen(Class, 'name_of_event', function)


来源:https://stackoverflow.com/questions/12039046/in-sqlalchemy-how-do-i-define-an-event-to-fire-ddl-using-declarative-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!