我正在尝试使用SQLAlchemy进行Pylons,我喜欢它,只有一件事,是否可以在执行之前打印出从Table()。create()生成的原始SQL CREATE TABLE数据?
答案 0 :(得分:82)
from sqlalchemy.schema import CreateTable
print(CreateTable(table))
如果您使用声明性语法:
print(CreateTable(Model.__table__))
<强>更新强>
由于我已接受答案并且klenwell answer中有重要信息,我也会在此处添加。
您可以通过编译引擎来获取特定数据库(MySQL,Postgresql等)的SQL。
print(CreateTable(Model.__table__).compile(engine))
更新2:
@jackotonye在评论中添加了一种没有引擎的方法。
print(CreateTable(Model.__table__).compile(dialect=postgresql.dialect()))
答案 1 :(得分:13)
我需要获取原始表sql以便为某些现有模型设置测试。这是我基于Antoine's answer为SQLAlchemy 0.7.4创建的成功单元测试作为概念证明:
from sqlalchemy import create_engine
from sqlalchemy.schema import CreateTable
from model import Foo
sql_url = "sqlite:///:memory:"
db_engine = create_engine(sql_url)
table_sql = CreateTable(Foo.table).compile(db_engine)
self.assertTrue("CREATE TABLE foos" in str(table_sql))
答案 2 :(得分:9)
您可以使用以下命令设置引擎以转储元数据创建序列:
X_train: (90, 20) y_train: (90,)
X_test: (10, 20) y_test: (10,)
此方法的一个优点是枚举和索引包含在打印输出中。使用def metadata_dump(sql, *multiparams, **params):
# print or write to log or file etc
print(sql.compile(dialect=engine.dialect))
engine = create_engine(myDatabaseURL, strategy='mock', executor=metadata_dump)
metadata.create_all(engine)
就可以了。
另一个优点是模式定义的顺序是正确的,并且(几乎)可用作脚本。
答案 3 :(得分:8)
这样的东西? (来自SQLA FAQ)
http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
答案 4 :(得分:2)
事实证明这是直截了当的:
from sqlalchemy.dialects import postgresql
from sqlalchemy.schema import CreateTable
from sqlalchemy import Table, Column, String, MetaData
metadata = MetaData()
users = Table('users', metadata,
Column('username', String)
)
statement = CreateTable(users)
print(statement.compile(dialect=postgresql.dialect()))
输出:
CREATE TABLE users (
username VARCHAR
)
更进一步,它甚至可以在预准备语句中支持绑定参数。
如何将SQL表达式呈现为字符串,可能使用内联绑定参数?
...
或没有引擎:
from sqlalchemy.dialects import postgresql print(statement.compile(dialect=postgresql.dialect()))
消息来源:http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html#faq-sql-expression-string
#!/usr/bin/env python
import csv
from sqlalchemy.dialects import postgresql
from sqlalchemy import bindparam, Table, Column, String, MetaData
metadata = MetaData()
users = Table('users', metadata,
Column('username', String)
)
renames = []
with open('users.csv') as csvfile:
for row in csv.DictReader(csvfile):
renames.append({
'from': row['sAMAccountName'],
'to': row['mail']
})
for rename in renames:
stmt = (users.update()
.where(users.c.username == rename['from'])
.values(username=rename['to']))
print(str(stmt.compile(dialect=postgresql.dialect(),
compile_kwargs={"literal_binds": True})) + ';')
处理此users.csv时:
sAMAccountName,mail
bmcboatface,boaty.mcboatface@example.com
ndhyani,naina.dhyani@contoso.com
给出如下输出:
UPDATE users SET username='boaty.mcboatface@example.com' WHERE users.username = 'bmcboatface';
UPDATE users SET username='naina.dhyani@contoso.com' WHERE users.username = 'ndhyani';users.username = 'ndhyani';
为什么研究船只有电子邮件地址尚未确定。我与Example Inc的IT团队保持联系并且没有回复。
答案 5 :(得分:1)
您可能是sqlalchemy.create_engine的echo
参数吗?
/ tmp $ cat test_s.py
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = "departments"
department_id = sa.Column(sa.types.Integer, primary_key=True)
name = sa.Column(sa.types.Unicode(100), unique=True)
chief_id = sa.Column(sa.types.Integer)
parent_department_id = sa.Column(sa.types.Integer,
sa.ForeignKey("departments.department_id"))
parent_department = sa.orm.relation("Department")
engine = sa.create_engine("sqlite:///:memory:", echo=True)
Base.metadata.create_all(bind=engine)
/ tmp $ python test_s.py
2011-03-24 15:09:58,311 INFO sqlalchemy.engine.base.Engine.0x...42cc PRAGMA table_info("departments")
2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc ()
2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc
CREATE TABLE departments (
department_id INTEGER NOT NULL,
name VARCHAR(100),
chief_id INTEGER,
parent_department_id INTEGER,
PRIMARY KEY (department_id),
UNIQUE (name),
FOREIGN KEY(parent_department_id) REFERENCES departments (department_id)
)
2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc ()
2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc COMMIT