Automatic truncation of character values & casting to the type of a column type - Mailing list pgsql-general

From Justin Bailey
Subject Automatic truncation of character values & casting to the type of a column type
Date
Msg-id a45dff840912161649v17f7c8b7ra4af624c510ddd4f@mail.gmail.com
Whole thread Raw
Responses Automatic truncation of character values & casting to the type of a column type  (Justin Bailey <jgbailey@gmail.com>)
Re: Automatic truncation of character values & casting to the type of a column type  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-general
Greetings! I am trying to avoid the old problem of inserting a 40
character string into a 20 character field. However, I'd like to avoid
hard-coding the acceptable length (20). Is there a way to say "cast to
the same type as a given column"? E.g., if I have tables Long and
Short:

  CREATE TABLE Long (longCol varchar(40) )
  CREATE TABLE Short (shortCol varchar(20) )

And this data:

   INSERT INTO Long VALUES ('FOOBAR'), ('BAZ'),
(CAST('2314J1L234J21LK342JKL32J32KL4J123LK4J13L4' AS VARCHAR(40)))

Can make values inserted into shortCol have a maximum length of 20
without hard-coding that value? Something like:

  INSERT INTO Short (ShortCol)
    (SELECT CAST(Long.longCol as Short.shortCol) FROM LONG)

I am using postgres 8.2.

Clearly this is a toy example. In the real world, I insert or update
values in my target table using a stored procedure. I want to
future-proof my stored procedure against the column lengths on the
target table changing. Otherwise, I have to update my sproc with new
lengths if the table ever changes. I have tried using the PL/PGSQL
feature where types can be "copied" in a declaration:

  DECLARE
     myVal Short.shortCol%TYPE;
  ...

But I can still put values which are too long into that variable, so
it doesn't help me. Sadly, using the same syntax in a CAST fails in
various ways:

  UPDATE Short SET shortCol = CAST(myVal AS Short.shortCol) -- schema
"Short" does not exist error
  UPDATE Short SET shortCol = CAST(myVal AS Short.shortCol%TYPE) -- syntax error
  UPDATE Short SET shortCol = CAST(myVal AS (Short).shortCol) -- syntax error

Thanks in advance for any advice

Justin

pgsql-general by date:

Previous
From: Christine Penner
Date:
Subject: Server Requirements
Next
From: Justin Bailey
Date:
Subject: Automatic truncation of character values & casting to the type of a column type