Re: add, subtract bool type

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jeff Davis <list-pgsql-general(at)dynworks(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: add, subtract bool type
Date: 2001-08-22 14:21:50
Message-ID: 3550.998490110@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jeff Davis <list-pgsql-general(at)dynworks(dot)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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2001-08-22 14:34:52 Re: problems transfering databases
Previous Message jose 2001-08-22 13:21:49 SELECT FOR UPDATE