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

时间:2017-01-15 16:47:46

标签: sql postgresql

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

CREATE TYPE new_type AS (new_date timestamp, some_int bigint);

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

CREATE TABLE new_table (
    table_id uuid primary key,
    new_type_list new_type[] not null
)

并在此表中插入数据,如下所示:

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

我收到此错误

ERROR: cannot cast type timestamp without time zone to new_type

我错过了什么? 我也试过使用{}的数组语法,但没有更好。

1 个答案:

答案 0 :(得分:7)

最简单的方法可能是:

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

请注意,您必须 row类型转换为::new_type

作为替代方案,你也可以写:

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

查看有关Composite Value Input

的PostgreSQL文档