unnest 与 psycopg2 抛出错误

unnest with psycopg2 throwing error

我有以下 python 脚本将数据插入 psql

from psycopg2 import connect


con = connect(  """my string""")

query = """   INSERT INTO test.result_data 
              SELECT id,
                     result,
                     result1,
                     result2
              FROM unnest(%s) s(id text, result real, result real, result integer)
"""
t = [('1234jc', 0.0, 1.2123, 1), ('1234sc', 1.0, 1.74, 1)]
c = con.cursor()
c.execute(query, (t,))

抛出以下错误

psycopg2.ProgrammingError: function return row and query-specified return row do not match
DETAIL:  Returned type unknown at ordinal position 1, but query expects text.

以下是table数据库中的结构

|---------------|-------|
|column name    | type  |
|---------------|-------|
|id             | text  |
|---------------|-------|
|result         |float8 |
|---------------|-------|
| cpr           |float8 |
|---------------|-------|
|cpr30          |float8 |
|---------------|-------|

您需要将这些数组转换为一个类型,因为 postgres 不知道如何将记录中的复合类型与列定义列表相匹配。

CREATE TYPE f AS (col1 text, col2 real, col3 real, col4 int);

SELECT * FROM
UNNEST(
  ARRAY[('1234jc', 0.0, 1.2123, 1), ('1234sc', 1.0, 1.74, 1)] :: f[]
);

在Python

query = """ CREATE TYPE f AS (id text, result real, result1 real, result2 int); 
            INSERT INTO test.result_data

            SELECT id,
                   result,
                   result1,
                   result2
            FROM unnest(%s :: f[])
            AS s(id text, result real, result1 real, result2 integer)
"""