【发布时间】:2017-11-04 05:35:14
【问题描述】:
我正在使用 SQLAlchemy 使用 compile 并设置 dialect 和 compile_kwargs 参数(例如,使用 str(ins.compile(dialect=oracle.dialect(), compile_kwargs={'literal_binds': True})))动态生成 PL/SQL 这工作正常,除了输出未格式化有史以来最漂亮的 SQL 语句。
例如,我的一个输出如下所示:
INSERT INTO my_table (a, b, c) SELECT my_table2.d, bar.e, bar.f
FROM my_table2 JOIN (SELECT my_table3.e AS e, max(my_table3.f) AS f, count(my_table3.g) AS g
FROM my_table3
WHERE my_table3.h = 'foo' GROUP BY my_table3.e
HAVING count(my_table3.g) = 1) bar ON my_table2.g = bar.g
相反,我希望它像下面这样打印出来:
INSERT INTO my _table (a, b c)
SELECT my_table2.d, bar.e, bar.f
FROM my_table2 JOIN (
SELECT my_table3.e, max(my_table3.f), count(my_table3.g)
FROM my_table3
WHERE my_table3.h = 'foo'
GROUP BY my_table3.e
HAVING count(my_table3.g) = 1
) bar ON my_table2.g = bar.g
如何让 SQLAlchemy 漂亮地打印 SQL 语句?
复制:
从 sqlalchemy 导入表、列、字符串、数字、函数、选择 从 sqlalchemy.dialects 导入 oracle my_table = table('my_table', column('a', String), column('b', String), column('c', String)) my_table2 = table('my_table2', column('d', String), column('g', String)) my_table3 = table('my_table3', column('d', String), column('e', String), column('f', Numeric), column('g', String), column('h',细绳)) inner_sel = select([my_table3.ce, func.max(my_table3.cf).label('f'), func.count(my_table3.cg).label('g')]).where(my_table3.ch== 'foo').group_by(my_table3.ce).having(func.count(my_table3.cg)==1).alias('bar') outer_sel = select([my_table2.c.d, inner_sel.c.e, inner_sel.c.f]).select_from(my_table2.join(inner_sel, my_table2.c.g==inner_sel.c.g)) ins = my_table.insert().from_select([my_table.c.a, my_table.c.b, my_table.c.c], outer_sel) 打印 ins.compile(dialect=oracle.dialect(), compile_kwargs={'literal_binds': True})【问题讨论】:
-
我不认为开箱即用。试试sqlparse。
-
它仍在尝试做某事,看起来:它并非全部在 1 行,但在 SQL 关键字之前有一些中断...嗯,我也在为此寻找免费和智能的东西任务。
标签: python oracle python-2.7 sqlalchemy