将元组列表作为 Snowflake 中的 cte 内的值传递

Passing list of tuples as values inside a cte in Snowflake

我正在尝试将查询传递给具有以下格式的 Snowflake:

query = f"""
insert into target
with incoming (id,name,age) as (
select * from
values ()
), another_cte (
....
)
select * from another cte
"""

对于值,我想传递一个元组列表。例如: incoming_values = [(1,'john',20),(2,'jane',22)].

我将执行函数调用为:

执行(查询,incoming_values)

但是,我 运行 犯了一个错误: AttributeError: 'tuple' 对象没有属性 'replace'\n"

与其尝试从值中 select 作为文字行,不如以通常的方式将它们插入临时 table 并在查询中使用该临时 table。这将使代码更简洁,这是一个完整的示例:


import snowflake.connector
import os

snowflake_username = os.environ['SNOWFLAKE_USERNAME']
snowflake_password = os.environ['SNOWFLAKE_PASSWORD']
snowflake_account = os.environ['SNOWFLAKE_ACCOUNT']
snowflake_warehouse = os.environ['SNOWFLAKE_WAREHOUSE']
snowflake_database = 'test_db'
snowflake_schema = 'public'


if __name__ == '__main__':
    with snowflake.connector.connect(
        user=snowflake_username,
        password=snowflake_password,
        account=snowflake_account,
        warehouse=snowflake_warehouse,
        database=snowflake_database,
        schema=snowflake_schema,
        autocommit=False
    ) as con:

        # Sample data to load into table
        tuples = [(1, 'john', 20), (2, 'jane', 22), (3, 'simon', 23)]

        # Create temporary table and insert list of tuples into it
        con.cursor().execute("create temporary table incoming (col1 number, col2 varchar, col3 number)")
        con.cursor().executemany("insert into incoming (col1, col2, col3) values (%s, %s, %s)", tuples)

        # This query uses the temporary table within the another_cte cte
        query = """
        with another_cte as (
            select * from incoming
        )
        select * from another_cte
        """

        # Run the query ane fetch the results to prove the temporary table contains the values
        results = con.cursor().execute(query).fetchall()
        print(results)

此脚本打印以下内容:

[(1, 'john', 20), (2, 'jane', 22), (3, 'simon', 23)]

不用担心临时 table 的创建,一旦 Snowflake 会话结束(当程序脱离上下文管理器时),table 就会被清除并消失,它清理后也不会使用任何不必要的存储成本。