Pages

Wednesday, August 27, 2008

default parameters for PL functions

Hello

I completed one task - defaults for PL functions. Using is simple - it is same as Firebird's 2.x defaults.
postgres=# create or replace function x1(int = 1,int = 2,int= 3)
returns int as $$
select $1+$2+$3;
$$ language sql;
CREATE FUNCTION
postgres=# select x1();
x1
----
6
(1 row)

postgres=# select x1(10);;
x1
----
15
(1 row)

postgres=# select x1(10,20);
x1
----
33
(1 row)

postgres=# select x1(10,20,30);
x1
----
60
(1 row)
This is first step before named parameters feature - and less controversy. Second step will be difficult - there are two opinions about named parameter's syntax: variant a) using Oracle's syntax name => expression and variant b) use own syntax based on keyword "AS" expression AS name. I prefer variant @a - I thing so it's more readable (SQL use AS for labeling). Variant @b is safe from compatibility views. There was discussion on pg_hackers - without any conclusion. So I hope so at least defaults will be committed.

bye
Pavel

3 comments:

  1. I thought PL functions already have named parameters, as the parameter "i" in this example from the docs:

    CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
    BEGIN
    RETURN i + 1;
    END;
    $$ LANGUAGE plpgsql;

    I take it you mean something different?

    ReplyDelete
  2. There are named parameters and named parameters. First, you can use it when you create function - it is in your sample (and postgres supports it). Second - you can use names when you call function - this feature isn't supported yet.

    example:
    select increment( i => 10 );

    ReplyDelete
  3. Great feature!!!
    Thanks a lot, I hope this patch will be commited.

    ReplyDelete