Re: BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: jiangshan(dot)liu(at)tju(dot)edu(dot)cn
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results
Date: 2023-03-26 15:41:05
Message-ID: 2912450.1679845265@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

PG Bug reporting form <noreply(at)postgresql(dot)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

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Tom Lane 2023-03-26 17:44:41 Re: BUG #17858: ExecEvalArrayExpr() leaves uninitialised memory for multidim array with nulls
Previous Message David G. Johnston 2023-03-26 15:19:49 Re: BUG #17869: Inconsistency between PL/pgSQL Function Parameter Handling and SQL Query Results