带有“%%”参数的 Postgres 查询未通过 psycopg2 返回结果

Postgres query with '%%' parameter not returning results via psycopg2

当我在像 DBeaver 这样的查询编辑器中执行下面的查询时 - 它 return 是一个结果但是如果我通过 Python & psycopg2 执行相同的查询它不会 return结果。 '%%' 应匹配任何 title/location,因此总会有 return 内容。我只是针对没有关键字的类别对此进行测试,但如果它们根据类别存在,它也会采用一组关键字。所以数组可以是 ['%%'] 或 ['%boston%', '%cambridge%'] 并且两者都应该有效。

select title, link
from internal.jobs 
where (title ilike any(array['%%'])
or location ilike any(array['%%']))
order by "publishDate" desc
limit 1;

我试过在字符串的开头添加 E 标志。例如。 E'%%'

Python:

import psycopg2

FILTERS = {
    'AllJobs': [],
    'BostonJobs': ['boston', 'cambridge'],
    'MachineLearningJobs': ['ml', 'machine learning']
}

conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()

sql = """
select title, link
from internal.jobs 
where (title ilike any(array[%s])
or location ilike any(array[%s]))
order by "publishDate" desc
limit 1;
"""

for title, tags in FILTERS.items():
    if not tags:
        formatted_filters = "'%%'" # Will match any record
    else:
        formatted_filters = ','.join([f"'%{keyword}%'" for keyword in tags])

    cur.execute(sql, (formatted_filters))
    results = cur.fetchone()
    print(results)

您可以使用 cur.mogrify() 查询查看最终生成的 SQL,检查 psql 是否有效,以及您需要如何调整它。

很可能你必须每 %.

加倍

感谢 Piro 提供非常有用的 cur.mogrify() 线索。这帮助我进一步调试查询以找出问题所在。

我最终删除了额外的引号集,我使用了一个命名参数,现在它按预期工作了。

更新代码:

import psycopg2

FILTERS = {
    'AllJobs': [],
    'BostonJobs': ['boston', 'cambridge'],
    'MachineLearningJobs': ['ml', 'machine learning']
}

conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()

sql = """
select title, link
from internal.jobs 
where (title ilike any(array[%(filter)s])
or location ilike any(array[%(filter)s]))
order by "publishDate" desc
limit 1;
"""

for title, tags in FILTERS.items():
    if not tags:
        formatted_filters = '%%' # Will match any record
    else:
        formatted_filters = [f'%{keyword}%' for keyword in tags]

    print(cur.mogrify(sql, {'filter': formatted_filters}))
    cur.execute(sql, {'filter': formatted_filters})
    results = cur.fetchone()
    print(results)