如何将自定义类型数组传递给Postgres函数

如何将自定义类型数组传递给Postgres函数

问题描述:

我有一个自定义类型

CREATE TYPE mytype as (id uuid, amount numeric(13,4));

我想将其传递给具有以下签名的函数:

I want to pass it to a function with the following signature:

CREATE FUNCTION myschema.myfunction(id uuid, mytypes mytype[])
  RETURNS BOOLEAN AS...

如何在postgres查询中以及不可避免地从PHP中调用它?

How can I call this in postgres query and inevitably from PHP?

您可以将替代语法与

You can use the alternative syntax with a string literal instead of the array constructor, which is a Postgres function-like construct and may cause trouble when you need to pass values - like in a prepared statement:

SELECT myschema.myfunc('0d6311cc-0d74-4a32-8cf9-87835651e1ee'
                  , '{"(0d6311cc-0d74-4a32-8cf9-87835651e1ee, 25)"
                    , "(6449fb3b-844e-440e-8973-31eb6bbefc81, 10)"}'::mytype[]);

我在数组的两个行类型之间添加了一个换行符,以在此处显示.没关系.

I added a line break between the two row types in the array for display here. That's legal.

这是一个演示:

CREATE TEMP TABLE mytype (id uuid, amount numeric(13,4));

INSERT INTO mytype VALUES
  ('0d6311cc-0d74-4a32-8cf9-87835651e1ee', 25)
 ,('6449fb3b-844e-440e-8973-31eb6bbefc81', 10);

SELECT ARRAY(SELECT m FROM mytype m);

返回:

{"(0d6311cc-0d74-4a32-8cf9-87835651e1ee,25.0000)","(6449fb3b-844e-440e-8973-31eb6bbefc81,10.0000)"}

应该注意,任何表(包括临时表)都隐式地创建相同名称的行类型.

It should be noted that any table (including temporary tables) implicitly creates a row type of the same name.