首页 > 解决方案 > 在带有 psycopg2 的 Postgresql 中找不到自定义类型

问题描述

介绍:

我正在尝试使用 Python/psycopg2 以下列格式将数据插入 Postgres:

(integer, date, integer, customtype[], customtype[], customtype[], customtype[])

但是,当我尝试插入它们时,我总是会收到此错误:

'"customtype[]" 不存在'


我的设置如何:

我有一个包含我需要的数据的字典,如下所示:

data_dict = {'integer1':1, 'date': datetime(), 
             'integer2': 2, 'custom1':[(str, double, double),(str, double, double)], 
             'custom2':[(str, double, double),(str, double, double),(str, double, double)],
             'custom3':[(str, double, double),(str, double, double),(str, double, double)],
             'custom4':[(str, double, double)]}

每个自定义数组都可以根据需要拥有任意数量的自定义元组。

我已经为这些自定义元组创建了一个类型,例如:

"CREATE TYPE customtype AS (text, double precision, double precision)"

我创建了一个包含 customtype [] 列的表。


到目前为止我已经尝试过:

query = """INSERT INTO table (column names...) VALUES
            (%(integer1)s, %(date)s, %(integer2)s, 
            %(custom1)s::customtype[], [...]);"""

和:

query = """INSERT INTO table (column names...) VALUES
            (%(integer1)s, %(date)s, %(integer2)s, 
            CAST(%(custom1)s AS customtype[]), [...]);"""

但是这两个选项都呈现相同的结果。

最后一个问题:

如何使用 Psycopg2 在 Postgresql 中插入这些记录类型的数组?

也许我可能完全误解了 Postgresql 的工作原理。我来自 BigQuery 记录/重复类型背景。

Ps.:这就是我查询的方式:

cursor.execute(query,data_dict)

标签: postgresqlpsycopg2

解决方案


问题是我在数据库中创建了类型。

在 Postgresql 中引用自定义类型时,需要引用创建类型的数据库以及类型。

像这样:

(%(dict_name)s)::"database_name".type
#or
CAST(%(dict_name)s as "database_name".type)

小心引用!


推荐阅读