#include "postgres.h"
#include "fmgr.h"
#include "utils/builtins.h"
#include "utils/array.h"
#include "catalog/pg_type.h"
PG_MODULE_MAGIC;
#define ARRPTR(x) ( (int64 *) ARR_DATA_PTR(x) )
#define ARRNELEMS(x) ArrayGetNItems(ARR_NDIM(x), ARR_DIMS(x))
PG_FUNCTION_INFO_V1(test_inc);
Datum
test_inc(PG_FUNCTION_ARGS)
{
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
int n = ARRNELEMS(a);
int nbytes = ARR_OVERHEAD_NONULLS(1) + sizeof(int64) * n;
ArrayType *r = (ArrayType *) palloc0(nbytes);
SET_VARSIZE(r, nbytes);
ARR_NDIM(r) = 1;
r->dataoffset = 0; // marker for no null bitmap
ARR_ELEMTYPE(r) = INT8OID;
ARR_DIMS(r)[0] = n;
ARR_LBOUND(r)[0] = 1;
int64 *ad = ARRPTR(a);
int64 *rd = ARRPTR(r);
ereport(WARNING,
errcode(ERRCODE_WARNING),
errmsg("Before loop"));
for (int i = 0; i < n; i++) {
rd[i] = ad[i] + 1;
}
ereport(WARNING,
errcode(ERRCODE_WARNING),
errmsg("After loop"));
PG_RETURN_POINTER(r);
}
Last query runs in 6s. Removing rd[i] = ad[i] + 1;
line makes code runs in 0.6s.
Also, looking at warning messages I see that execution stuck somewhere after the loop, and not inside the loop..