Как я могу передать данные таблицы в функцию, используя составной тип PostgresSQL? - PullRequest
0 голосов
/ 10 апреля 2019

Я пытаюсь передать данные в функцию, используя составной тип .Тем не менее, я не вижу, как вызвать функцию.Рассмотрим следующий код:

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 Ответ

1 голос
/ 10 апреля 2019

Второй вызов функции правильный, однако в вашем определении функции есть ошибка.

Вы допустили ошибку, рассматривая data_to_insert как таблицу, но это единственное значение. Используйте следующие обозначения, чтобы получить отдельное поле из составного типа:

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