Re: Function with DEFAULT arguments

From: "dario(dot)ber(at)libero(dot)it" <dario(dot)ber(at)libero(dot)it>
To: <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: <pgsql-general(at)postgresql(dot)org>
Subject: Re: Function with DEFAULT arguments
Date: 2010-03-13 00:37:51
Message-ID: 6348737.210651268440671106.JavaMail.defaultUser@defaultHost
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>----Messaggio originale----
>Da: tgl(at)sss(dot)pgh(dot)pa(dot)us
>Data: 12/03/2010 17.51
>A: "dario(dot)ber(at)libero(dot)it"<dario(dot)ber(at)libero(dot)it>
>Cc: <pgsql-general(at)postgresql(dot)org>
>Ogg: Re: [GENERAL] Function with DEFAULT arguments
>
>"dario(dot)ber(at)libero(dot)it" <dario(dot)ber(at)libero(dot)it> writes:
>> I'm trying to use the DEFAULT option to pass parameters to the arguments of
a
>> function.
>> When I call that function, how can I change the default value of some
>> arguments and leave as default the value of other arguments?
>
>You can only omit arguments from right to left, so basically what this
>requires is some foresight while choosing the function's argument order.
>
> regards, tom lane

Thanks for replies!
Would it be a very horrible workaround to pass a single string to the function
which contains the user's parameters? This string then is parsed into the
individual arguments/defaults inside the function. In this way there is no need
to have arguments in any order.

Example using plpythonu:

CREATE OR REPLACE FUNCTION test_default(arg_string text) RETURNS text AS
$$
## List of pseudo-arguments the function can take
arg_1= 'arg_1'
arg_2= 'arg_2'
arg_3= 'arg_3'

## Convert the argument string to a dictionary
arg_dict= eval('{' + arg_string + '}')

## Retrieve user's parameters and assign defaults
try:
arg_1= arg_dict[arg_1]
except:
arg_1= 'A'
try:
arg_2= arg_dict[arg_2]
except:
arg_2= 'B'
try:
arg_3= arg_dict[arg_3]
except:
arg_3= 'C'

## Do something with the parameters
return('One: ' + arg_1 + '; Two: ' + arg_2 + '; Three: ' + arg_3)
$$
language 'plpythonu';

-- Execute with default 'pseudo-arguments' only:
SELECT test_default($$ $$);
--> One: A; Two: B; Three: C

-- With arg_2 as default:
SELECT test_default($$ arg_3:'z', arg_1:'x' $$);
--> One: x; Two: B; Three: z

All the best
Dario

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Gordon Shannon 2010-03-13 01:19:44 Re: unexplained autovacuum to prevent wraparound
Previous Message Harry Gold 2010-03-13 00:24:33 How to remove superuser