我正在为MySQL使用SQLAlchemy。
SQLAlchemy的常见示例是
class User(Base))db.create_all (或alembic等)db.session.query(User))但是如果我想使用原始的SQL文件而不是定义的模型类呢?我确实看到automap做了类似的事情,但我想从原始的SQL文件中获得映射器对象,而不是创建的数据库。
有没有这样做的最佳实践?
这是DDL的一个例子
-- ddl.sql
-- This is just an example, so please ignore some issues related to a grammar
CREATE TABLE `card` (
`card_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'card',
`card_company_id` bigint(20) DEFAULT NULL COMMENT 'card_company_id',
PRIMARY KEY (`card_id`),
KEY `card_ix01` (`card_company_id`),
KEY `card_ix02` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='card table'我想这样做
Base = raw_sql_base('ddl.sql') # Some kinda automap_base but from SQL file
# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("mysql://user@localhost/program")
# reflect the tables
Base.prepare(engine)
# mapped classes are now created with names by sql file
Card = Base.classes.card
session = Session(engine)
session.add(Card(card_id=1, card_company_id=1))
session.commit() # Insert发布于 2019-06-04 14:04:24
SQLAlchemy不是SQL解析器,但恰恰相反;它的反射只对现有数据库起作用。换句话说,您必须执行DDL,然后使用反射/自动映射来创建必要的Python模型:
from sqlalchemy.ext.automap import automap_base
# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("mysql://user@localhost/program")
# execute the DDL in order to populate the DB
with open('ddl.sql') as ddl:
engine.execute(ddl)
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)
# mapped classes are now created with names by sql file
Card = Base.classes.card
session = Session(engine)
session.add(Card(card_id=1, card_company_id=1))
session.commit() # Insert如果您已经对数据库执行了相同的DDL,那么这当然可能会失败,因此您也必须处理这种情况。另一个可能的警告是,如果您的ddl.sql碰巧包含多个CREATE TABLE语句等,那么一些DB-API驱动程序可能不喜欢一次执行多个语句。
...but我想从原始的SQL文件中获取映射器对象。
好的,在这种情况下,你需要的是前面提到的解析器。粗略的搜索产生了两个候选者:
SQL是通用的,但是issue tracker证明了解析
... COMMENT 'card', `card_company_id` ...解析为关键字和标识符列表,而不是关键字、文字、标点符号和标识符(或者更好的是,将列定义为自己的nodes).不过,解析只是第一步。然后,您必须将生成的树转换为模型。
https://stackoverflow.com/questions/56437813
复制相似问题