如何让 SQLAlchemy session.execute 在替换参数时不向字符串添加单引号?

How to get SQLAlchemy session.execute to not add single quotes to string when replacing parameters?

我在一个更大的语句中有这段 SQL,我需要在其中替换两个变量:

jsonb_pretty(jsonb_build_object('analysis_config', jsonb_agg(
            case value->>'name'
            when :old_name then value || '{"name": ":new_name"}'
            else value
            end
        ))

问题是,当我这样做时,session.execute(statement, params={"old_name": old_name, "new_name": new_name}) new_name 被替换为单引号,这样就不起作用了。它需要明确地用双引号括起来(我已经尝试通过添加它们来做到这一点)。 fstring 工作得很好,但我们不想在这里这样做。 有什么简单的方法可以做到吗?谢谢!

一个选项是将整个 JSON 字符串作为值传递。而不是

when :old_name then value || '{"name": ":new_name"}'

使用

when :old_name then value || :new_name

并传递编码字符串作为值:

import json

session.execute(
    statement,
    params={
        "old_name": old_name,
        "new_name": json.dumps({"name": new_name})
    })