Thread: user defined C-lang pg function bug

user defined C-lang pg function bug

From
"James Moss"
Date:
I could use a helpful suggestion or two as to why the following is
occuring or more to the matter, how I might work around it.  Certainly
appears to be a bug or some sort of misunderstanding on my part.

This has been tested on FreeBSD/i386 5.4 and postgres 8.1.3 as well as
Linux (2.4 kernel) and postgres 8.1.5.

Below is the issue:

CREATE OR REPLACE FUNCTION pg_test(text) RETURNS integer
    AS '/usr/local/lib/postgresql/pg_test', 'pg_test'
LANGUAGE C STRICT;

PG_FUNCTION_INFO_V1(pg_test);
Datum pg_test(PG_FUNCTION_ARGS) {
    text *a = PG_GETARG_TEXT_P(0);
    ereport(NOTICE,(errmsg("incoming text: %s", VARDATA(a))));
    PG_RETURN_INT32(1);
}

CREATE OR REPLACE FUNCTION pg_test(text) RETURNS integer
    AS '/usr/local/lib/postgresql/pg_test', 'pg_test'
LANGUAGE C STRICT;

postgres=> select pg_test('HELLO WORLD');
NOTICE:  incoming text: HELLO WORLD
 pg_test
---------
       1
(1 row)

postgres=> select pg_test('STRANGE WORLD');
NOTICE:  incoming text: STRANGE WORLD4
 pg_test
---------
       1
(1 row)

postgres=> select pg_test('HELLO WORLD');
NOTICE:  incoming text: HELLO WORLDLà4
 pg_test
---------
       1
(1 row)

The incoming text indicates there are extraneous characters making
there way in somehow.

James

Re: user defined C-lang pg function bug

From
Tom Lane
Date:
"James Moss" <jpmoss@gmail.com> writes:
> I could use a helpful suggestion or two as to why the following is
> occuring or more to the matter, how I might work around it.  Certainly
> appears to be a bug or some sort of misunderstanding on my part.

The content of a text datum is not guaranteed null-terminated, hence
you can't just take VARDATA(a) as being a C string.  The cleanest way
to convert to C string if you need to is to call textout() --- look
around in the sources for examples to copy.

            regards, tom lane