0

I have a user-defined type mytype :

CREATE TYPE mytype AS (
    timestamps timestamp[], 
    last integer
);

I want to access values in timestamps field using C function. Here is what I have written :

#include "postgres.h"
#include "fmgr.h"
#include "executor/executor.h"
#include "datatype/timestamp.h"


#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

PG_FUNCTION_INFO_V1(testfunc);

Datum
testfunc(PG_FUNCTION_ARGS) {
    bool isnull;
    HeapTupleHeader  at = PG_GETARG_HEAPTUPLEHEADER(0);
    Datum dt = GetAttributeByName(at, "timestamps", &isnull);

    Timestamp ** tts = (Timestamp **) DatumGetPointer(dt);

    PG_RETURN_DATUM(**tts);
}

SQL reference :

CREATE OR REPLACE FUNCTION testfunc(mytype) RETURNS timestamp AS 'path/to/library.so', 'testfunc' LANGUAGE C STRICT;

Now I am getting garbage result when I am trying to test:

postgres=# SELECT testfunc('("{""2017-01-11 00:00:00"", NULL}", 10)');
        testfunc        
---------------------------
 2000-01-01 00:00:00.00001
(1 row)

1 Answer 1

1

Look at the PostgreSQL source code to see how to handle array arguments.

Your code should look somewhat like this:

HeapTupleHeader at = PG_GETARG_HEAPTUPLEHEADER(0);
Datum dt = GetAttributeByName(at, "timestamps", &isnull);
ArrayType *ts = DatumGetArrayTypeP(dt);
Timestamp *timestamps = (Timestamp *) ARR_DATA_PTR(ts);

This is not complete; you might want to add checks for NULL, if the array has the expected number of dimensions and similar.

Sign up to request clarification or add additional context in comments.

2 Comments

This is not working, perhaps because it is expecting first argument to be timestamp[] type but actually is a composite-type argument mytype. Also this page says that for composite-type HeapTupleHeader should be used.
Argh, I forgot that it is a user-defined type. I have fixed the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.