Nils
Nils

Reputation: 357

insert into array of custom type in Postgres

i have created a custom Postgres type with :

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

i have a table that store arrays of new_type like:

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

and i insert data in this table with something like this:

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

and i get this error

ERROR: cannot cast type timestamp without time zone to new_type

What am I missing? I've also tried array syntax that uses {} but nothing better.

Upvotes: 17

Views: 10655

Answers (1)

joanolo
joanolo

Reputation: 6328

The easiest way would probably be:

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

Note that you have to cast the row type to ::new_type.

As an alternative, you could also write:

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

Check PostgreSQL documentation about Composite Value Input.

Upvotes: 28

Related Questions