Fwd: Handling Numeric Datums in C

From: Alban Hertroys <dalroi(at)solfertje(dot)student(dot)utwente(dot)nl>
To: "pgsql-general(at)postgresql(dot)org Forums" <pgsql-general(at)postgresql(dot)org>
Subject: Fwd: Handling Numeric Datums in C
Date: 2010-02-11 13:16:55
Message-ID: C933B683-362B-4D43-B0EC-DC7E19A494DC@solfertje.student.utwente.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I guess it'd be useful to mention what types the different fields are, doh!

Begin forwarded message:

> Hey all,
>
> I'm working on some server-side C code that involves a few calculations on a numeric value. The calculation is along the lines of:
> (numeric) result = (numeric) value * ((int) base ^ (int) power);
>
> What's the usual approach to write functions like these?
>
> This is how far I got:
>
> #include <postgres.h>
> #include <fmgr.h>
> #include <executor/spi.h>
> #include <executor/executor.h>
> #include <utils/numeric.h>
> #include <utils/builtins.h>
>
> PG_FUNCTION_INFO_V1(unit_product__aggregate_state);
>
> Datum
> unit_product__aggregate_state(PG_FUNCTION_ARGS)
> {
> Datum state = PG_GETARG_DATUM(0);

This is a numeric.

> HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(1);
>
> Datum base, scale, exponent;

These are all ints.

> Datum result;

This is a numeric again.

> bool isNull;
>
> base = GetAttributeByName(t, "base", &isNull);
> if (isNull)
> PG_RETURN_NULL();
>
> scale = GetAttributeByName(t, "scale", &isNull);
> if (isNull)
> PG_RETURN_NULL();
>
> exponent = GetAttributeByName(t, "exponent", &isNull);
> if (isNull)
> PG_RETURN_NULL();
>
>
> /* state *= base ^ (scale * exponent) */
> result = DirectFunctionCall2(int4mul, scale, exponent);
> result = DirectFunctionCall2(numeric_power, base, result);
> result = DirectFunctionCall2(numeric_mul, state, result);
>
> PG_RETURN_NUMERIC(result);
> }
>
> But it crashes the server, probably because I'm passing ints where numerics are expected. Is this the right approach at all? And if so, how am I supposed to cast those ints to numerics?
>
> Are there any examples around for dealing with numerics? The stuff in the documentation (http://www.postgresql.org/docs/8.4/interactive/xfunc-c.html) conveniently omits numerics, so I had to dig through doxygen to get as far as I am now...

Alban Hertroys

--
Screwing up is the best way to attach something to the ceiling.

!DSPAM:737,4b74034810441727621217!

In response to

Browse pgsql-general by date

  From Date Subject
Next Message janandith jayawardena 2010-02-11 13:25:06 subscribe
Previous Message Alban Hertroys 2010-02-11 13:13:44 Handling Numeric Datums in C