2017-10-11 82 views
0

我想要構建SQL查詢傳入spark-redshift閱讀器的「查詢」選項。我試圖使用psycopg2,所以我做這樣的事情:如何在沒有連接的情況下爲postgres(Redshift)生成SQL查詢?

from psycopg2 import sql 

query = sql.SQL(
    "select * from {} where event_timestamp < {}" 
).format(
    sql.Identifier("events"), 
    sql.Literal(datetime.now()) 
).as_string() 

但它告訴我,我需要通過上下文(連接或光標)as_string()。我無法做到,因爲我沒有任何聯繫。

在這種情況下,我應該使用純字符串格式進行一些轉義嗎?

或者有什麼方法可以傳遞一些模擬上下文嗎?爲什麼它需要連接來建立查詢字符串? SQL查詢是否因連接而改變?

回答

1

我並不熟悉spark,但如果他們沒有某種sql支持,我會感到驚訝。另一種選擇是像sqlbuilder這樣的輕量級包裝。

如果你真的想使用psycopg,我建議看看他們如何使用mocks進行單元測試 - psycopg2's ConnectingTestCase

class ConnectingTestCase(unittest.TestCase): 
    """A test case providing connections for tests. 

    A connection for the test is always available as `self.conn`. Others can be 
    created with `self.connect()`. All are closed on tearDown. 

    Subclasses needing to customize setUp and tearDown should remember to call 
    the base class implementations. 
    """ 
相關問題