How to pass custom type array to Postgres function

╄→гoц情女王★ 提交于 2019-11-26 23:36:53

问题


I have a custom type

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...

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


回答1:


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.

How to find the correct syntax for any literal?

Here is a demo:

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);

Returns:

{"(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.




回答2:


select myschema.myfunc('0d6311cc-0d74-4a32-8cf9-87835651e1ee'
                , ARRAY[('ac747f0e-93d4-43a9-bc5b-09df06593239', '25.00')
                              , ('6449fb3b-844e-440e-8973-31eb6bbefc81', '10.00')]::mytype[]
    );

Still need PHP portion of this resolved though, still not sure how to call a function populating with the custom array parameter.



来源:https://stackoverflow.com/questions/12009822/how-to-pass-custom-type-array-to-postgres-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!