如何使用PostgresSQL复合类型将表数据传递给函数?

时间:2019-04-10 13:43:24

标签: postgresql compositetype

我想使用composite type将数据传递到函数中。但是,我看不到如何调用该函数。考虑以下代码:

drop table if exists ids cascade;
create table ids
(
    id bigint primary key
);

drop table if exists data;
create table data
(
    id   bigint generated always as identity primary key references ids(id) deferrable initially deferred,
    name text
);

drop type if exists raw_type cascade;
create type raw_type as (name text);
create table raw2 of raw_type;

insert into raw2(name)
values ('test1'),
       ('test2'),
       ('test3'),
       ('test4'),
       ('test5'),
       ('test6'),
       ('test7')
;

create or replace function special_insert(data_to_insert raw_type) returns void as
    $func$
    begin
    with x as (insert into data(name) select name from data_to_insert returning id)
    insert into ids(id)
    select id from x;
    end;
$func$ language plpgsql;

运行此:

begin transaction ;
select special_insert(raw2);
commit ;

我收到以下错误:

ERROR: column "raw2" does not exist

运行此:

begin transaction ;
select special_insert(name::raw_type) from raw2;
commit ;

我明白了

[2019-04-10 15:41:18] [22P02] ERROR: malformed record literal: "test1"
[2019-04-10 15:41:18] Detail: Missing left parenthesis.

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

第二个函数调用是正确的,但是函数定义中存在错误。

您将data_to_insert视为表是错误的,但这是单个值。使用以下符号从组合类型中获取单个字段:

INSERT INTO data (name)
VALUES (data_to_insert.name)
RETURNING id