Re: convert binary string to datum - Mailing list pgsql-general

From Gregory Stark
Subject Re: convert binary string to datum
Date
Msg-id 87odf3vbb5.fsf@oxford.xeocode.com
Whole thread Raw
In response to Re: convert binary string to datum  (Ron Peterson <ron.peterson@yellowbank.com>)
Responses Re: convert binary string to datum  (Ron Peterson <ron.peterson@yellowbank.com>)
List pgsql-general
"Ron Peterson" <ron.peterson@yellowbank.com> writes:

> Is this a legitimate/blessed way to go about it?
>
> aval = (bytea *)palloc( len + VARHDRSZ );
> VARATT_SIZEP(aval) = len + VARHDRSZ;
> memcpy( VARDATA(aval), myrawdata, len );
> values[0] = PointerGetDatum(aval);
> ...etc
> tuple = heap_formtuple( tupdesc, values, &isNull );

Yes, assuming that your tuple descriptor there does in fact have a varlena
data type in column 1. And normally you would define your own datatype and not
use bytea. Personally I'm not entirely clear why we don't just use void* for
text and bytea though.

Postgres 8.3 has a different macro api here though. If you want to
future-proof your code you could do (put the macro definition somewhere in
your private header file after including postgres.h).

#ifndef SET_VARSIZE
#define SET_VARSIZE(v,l) (VARATT_SIZEP(v) = (l))
#endif

aval = (bytea *)palloc( len + VARHDRSZ );
SET_VARSIZE(aval, len + VARHDRSZ);
memcpy( VARDATA(aval), myrawdata, len );
values[0] = PointerGetDatum(aval);
...etc
tuple = heap_formtuple( tupdesc, values, &isNull );

Also, make sure you use VARSIZE to refer to the size header at all times,
don't refer to it directly. And unless you mark it with storage plain always
detoast it before working with an argument or anything from heap_deform_tuple.
In postgres we normally put pg_detoast_datum() directly into the DatumGetFoo()
and PG_GETARG_FOO_P() macros.


--
  Gregory Stark
  EnterpriseDB          http://www.enterprisedb.com

pgsql-general by date:

Previous
From: "brien colwell"
Date:
Subject: contrib / fuzzystr documentation
Next
From: "Trevor Talbot"
Date:
Subject: Re: can I define own variables?