如何使用 psycopg2/python 处理这个驼峰式 postgreSQL 查询?

How can I handle this camelcase postgreSQL query with psycopg2/python?

互联网上散布着几个类似的类似问题,但 none 完全解决了我的特定问题。

希望大家帮帮忙!

这是我的脚本的一小部分:

import psycopg2 as p
import psycopg2.extras as e
# The 'AsIs' extension is here because I've attempted using it to fix my issue - with no luck unfortunately...
from psycopg2.extensions import AsIs

con = p.connect("dbname='my_db' user='user_name' host='123.45.67.89' port='5432'")

cur = con.cursor(cursor_factory=e.DictCursor)

query = "INSERT INTO happy_alerts_triggered (happy_affiliate_id, alert_format, alert_minutes, happy_client_internal_id, alert_triggered_date, alert_processed_date, alert_id, affiliate_name, client_name) 
SELECT r.happy_affiliate_id, r.alert_format, r.alert_minutes, r.happy_client_internal_id, now() as alert_triggered_date, null as alert_processed_date, r.id, ha.happy_affiliate_description, hc.happy_client_description 
FROM happy_alerts_config r 
INNER JOIN happy_affiliates ha ON r.happy_affiliate_id = ha.id 
INNER JOIN happy_clients hc ON r.happy_client_internal_id = hc.id 
WHERE not exists
(SELECT 1 FROM "happyEvents" he 
WHERE he."messageType" = r.alert_format 
AND he."affiliateClient" = hc.happy_client_description 
AND he."insertTime" > (now() - (r.alert_minutes * interval '1 minute')))"

cur.execute(query)

con.commit()
cur.close()

正如您在最后的 SELECT 语句中看到的,我试图从一个 table 中 SELECT 使用驼峰式格式的名称(无法更改: /).

我尝试了几种不同的 AsIs 扩展,但没有成功。

我曾尝试参数化 camelCase 变量,但是在尝试使用 table 名称时这会导致问题。

如果我研究正确,使用 'AsIs' 进行参数化只会修复当参数本身是 VALUES 而不是 tables/indexable 项时的驼峰命名法问题。

最后,这个脚本的原因是更新我的数据库中的 table(使用上面的查询),然后使用另一个查询 return 来自 table 的数据将用作同一脚本中生成的电子邮件中的信息。

如果有关于如何以其他方式 运行 此查询的建议(即在 bash 脚本中使用 psql 命令、node.js 文件或任何其他文件类型可以设置为 crontab),我愿意接受建议。查询不必保留在此文件中,但我希望保留。 (pgAgent 不是首选方法。)

我 运行 在 Ubuntu 14.04 服务器上安装它。

感谢任何帮助!谢谢!

cur.execute("select * from %s", (AsIs('"MyTable"'),))

您的标识符周围的双引号未转义。请改用块引号。

query = """
INSERT INTO happy_alerts_triggered (happy_affiliate_id, alert_format, alert_minutes, happy_client_internal_id, alert_triggered_date, alert_processed_date, alert_id, affiliate_name, client_name) 
SELECT r.happy_affiliate_id, r.alert_format, r.alert_minutes, r.happy_client_internal_id, now() as alert_triggered_date, null as alert_processed_date, r.id, ha.happy_affiliate_description, hc.happy_client_description 
FROM happy_alerts_config r 
INNER JOIN happy_affiliates ha ON r.happy_affiliate_id = ha.id 
INNER JOIN happy_clients hc ON r.happy_client_internal_id = hc.id 
WHERE not exists
(SELECT 1 FROM "happyEvents" he 
WHERE he."messageType" = r.alert_format 
AND he."affiliateClient" = hc.happy_client_description 
AND he."insertTime" > (now() - (r.alert_minutes * interval '1 minute')))
"""