一个接受SELECT查询结果的PostgreSQL函数。

huangapple go评论88阅读模式
英文:

postgres function that takes the result of a select query

问题

我正在尝试编写一个 PostgreSQL 函数,该函数接受一个 SELECT 语句的结果作为参数。需要注意的是,我在语句级触发器的上下文中,因此我有 NEWOLD 伪表,并且我想将它们作为参数调用一个函数。

我想能否从类似的 UPDATE 触发器中调用 the_other_func,该触发器也包含伪表。

这种情况是否可行?谢谢!(我使用的是 PostgreSQL 14)

英文:

I'm trying to write a postgres function that takes the result of a select. The detail that requires this use-case is that I'm within the context of a statement-level trigger, so I have the NEW and OLD pseudo-tables, and I'd like to call a function with them as the argument.

CREATE TRIGGER my_trg
AFTER INSERT ON my_table
REFERENCING
    NEW TABLE AS my_inserted_records
FOR EACH STATEMENT
EXECUTE PROCEDURE my_trigger_func();
CREATE FUNCTION my_trigger_func()
RETURNS TRIGGER
AS $$
BEGIN

    SELECT the_other_func(
        (SELECT * FROM my_inserted_records)
    );

    RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE FUNCTION the_other_func(
   ...what here???...
)
RETURNS JSONB
AS $$
    -- do something
$$ LANGUAGE sql;

I want to be able to call the_other_func from a similar UPDATE trigger, which also contains the pseudo-tables.

Is this possible? Thanks! (I'm using postgres 14)

答案1

得分: 1

你无法从这里到达那里,函数参数必须是单个值,包括记录类型和数组,但不能是结果集或表格。

寻找一种方法,使the_other_func成为触发函数,也许可以使用参数来为不同的表格自定义其操作。这可能比以下的解决方案更清晰。

由于允许使用数组,你可以尝试使用记录的数组。

CREATE FUNCTION my_trigger_func()
RETURNS TRIGGER
AS $$
BEGIN

    PERFORM the_other_func (array_agg(i)) 
       FROM my_inserted_records AS i ;

    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

其中,the_other_func的定义如下:

CREATE FUNCTION the_other_func(
   newdata my_table[]
)
...
英文:

you can't get there from here, function arguments must be single values, including record types and arrays, but not result-sets or tables.

look for a way to have the the_other_func be a trigger function
perhaps using arguments customize its operation for different tables. that will probably be a cleaner solution than the following

As arrays are allowed perhaps you could try an array of records.

CREATE FUNCTION my_trigger_func()
RETURNS TRIGGER
AS $$
BEGIN

    PERFORM the_other_func (array_agg(i)) 
       FROM my_inserted_records AS i ;

    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

with the otherfunc being defined as.

CREATE FUNCTION the_other_func(
   newdata my_table[]
)
...

huangapple
  • 本文由 发表于 2023年8月9日 04:01:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定