Re: add, subtract bool type - Mailing list pgsql-general

From Tom Lane
Subject Re: add, subtract bool type
Date
Msg-id 3550.998490110@sss.pgh.pa.us
Whole thread Raw
In response to add, subtract bool type  (Jeff Davis <list-pgsql-general@dynworks.com>)
Responses Re: add, subtract bool type
List pgsql-general
Jeff Davis <list-pgsql-general@dynworks.com> writes:
> I made some simple functions that create the operators + and - for any
> combination of int4's and bool's.

> My question is two-part:
> 1) Is this a sane approach?

It'd be less work if you made a bool->int conversion function and relied
on the regular integer operators.  Safer, too: this way is likely to
cause the system to accept queries that do things you didn't intend.

In fact, I'd personally want the conversion to not be applied by
default, which means you *shouldn't* call the conversion function int4().
Functions named after the destination type are assumed to represent
implicit type coercions, and will be applied without being mentioned
explicitly.  OTOH, if you don't care about type safety, you could
achieve the same result as your operator set with just such an implicit
coercion function:

test71=# select 't'::bool + 44;
ERROR:  Unable to identify an operator '+' for types 'bool' and 'int4'
        You will have to retype this query using an explicit cast

test71=# select 't'::bool + 't'::bool;
ERROR:  Unable to identify an operator '+' for types 'bool' and 'bool'
        You will have to retype this query using an explicit cast

test71=# create function int4(bool) returns int4 as '
test71'# select case when $1 then 1 else 0 end;' language 'sql';
CREATE

test71=# select 't'::bool + 44;
 ?column?
----------
       45
(1 row)

test71=# select 't'::bool + 't'::bool;
 ?column?
----------
        2
(1 row)

test71=#

But as I said, I'd prefer to name the function something else (maybe
"integerize") and have to invoke it explicitly.  I'm an old Pascal
programmer and believe strongly that bool and int ought not be
considered interchangeable: that masks too many programming errors.

> 2) Might enough other people find a use that I should make a
> contribution somewhere (and would it be appropriate to send it to
> pgsql-hackers or pgsql-patches)?

As you can see, there's not a lot to it, at least not for low-volume
applications.  If you expected to invoke integerize() zillions of
times, it might be worth the trouble to prepare a C-coded version of
it.  That would be worth contributing, since other people have asked
for this same functionality.  But then you'd have to get people to
agree on a name for the function, and believe me that'll be the
hardest part ;-)

            regards, tom lane

pgsql-general by date:

Previous
From: jose
Date:
Subject: SELECT FOR UPDATE
Next
From: Tom Lane
Date:
Subject: Re: problems transfering databases