Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

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

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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...