Skip site navigation (1) Skip section navigation (2)

Casting INT4 to BOOL...

From: Sean Chittenden <chitt(at)speakeasy(dot)net>
To: PostgreSQL-patches <pgsql-patches(at)postgresql(dot)org>
Subject: Casting INT4 to BOOL...
Date: 2004-10-10 06:27:39
Message-ID: 7B9F6E6C-1A85-11D9-BF1B-000A95C705DC@speakeasy.net (view raw or flat)
Thread:
Lists: pgsql-patches
Is there any reason why the backend doesn't cast an unquoted integer to 
a boolean value?

test=> SELECT 1::BOOL;
ERROR:  cannot cast type integer to boolean
test=> SELECT '1'::BOOL;
  bool
------
  t
(1 row)

Time: 2.478 ms

It doesn't add anything to the grammar and would make life peachy for 
Qt users.  In Qt, to get around this, I end up doing one of two things:

QSqlQuery q(db);
q.prepare("SELECT '?'::BOOL");
q.bindValue(0, true);
q.exec();

Or I'll do something even more grotty like:

q.prepare("SELECT CASE ?::INT WHEN 0 THEN FALSE ELSE TRUE END");

One could argue that it's a bug in Qt in that it doesn't quote the 
value sent to the backend like it does strings, but, since the backend 
already handles unquoted integers, it seems like it'd be trivial to 
setup a cast.  On installs that use my software, I have to work around 
it with:

CREATE FUNCTION int4_to_bool(INT) RETURNS BOOL AS 'BEGIN IF $1 THEN 
RETURN TRUE; ELSE RETURN FALSE; END IF; END;' LANGUAGE 'plpgsql' 
IMMUTABLE;
CREATE CAST (INT AS BOOL) WITH FUNCTION int4_to_bool(INT) AS ASSIGNMENT;

But that's not something that is supported by default.  Is there any 
reason this hasn't been added yet?  "if (1)" and "if (0)" are 
conditional constructs that are accepted in every language that I can 
think of (even MUMPs *hopes no one remembers/has to use that 
language*).  Could someone apply the attached patch (the C version of 
the above) if there are no glaring reasons not to?  It would make the 
lives of Qt programmers *much* more pleasant.  Thanks in advance.  -sc

test=> SELECT 1::BOOL, 0::BOOL, 42::BOOL;
  bool | bool | bool
------+------+------
  t    | f    | t
(1 row)


Attachment: patch.txt
Description: text/plain (2.6 KB)

Responses

pgsql-patches by date

Next:From: Reini UrbanDate: 2004-10-10 12:42:43
Subject: Re: cypg.dll, libpq_a, initdb max_connections 60
Previous:From: Sean ChittendenDate: 2004-10-10 06:24:21
Subject: Slightly better testing for pg_ctl(1)'s -w...

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group