将 table 转换为自定义类型数组

Convert table into array of custom types

很容易将一列table转换为一维数组;

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

但就我而言,我需要将具有多个列的 table 转换为自定义类型对象数组;

所以我有自定义类型

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

数组声明为

my_files dbfile[];

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

如何将 table 转换为自定义类型数组?

ARRAY() 不起作用,因为它需要单列。

您必须使用 ROW 构造函数:

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)

任何 PostgreSQL table 都有名为 table 的记录类型的虚拟列,其字段与 table 的列相关。你可以使用它:

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