Re: BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results - Mailing list pgsql-bugs

From Tom Lane
Subject Re: BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results
Date
Msg-id 2912450.1679845265@sss.pgh.pa.us
Whole thread Raw
In response to BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results  (PG Bug reporting form <noreply@postgresql.org>)
List pgsql-bugs
PG Bug reporting form <noreply@postgresql.org> writes:
> However, when passing fixed-length character types as parameters in PL/pgSQL
> functions, the behavior seems to be different. The documentation states that
> parenthesized type modifiers are discarded by CREATE FUNCTION, meaning that
> CREATE FUNCTION foo (varchar(10)) is the same as CREATE FUNCTION foo
> (varchar) [2].

I think you've misunderstood that.  Type modifiers are not applied
to function parameters.  Thus, this function declaration:

> CREATE OR REPLACE FUNCTION test(param CHAR) RETURNS TEXT AS $$

avers that the function takes any CHAR-type value regardless of length.
Had you written, say,

regression=# SELECT * FROM test('abc'::char);
NOTICE:  a
 test 
------
 a
(1 row)

the cast operation would enforce the "defaults to length 1" business;
but the function itself does not.

Generally speaking this is desirable because you wouldn't want to have
to write a different copy of test() for each string length you might
want to use it with.  If you are really intent on getting the other
behavior you could use a domain:

regression=# create domain c1 as char(1);
CREATE DOMAIN
regression=# CREATE OR REPLACE FUNCTION test(param c1) RETURNS TEXT AS $$
  BEGIN
    RAISE NOTICE '%', param;
    RETURN param;
  END; 
$$ LANGUAGE plpgsql;
CREATE FUNCTION
regression=# SELECT * FROM test('abc');
ERROR:  value too long for type character(1)
regression=# SELECT * FROM test('abc'::char);
NOTICE:  a
 test 
------
 a
(1 row)

This happens because there is no concept of a non-typmod-enforcing
cast to a domain.

            regards, tom lane



pgsql-bugs by date:

Previous
From: "David G. Johnston"
Date:
Subject: Re: BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results
Next
From: Tom Lane
Date:
Subject: Re: BUG #17858: ExecEvalArrayExpr() leaves uninitialised memory for multidim array with nulls