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.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With