Re: Can functions return NULL value?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Andrea Austa <aausta(at)athena(dot)polito(dot)it>
Cc: pgsql-interfaces(at)postgresql(dot)org
Subject: Re: Can functions return NULL value?
Date: 2000-05-08 23:37:21
Message-ID: 4456.957829041@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-interfaces

Andrea Austa <aausta(at)athena(dot)polito(dot)it> writes:
> Can a function, written in C, return a NULL value?
> I would like write code like this:

> text * getnull (text * t)
> {
> return NULL;
> }

> but it doesn't work, the backend terminates abnormally.

This will be possible in 7.1 with the new function manager interface.
Right now, it's not possible.

(If your stomach is easily turned, stop reading here.)

There is an incredibly ugly hack for single-argument functions;
if that's the only kind you need to do this for, you're in luck.
A single-argument function implicitly gets a second "bool *"
argument, which on entry tells you whether the argument is NULL,
and on exit tells whether the result is NULL. So:

text * getnull (text * t, bool * isNull)
{
if (*isNull)
{
/* passed argument is NULL, do appropriate thing */
}
else
{
/* normal case here */
}
if (want-to-return-NULL)
{
*isNull = true;
return NULL;
}
else
{
*isNull = false; /* necessary iff arg is NULL */
return appropriate-value;
}
}

Note that you still declare the function to SQL as taking a single
argument; the extra arg only appears at the C level.

This was only meant to support implementation of IS NULL/IS NOT NULL,
which is why it only copes with the single-argument case. 7.1 will
replace this crock with a more reasonable design that passes in a
separate isNull flag for each argument, and also has an isNull flag
the function can set for its result value. See past discussions of
function manager redesign in pghackers archives (last thread was
in late Oct 99).

regards, tom lane

In response to

Responses

Browse pgsql-interfaces by date

  From Date Subject
Next Message Hannu Krosing 2000-05-09 11:54:53 Re: Can functions return NULL value?
Previous Message Andrea Austa 2000-05-08 21:07:15 Can functions return NULL value?