Re: understanding Datum -> char * -> Datum conversions

From: Karel Zak <zakkr(at)zf(dot)jcu(dot)cz>
To: ldm(at)apartia(dot)com
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: understanding Datum -> char * -> Datum conversions
Date: 2000-05-24 16:34:48
Message-ID: Pine.LNX.3.96.1000524181519.7481A-100000@ara.zf.jcu.cz
Views: Raw Message | Whole Thread | Download mbox
Thread:
Lists: pgsql-hackers


On Wed, 24 May 2000, Louis-David Mitterrand wrote:

> Hello,
>
> I am learning to programm triggers in C by using the examples and the
> programmer's manual but it's a steep learning curve for a mere perl
> programmer ;-)
>
> What I am trying to do for instance is:
> - read a ::text colum with SPI_getbinval(),
> - convert it to a char*,
> - modify it,
> - convert it back to a Datum,
> - reinsert it into the tuple through SPI_modifytuple,
>
> The conversions involve some pointer magic and casting that I really
> don't grasp.
>
> Also I am trying to read a timestamp with SPI_getbinval and get the
> number of seconds contained. Using DatumGetInt32 doens't seem to do it.
>
> Thanks in advance for your insight, cheers,

Examples:

* Add actual time to column "chtime":

Datum chtime = PointerGetDatum(timestamp_in("now"));
int attnum = SPI_fnumber(tupdesc, "chtime");

rettuple = SPI_modifytuple(CurrentTriggerData->tg_relation,
rettuple, 1, &attnum, &chtime, NULL);

You can use instead "now" SPI_getvalue() .... etc.

* A small complex example:

HeapTuple xxx_trigger()
{
TupleDesc tupdesc;
HeapTuple rettuple = NULL;
int attnum;
char *value;
Datum newdt;

if (!CurrentTriggerData)
elog(ERROR, "XXX: triggers are not initialized");

if (TRIGGER_FIRED_BY_UPDATE(CurrentTriggerData->tg_event)) {
rettuple = CurrentTriggerData->tg_newtuple;
else if (TRIGGER_FIRED_BY_INSERT(CurrentTriggerData->tg_event))
rettuple = CurrentTriggerData->tg_trigtuple;
else if (TRIGGER_FIRED_BY_DELETE(CurrentTriggerData->tg_event))
rettuple = CurrentTriggerData->tg_trigtuple;

tupdesc = CurrentTriggerData->tg_relation->rd_att;

if ( SPI_connect() < 0)
elog(ERROR, "SPI_connect() fail... ");

attnum = SPI_fnumber(tupdesc, "ColumnName");
value = SPI_getvalue(rettuple, tupdesc, attnum);

/* --- add some code for 'value' ---*/

newdt = PointerGetDatum(value);

rettuple = SPI_modifytuple(CurrentTriggerData->tg_relation,
rettuple, 1, &attnum, &newdt, NULL);

SPI_finish();
CurrentTriggerData = NULL;
return(rettuple);
}

.......... it must works :-)

Karel

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Jeff Hoffmann 2000-05-24 16:46:56 Re: [HACKERS] Re: interactive pgsql book
Previous Message Louis-David Mitterrand 2000-05-24 16:26:41 understanding Datum -> char * -> Datum conversions