我正在尝试使用SQLAlchemy在Python中实现PostgreSQL查询,但无济于事。我的查询如下:
with given ("id", "instance") as (
values (1, 1), (108, 23), (203, 5)
)
select given."id" from given
left join panel on panel."id" = given."id" and panel.instance_id = given."instance"
where panel."id" is null
我尝试了许多不同的方法,但是主要的问题是我无法使用CTE语句创建“给定”表,因为它无法预定义列名并提供所需的值。
这是VALUES clause in SQLAlchemy上一个有用的主题,但是我仍然没有设法解决问题。
任何对此问题的见解都将受到欢迎!
答案 0 :(得分:2)
因此,经过一些阅读和调整,我得出了以下结论。首先,我必须添加此处找到的代码作为答案How to make use of bindparam() in a custom Compiled expression?。该代码是VALUES clause in SQLAlchemy中代码的更改版本。
describe('YoutubeService.getTrendingVideos', function() {
it('should resolve to expectedResult', function() {
const params = '';
const expectedResult = [];
return getTrendingVideos(params).should.eventually.equal(expectedResult);
});
});
从那里开始,以下代码对我有用。最后,我不必使用CTE。关键部分是声明临时表的列名,该列名与我的面板表的列名不匹配,因为这会导致“模棱两可的列引用错误”。
from sqlalchemy import *
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import FromClause, ClauseElement
from sqlalchemy.dialects.postgresql import array
from sqlalchemy.types import NULLTYPE
from pp.core.db import panels, engine
class values(FromClause):
named_with_column = True
def __init__(self, columns, *args, **kw):
self._column_args = columns
self.list = args
self.alias_name = self.name = kw.pop('alias_name', None)
def _populate_column_collection(self):
# self._columns.update((col.name, col) for col in self._column_args)
for c in self._column_args:
c._make_proxy(self, c.name)
@compiles(values)
def compile_values(clause, compiler, asfrom=False, **kw):
def decide(value, column):
add_type_hint = False
if isinstance(value, array) and not value.clauses: # for empty array literals
add_type_hint = True
if isinstance(value, ClauseElement):
intermediate = compiler.process(value)
if add_type_hint:
intermediate += '::' + str(column.type)
return intermediate
elif value is None:
return compiler.render_literal_value(
value,
NULLTYPE
) + '::' + str(column.type)
else:
return compiler.process(
bindparam(
None,
value=compiler.render_literal_value(
value,
column.type
).strip("'")
)
) + '::' + str(column.type)
columns = clause.columns
v = "VALUES %s" % ", ".join(
"(%s)" % ", ".join(
decide(elem, column)
for elem, column in zip(tup, columns))
for tup in clause.list
)
if asfrom:
if clause.alias_name:
v = "(%s) AS %s (%s)" % (v, clause.alias_name, (", ".join(c.name for c in clause.columns)))
else:
v = "(%s)" % v
return v