在 SQLAlchemy 中,如何使用声明性语法定义一个事件来触发 DDL? [英] In SQLAlchemy, how do I define an event to fire DDL using declarative syntax?

查看:22
本文介绍了在 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆