Re: Re: Where is the char and varchar length in pg_catalog for function input variables - Mailing list pgsql-general

From David Johnston
Subject Re: Re: Where is the char and varchar length in pg_catalog for function input variables
Date
Msg-id 01d101cd8bad$49d96740$dd8c35c0$@yahoo.com
Whole thread Raw
In response to Re: Where is the char and varchar length in pg_catalog for function input variables  (jam3 <jamorton3@gmail.com>)
Responses Re: Re: Where is the char and varchar length in pg_catalog for function input variables
List pgsql-general
>
> How does postgres figure this out to throw the error msg?
>
>
> select test1('this is way way longer than 10 characters','this is way way
way
> way way way way way way way way way longer than 20 characters')
>
> ERROR:  value too long for type character(10)
> CONTEXT:  SQL statement "insert into test_table values ($1, $2)"
> PL/pgSQL function "test1" line 3 at SQL statement
>
> ********** Error **********
>
> ERROR: value too long for type character(10)
>

When it goes to execute:

INSERT INTO test_table ('this is way way ...', 'this is way way way...')

The char(10) type definition for test_table.column1 is too short to hold the
supplied value (stored in $1 in the function) and throws an error.

The length of $1 and $2 inside the function are however long the input
values are because they ignore the length specifier on the function call
types.

If you want to guarantee that the INSERT will work you would need to write:

INSERT INTO test_table VALUES ( $1::char(10), $2::varchar(20) )

This tells PostgreSQL to truncate the supplied value at whatever specified
length is noted; the same as writing substring($1, 1, 10)::char or
substring($1, 1, 20)::varchar though whether "char" and "varchar" differ in
their behavior in this respect I do not know.  It is generally not
recommended to use "char"

David J.







pgsql-general by date:

Previous
From: Scott Marlowe
Date:
Subject: Re: Would my postgresql 8.4.12 profit from doubling RAM?
Next
From: "Kevin Grittner"
Date:
Subject: Re: Re: Where is the char and varchar length in pg_catalog for function input variables