33

I am trying to write a PL/pgSQL function with optional arguments. It performs a query based on a filtered set of records (if specified), otherwise performs a query on the entire data set in a table.

For example (PSEUDO CODE):

CREATE OR REPLACE FUNCTION foofunc(param1 integer, param2 date, param2 date, optional_list_of_ids=[]) RETURNS SETOF RECORD AS $$
    IF len(optional_list_of_ids) > 0 THEN
        RETURN QUERY (SELECT * from foobar where f1=param1 AND f2=param2 AND id in optional_list_of_ids);
    ELSE
        RETURN QUERY (SELECT * from foobar where f1=param1 AND f2=param2);
    ENDIF
$$ LANGUAGE SQL;

What would be the correct way to implement this function?

As an aside, I would like to know how I could call such a function in another outer function. This is how I would do it - is it correct, or is there a better way?

CREATE FUNCTION foofuncwrapper(param1 integer, param2 date, param2 date) RETURNS SETOF RECORD AS $$
BEGIN
   CREATE TABLE ids AS SELECT id from foobar where id < 100;
   RETURN QUERY (SELECT * FROM foofunc(param1, param2, ids));
END
$$ LANGUAGE SQL
0

3 Answers 3

51

Since PostgreSQL 8.4 (which you seem to be running), there are default values for function parameters. If you put your parameter last and provide a default, you can simply omit it from the call:

CREATE OR REPLACE FUNCTION foofunc(_param1 integer
                                 , _param2 date
                                 , _ids    int[] DEFAULT '{}')
  RETURNS SETOF foobar         -- declare return type!
  LANGUAGE plpgsql AS
$func$
BEGIN  -- required for plpgsql
   IF _ids <> '{}'::int[] THEN  -- exclude empty array and NULL
      RETURN QUERY
      SELECT *
      FROM   foobar
      WHERE  f1 = _param1
      AND    f2 = _param2
      AND    id = ANY(_ids);    -- "IN" is not proper syntax for arrays
   ELSE
      RETURN QUERY
      SELECT *
      FROM   foobar
      WHERE  f1 = _param1
      AND    f2 = _param2;
   END IF;
END  -- required for plpgsql
$func$;

Major points:

  • The keyword DEFAULT is used to declare parameter defaults. Short alternative: =.

  • I removed the redundant param1 from the messy example.

  • Since you return SELECT * FROM foobar, declare the return type as RETURNS SETOF foobar instead of RETURNS SETOF record. The latter form with anonymous records is very unwieldy, you'd have to provide a column definition list with every call.

  • I use an array of integer (int[]) as function parameter. Adapted the IF expression and the WHERE clause accordingly.

  • IF statements are not available in plain SQL. Has to be LANGUAGE plpgsql for that.

Call with or without _ids:

SELECT * FROM foofunc(1, '2012-1-1'::date);

Effectively the same:

SELECT * FROM foofunc(1, '2012-1-1'::date, '{}'::int[]);

You have to make sure the call is unambiguous. If you have another function of the same name and two parameters, Postgres might not know which to pick. Explicit casting (like I demonstrate) narrows it down. Else, untyped string literals work, too, but being explicit never hurts.

Call from within another function:

CREATE FUNCTION foofuncwrapper(_param1 integer, _param2 date)
  RETURNS SETOF foobar
  LANGUAGE plgpsql AS
$func$
DECLARE
   _ids int[] := '{1,2,3}';
BEGIN
   -- whatever

   RETURN QUERY
   SELECT * FROM foofunc(_param1, _param2, _ids);
END
$func$;
1
  • 1
    +1 for actually answering the question. This is exactly what I was looking for! Jul 23, 2012 at 13:02
4

Elaborating on Frank's answer on this thread:

The VARIADIC agument doesn't have to be the only argument, only the last one.

You can use VARIADIC for functions that may take zero variadic arguments, it's just a little fiddlier in that it requires a different calling style for zero args. You can provide a wrapper function to hide the ugliness. Given an initial varardic function definition like:

CREATE OR REPLACE FUNCTION foofunc(param1 integer, param2 date, param2 date, optional_list_of_ids VARIADIC integer[]) RETURNS SETOF RECORD AS $$
....
$$ language sql;

For zero args use a wrapper like:

CREATE OR REPLACE FUNCTION foofunc(integer, date, date) RETURNS SETOF RECORD AS $body$
SELECT foofunc($1,$2,$3,VARIADIC ARRAY[]::integer[]);
$body$ LANGUAGE 'sql';

or just call the main func with an empty array like VARIADIC '{}'::integer[] directly. The wrapper is ugly, but it's contained ugliness, so I'd recommend using a wrapper.

Direct calls can be made in variadic form:

SELECT foofunc(1,'2011-01-01','2011-01-01', 1, 2, 3, 4);

... or array call form with array ctor:

SELECT foofunc(1,'2011-01-01','2011-01-01', VARIADIC ARRAY[1,2,3,4]);

... or array text literal form:

SELECT foofunc(1,'2011-01-01','2011-01-01', VARIADIC '{1,2,3,4}'::int[]);

The latter two forms work with empty arrays.

3
  • I think I can simply change the function signature to CREATE OR REPLACE FUNCTION foofunc(int, date, date, VARIADIC ARRAY[]::integer[]) ? and overload the function with a wrapper for an empty list (I think thats what you are saying). Now, regarding passing a list of ids, how can I pass a list of ids to foofunc() - please refer to the aside at the bottom of my question. Jul 17, 2012 at 11:35
  • @HomunculusReticulli Question updated for further explicitness and clarity. Hope it helps. I haven't dummied them up with syntax checks, I'm working from memory, but I did a bit with variadic functions in Pg recently so it should be right. Jul 17, 2012 at 13:57
  • @HomunculusReticulli The latter part of that proposed signature is invalid; you can't take an array constructor as an argument type. Omit the ARRAY[]::, just accept variable_name VARIADIC integer[] . Jul 17, 2012 at 14:13
1

You mean SQL Functions with Variable Numbers of Arguments? If so, use VARIADIC.

3
  • 1
    @HomunculusReticulli Note that VARIADIC behaves differently to what you might be used to with varargs in some languages. In particular zero variadic arguments aren't accepted. If you want to call with zero variadic arguments, use the syntax the_varargs_function(fixedarg1, fixedarg2, VARIADIC ARRAY[]::argtype[]) where argtype[] is the type of the variadic array argument. It's often handy to write a simple LANGUAGE SQL wrapper function that provides a zero-argument form. Jul 17, 2012 at 10:48
  • Not sure if VARIADIC is useful in all scenarios for me. Its only the last argument that may (or maynot) consist of a list of ids. The previous arguments param1, param2 etc will always be present. Jul 17, 2012 at 10:49
  • @CraigRinger: Yes, this sounds more like the way I want to go. Could you please flesh out your comment as an answer (preferably with a little SQL code), so that I may learn from it?. Thanks Jul 17, 2012 at 10:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.