插入Postgres中的自定义类型数组

Nil*_*ils 5 sql postgresql

我已经创建了一个自定义Postgres类型:

CREATE TYPE new_type AS (new_date timestamp, some_int bigint);
Run Code Online (Sandbox Code Playgroud)

我有一个表来存储new_type数组,例如:

CREATE TABLE new_table (
    table_id uuid primary key,
    new_type_list new_type[] not null
)
Run Code Online (Sandbox Code Playgroud)

我将数据插入此表中,如下所示:

INSERT INTO new_table VALUES (
    '*inApplicationGeneratedRandomUUID*',
    ARRAY[[NOW()::timestamp, '146252'::bigint],
          [NOW()::timestamp, '526685'::bigint]]::new_type[]
)
Run Code Online (Sandbox Code Playgroud)

我得到这个错误

ERROR: cannot cast type timestamp without time zone to new_type
Run Code Online (Sandbox Code Playgroud)

我想念什么?我也尝试过使用{}的数组语法,但没有更好的方法。

joa*_*olo 8

最简单的方法可能是:

INSERT INTO new_table VALUES (
    '9fd92c53-d0d8-4aba-8925-1bd648d565f2'::uuid,
    ARRAY[ row(now(), 146252)::new_type,
           row(now(), 526685)::new_type
     ] );
Run Code Online (Sandbox Code Playgroud)

请注意,你必须强制转换row类型::new_type

或者,您也可以编写:

INSERT INTO new_table VALUES (
    '9fd92c53-d0d8-4aba-7925-1ad648d565f2'::uuid,
    ARRAY['("now", 146252)'::new_type,
          '("now", 526685)'::new_type
     ] );
Run Code Online (Sandbox Code Playgroud)

检查有关复合值输入的 PostgreSQL文档。