Re: [HACKERS] Issue on C function that reads int2[] (using "int2vector")

2015-12-01 Thread Rodrigo Hjort
2015-11-30 0:39 GMT-02:00 Tom Lane:

> Rodrigo Hjort writes:
> > I created a custom C function with this signature:
>
> > CREATE FUNCTION calculate_hash(numbers int2[])
> > RETURNS int8
> > AS 'MODULE_PATHNAME', 'pg_calculate_hash'
> > LANGUAGE C
> > IMMUTABLE STRICT;
>
> > And here is the function source code (inspired in codes I found in
> > src/backend/utils/adt/int.c):
>
> > PG_FUNCTION_INFO_V1(pg_calculate_hash);
> > Datum
> > pg_calculate_hash(PG_FUNCTION_ARGS)
> > {
> >   int2vector *int2Array = (int2vector *) PG_GETARG_POINTER(0);
>
> Nope.  int2vector is not the same as int2[].  It might occasionally seem
> to work, but in general it's not the same type.  And this particular
> coding won't work at all on on-disk int2[] data, because it doesn't
> account for toasting.
>
> regards, tom lane
>


Thanks for the advice, Tom.

I ended up with the following code, which worked successfully:

#define ARRPTR16(x)   ((uint16 *) ARR_DATA_PTR(x))
#define ARRNELEMS(x)  ArrayGetNItems(ARR_NDIM(x), ARR_DIMS(x))
#define ARRISEMPTY(x) (ARRNELEMS(x) == 0)

PG_FUNCTION_INFO_V1(pg_calculate_hash);
Datum
pg_calculate_hash(PG_FUNCTION_ARGS)
{
  ArrayType *a = PG_GETARG_ARRAYTYPE_P_COPY(0);
  unsigned int i, qtd, tipo, nums[MAX_NUMEROS];
  uint16 *da;

  qtd = ARRNELEMS(a);
  tipo = ARR_ELEMTYPE(a);
  da = ARRPTR16(a);

  elog(DEBUG1, "pg_calculate_hash(qtd=%d, tipo=%d)", qtd, tipo);

  [...]

  pfree(a);
  PG_RETURN_INT64(hash);
}


Regards,

Rodrigo Hjort


Re: [HACKERS] Issue on C function that reads int2[] (using "int2vector")

2015-11-29 Thread Tom Lane
Rodrigo Hjort  writes:
> I created a custom C function with this signature:

> CREATE FUNCTION calculate_hash(numbers int2[])
> RETURNS int8
> AS 'MODULE_PATHNAME', 'pg_calculate_hash'
> LANGUAGE C
> IMMUTABLE STRICT;

> And here is the function source code (inspired in codes I found in
> src/backend/utils/adt/int.c):

> PG_FUNCTION_INFO_V1(pg_calculate_hash);
> Datum
> pg_calculate_hash(PG_FUNCTION_ARGS)
> {
>   int2vector *int2Array = (int2vector *) PG_GETARG_POINTER(0);

Nope.  int2vector is not the same as int2[].  It might occasionally seem
to work, but in general it's not the same type.  And this particular
coding won't work at all on on-disk int2[] data, because it doesn't
account for toasting.

regards, tom lane


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers