Thread: varchar/name casts

varchar/name casts

From
Peter Eisentraut
Date:
With this query you can view all casts involving varchar:

SELECT castsource::regtype, casttarget::regtype, castfunc::regprocedure, 
castcontext FROM pg_cast WHERE 'varchar'::regtype IN (castsource, casttarget) 
ORDER BY 1, 2;

Note that varchar mostly "borrows" the cast functions from the text type.  The 
exception is that there is a separate set of SQL-level functions for casting 
between name and varchar and vice versa.  But these are actually matched to 
the same C-level functions as the casts between text and name (name_text() 
and text_name()).

Does anyone recall a reason for this special case or is it just another dark 
area in the casting maze?  If the latter, I would like to remove the extra 
functions and redefine the casts between varchar and name to use the 
SQL-level casting functions for the text type.


Re: varchar/name casts

From
Tom Lane
Date:
Peter Eisentraut <peter_e@gmx.net> writes:
> Note that varchar mostly "borrows" the cast functions from the text type.  The 
> exception is that there is a separate set of SQL-level functions for casting 
> between name and varchar and vice versa.  But these are actually matched to 
> the same C-level functions as the casts between text and name (name_text() 
> and text_name()).

> Does anyone recall a reason for this special case or is it just another dark 
> area in the casting maze?

I think the idea was to support the functional casting notation, viz
"varchar(name_col)".  However it seems we've broken that already for
most of the other cases; and in any case it never worked very nicely
for varchar because "varchar" is a reserved word, so you have to
quote :-(

As a historical note, in 7.3 (the first release with a pg_cast catalog)
your query gives just
   castsource     |    casttarget     |        castfunc         | castcontext 
-------------------+-------------------+-------------------------+-------------name              | character varying |
"varchar"(name)        | itext              | character varying | -                       | icharacter         |
charactervarying | -                       | icharacter varying | name              | name(character varying) |
icharactervarying | text              | -                       | icharacter varying | character         | -
          | i
 
(6 rows)

So it seems the cross-category casts for varchar got accreted on later,
rather than it being a case of things having disappeared.
        regards, tom lane