Re: Casting to varchar

From: Alvaro Herrera <alvherre(at)commandprompt(dot)com>
To: "Raymond O'Donnell" <rod(at)iol(dot)ie>
Cc: Scott Ribe <scott_ribe(at)killerbytes(dot)com>, Postgresql General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Casting to varchar
Date: 2007-05-04 20:48:41
Message-ID: 20070504204841.GD26685@alvh.no-ip.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Raymond O'Donnell wrote:
> On 04/05/2007 21:34, Scott Ribe wrote:
>
> >Just discovered (the hard way) that casting a boolean column ::varchar
> >doesn't work. I assume I can add a function somewhere that will define a
> >default cast for this? Are there any other standard types that can't be
> >cast
>
> I just use something like this:
>
> create or replace function bool2str(TheValue boolean)
> returns varchar as
> $$
> begin
> if TheValue then
> return 'true';
> else
> return 'false';
> end if;
> end;
> $$
> language plpgsql stable;

To complete the example,

alvherre=# create cast (boolean as varchar) with function bool2str(bool);
CREATE CAST

alvherre=# select 't'::boolean::varchar;
varchar
---------
true
(1 fila)

Though I'd mark the function immutable rather than stable.

alvherre=# select 'f'::boolean::varchar;
varchar
---------
false
(1 fila)

alvherre=# select '0'::boolean::varchar;
varchar
---------
false
(1 fila)

alvherre=# select '123'::boolean::varchar;
ERROR: invalid input syntax for type boolean: "123"

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Ribe 2007-05-04 20:50:29 Re: Casting to varchar
Previous Message Alvaro Herrera 2007-05-04 20:46:37 Re: Casting to varchar