Thread: PQresult() return value not very handy...

PQresult() return value not very handy...

From
"Peter de Vroomen"
Date:
Hi,

For NULL fields in a record, PQresult returns an empty string. This is not
very usefull, as it means I will have to check the resulting string for
empty AND check for errors retrieving the value, something like:

    m_bField1IsNull = false;
    pszValue = PQresult( m_Result, nTuple, 0 );
    if( pszValue == NULL )
    {
        return( false );
    }
    if( pszValue[0] == '\0' )
    {
        if( PQgetisnull( m_Result, nTuple, 0 ))
        {
            m_bField1IsNull = true;
        }
    }
    strcpy( m_szField1, pszValue );

I have to issue 2 if-statements, one to check for error, one to check for
NULL. I have to do this for EVERY field that could be NULL, even if the
field is definately not NULL. The call to PQgetisnull is just wasted CPU
time.

It would have been better if PQresult() would return NULL when an error
occurs and also return NULL when the field is NULL. In that case my code
would become the following:

    m_bField1IsNull = false;
    pszValue = PQresult( m_Result, nTuple, 0 );
    if( pszValue == NULL )
    {
        if( PQgetisnull( m_Result, nTuple, 0 ))
        {
            m_bField1IsNull = true;
            strcpy( m_szField1, "" );
        }
        else
        {
            return( false );
        }
    }
    else
    {
        strcpy( m_szField1, pszValue );
    }

In this case, the function PQgetisnull would ONLY be called if there was a
possibility that the field actually was NULL.

Any chance that this will be changed in the future? I expect that these
kinds of things can be done throughout the libpq C API (I am just beginning
to use it, so I wouldn't actually know :-)), so it would be nice if someone
would do some optimizations like this one :-).

Please don't flame me on bugs/typing errors in the above code examples, they
are not real code, I just typed them in to explain the general idea.

Regards,

Peter



Re: PQresult() return value not very handy...

From
Tom Lane
Date:
"Peter de Vroomen" <peterv@geenspam_jaytown.com> writes:
> It would have been better if PQresult() would return NULL when an error
> occurs and also return NULL when the field is NULL.

But field-is-NULL is not an error condition.

There's some merit in your suggestion, but it's not as obvious a win
as you seem to think.  The caller really needs to distinguish three
cases (error, NULL field value, normal case) and there's no clean
way to do so with only one return value.

> Any chance that this will be changed in the future?

Not much; it'd break too much existing code.  And PQgetisnull is not
so slow that anyone's going to get very excited about removing it
from the normal code path...

            regards, tom lane