Re: Re: Where is the char and varchar length in pg_catalog for function input variables

From: "David Johnston" <polobo(at)yahoo(dot)com>
To: "'jam3'" <jamorton3(at)gmail(dot)com>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: Re: Where is the char and varchar length in pg_catalog for function input variables
Date: 2012-09-05 21:27:44
Message-ID: 01d101cd8bad$49d96740$dd8c35c0$@yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Kevin Grittner 2012-09-05 21:41:53 Re: Re: Where is the char and varchar length in pg_catalog for function input variables
Previous Message Scott Marlowe 2012-09-05 21:10:14 Re: Would my postgresql 8.4.12 profit from doubling RAM?