In Postgres C extension development, the argument of function is a tuple, how to iterate all its attributes
1
vote
0
answers
81
views
This is my .c file
Datum show_line(PG_FUNCTION_ARGS)
{
/* Get Input*/
HeapTupleHeader tup_hdr;
TupleDesc tup_desc;
Oid tupType;
int32 tupTypmod;
bool isNull;
// int tuplen;
// bool *nulls;
int i;
tup_hdr = PG_GETARG_HEAPTUPLEHEADER(0);
elog(NOTICE, "Get tup_hdr");
tupType = HeapTupleHeaderGetTypeId(tup_hdr);
tupTypmod = HeapTupleHeaderGetTypMod(tup_hdr);
tup_desc = lookup_rowtype_tupdesc(tupType, tupTypmod);
// tup_desc = lookup_rowtype_tupdesc(
// HeapTupleHeaderGetTypeId(tup_hdr),
// HeapTupleHeaderGetTypMod(tup_hdr));
Datum value = GetAttributeByNum(tup_hdr, 5, &isNull);
if (isNull)
{
elog(NOTICE, "Get value is NULL");
}
else
{
elog(NOTICE, "Get value %f", DatumGetFloat8(value));
}
elog(NOTICE, "Get tup_desc");
elog(NOTICE, "get tupType %d", tupType);
elog(NOTICE, "get tupTypmod %d", tupTypmod);
if (tup_desc == NULL)
{
elog(NOTICE, "tup_desc is NULL");
PG_RETURN_INT32(0);
}
int natts = tup_desc->natts;
elog(NOTICE, "Get natts %d", natts);
for (i = 0; i natts; i++)
{
Form_pg_attribute attr;
char *name;
elog(NOTICE, "Get attr %d, Step 1", i);
attr = TupleDescAttr(tup_desc, i);
elog(NOTICE, "Get attr %d, Step 2", i);
name = NameStr(attr->attname);
elog(NOTICE, "Attribute %d: %s", i, name);
}
PG_RETURN_INT32(0);
}
this is SQL file
CREATE
OR REPLACE FUNCTION show_line(iris) RETURNS int AS 'MODULE_PATHNAME',
'show_line' LANGUAGE C STRICT;
I can successfully compile and install it in Postgres.
But when execute it, the psql will crash
test_db=# SELECT
show_line(iris) as target
from
iris
limit
4;
NOTICE: Get tup_hdr
NOTICE: Get value 0.000000
NOTICE: Get tup_desc
NOTICE: get tupType 24617
NOTICE: get tupTypmod -1
SSL SYSCALL error: EOF detected
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?>
It seems it crashed when run in
int natts = tup_desc->natts;
I follow the function in example
composite_to_json
in src/backend/utils/adt/json.c
Asked by Lingze Zeng
(11 rep)
Dec 22, 2023, 09:57 AM