2017-03-22 5 views
0

インターネットに散在しているこのような問題はいくつかありますが、私の特定の問題に厳密に対処するものはありません。このcamelcase postgreSQLクエリをpsycopg2/pythonで処理するにはどうすればよいですか?

あなたのお役に立てれば幸いです。あなたは、最終的なSELECTなステートメントで見ることができるように、私がすることはできませんキャメルケースでフォーマットされた名前を持つテーブル(から選択しようしています

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() 

:ここ

は私のスクリプトのごく一部であります変更する:/)。

私は運がないいくつかの異なる方法でAsIs拡張を試しました。

私はcamelCase変数をパラメータ化しようとしましたが、これはテーブル名を使用するときに問題を引き起こします。

「AsIs」でパラメータを設定すると、パラメータ自体がテーブル/インデックス可能なアイテムではないVALUEである場合にのみ、CamelCaseの問題が修正されます。

最後に、このスクリプトの目的は、(上記のクエリを使用して)自分のDB内のテーブルを更新し、別のクエリを使用してそのテーブルから、この同じスクリプト内で生成された電子メールの情報として使用されるデータを返します。

このクエリを他の方法(つまり、psqlコマンド、node.jsファイル、またはcrontabに設定できる他のファイルタイプを使用するbashスクリプト)で実行する方法についての提案がある場合は、私は開いています提案に。クエリはこのファイルに残る必要はありませんが、私はそれを望みます。 (pgAgentは望ましい方法ではありません)

私はこれをUbuntu 14.04サーバーで実行しています。

ご協力いただきましてありがとうございます。ありがとう!

答えて

1

あなたの識別子の二重引用符はエスケープされません。代わりにブロック引用符を使用してください。

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'))) 
""" 
+0

ありがとう!魅力のように働いた。 – jmoneygram

0
cur.execute("select * from %s", (AsIs('"MyTable"'),)) 
関連する問題