1

I have a function like so:

update_stuff_variadic(
 VARIADIC _stuff_array stuff[]
)

I understand that this syntax requires _stuff_array to match the column structure of the stuff[] table.

Instead of implicitly matching every column of the stuff table, is it possible to set the required type of the elements in the array?

Pseudo:

update_stuff_variadic(
 VARIADIC _stuff_array array['comment'::BIGINT, 'created_by'::TEXT]
)

This way the array passed to the function doesn't have to accommodate for columns such as serial id fields, or auto-populated fields such as timestamps.

Erwin Brandstetter
186k28 gold badges464 silver badges636 bronze badges
asked Oct 6, 2021 at 12:05

2 Answers 2

1

You need a registered composite type (row type).
You register a composite type implicitly whenever you create a table or view.
You register a composite type explicitly with CREATE TYPE.

So you could:

CREATE TYPE my_partial_stuff AS (comment bigint, created_by text);
CREATE OR REPLACE FUNCTION update_stuff_variadic(
 VARIADIC _stuff_array my_partial_stuff[]
) ...

And then call the function with:

SELECT update_stuff_variadic ('(8,foo)', '(9,bar)');
answered Oct 6, 2021 at 13:05
1
  • Fantastic. Thank you Erwin! :) Commented Oct 6, 2021 at 14:06
1

I just looked for the same topic and found out that this is working well in my 'PostgreSQL 14.4, compiled by Visual C++ build 1914, 64-bit':

CREATE OR REPLACE FUNCTION myfunc(
 VARIADIC in_ttravalues anyarray DEFAULT null::anyarray
)
 RETURNS json
 LANGUAGE 'plpgsql'
 COST 100
 VOLATILE PARALLEL UNSAFE
AS $BODY$
BEGIN
 -- do some stuff here
 return '{}'::json;
END
$BODY$

This allows to call:

SELECT * FROM myfunc( 'abc'::text, 123);
tinlyx
3,84014 gold badges50 silver badges79 bronze badges
answered Dec 14, 2023 at 6:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.