我需要将SQLAlchemy查询的结果和pyscopg查询的结果结合起来。
目前,我在我的代码中使用心理学来完成我的大部分SQL选择。这是使用游标和fetchall()完成的。
但是,我有一个单独的微服务,它根据一些变量返回语句所需的一些额外的WHERE子句。这将作为SQLAlchemy 选择对象返回。这是我无法控制的。
示例返回:
select * from users where name = 'bar';我目前的解决方案是将微服务的结果(只有WHERE子句)硬编码到枚举中,然后使用f-字符串将它们添加到pyscopg语句中。这是暂时的解决办法。
简化示例:
user_name = "bar"
sql_enum = {
"foo": "name = 'foo'"
"bar": "name = 'bar'"
}
with conn.cursor() as cur:
cur.execute(f"select * from users where location = 'FOOBAR' and {sql_enum[user_name]}")我正在寻找一种更好地加入这两种说法的方法。任何建议都是非常感谢的!
发布于 2022-11-11 16:04:54
与其处理动态SQL (f-string等),不如从SQLAlchemy核心select()语句开始,然后从微服务返回的语句中添加whereclause:
import sqlalchemy as sa
engine = sa.create_engine("postgresql://scott:tiger@192.168.0.199/test")
users = sa.Table(
"users", sa.MetaData(),
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("name", sa.String(50)),
sa.Column("location", sa.String(50))
)
users.drop(engine, checkfirst=True)
users.create(engine)
# mock return from microservice
from_ms = sa.select(sa.text("*")).select_from(users).where(users.c.name == "bar")
base_query = sa.select(users).where(users.c.location == "FOOBAR")
full_query = base_query.where(from_ms.whereclause)
engine.echo = True
with engine.begin() as conn:
result = conn.execute(full_query)
"""SQL emitted:
SELECT users.id, users.name, users.location
FROM users
WHERE users.location = %(location_1)s AND users.name = %(name_1)s
[generated in 0.00077s] {'location_1': 'FOOBAR', 'name_1': 'bar'}
"""https://stackoverflow.com/questions/74400990
复制相似问题