Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert table into array of custom types

it's easy to convert one column table to single dimension array;

my_array integer[];
my_array := ARRAY(SELECT * FROM single_column_table);

But in my case, I need to convert table with several columns to array of custom type objects;

So I have custom type

TYPE dbfile AS
   (fileid integer,
    deleted boolean,
    name text,
    parentid integer,
    ...
ALTER TYPE dbfile

and array declared as

my_files dbfile[];

-- how to cast table to array of custom types???
my_files := SELECT * FROM get_files();  -- get_files return SETOF dbfile.

how to cast table to array of custom types?

ARRAY() does not work, as it requires single column.

like image 837
Serhiy Avatar asked Sep 18 '15 08:09

Serhiy


1 Answers

You have to use a ROW constructor:

postgres=# SELECT * FROM foo;
┌────┬───────┐
│ a  │   b   │
╞════╪═══════╡
│ 10 │ Hi    │
│ 20 │ Hello │
└────┴───────┘
(2 rows)

postgres=# SELECT ARRAY(SELECT ROW(a,b) FROM foo);
┌──────────────────────────┐
│          array           │
╞══════════════════════════╡
│ {"(10,Hi)","(20,Hello)"} │
└──────────────────────────┘
(1 row)

Any PostgreSQL table has virtual column named as table of record type with with fields related to table's columns. You can use it:

postgres=# SELECT ARRAY(SELECT foo FROM foo);
┌──────────────────────────┐
│          array           │
╞══════════════════════════╡
│ {"(10,Hi)","(20,Hello)"} │
└──────────────────────────┘
(1 row)
like image 64
Pavel Stehule Avatar answered Nov 23 '22 18:11

Pavel Stehule