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: Handling Numeric Datums in C
Date: 2010-02-11 13:13:44
Message-ID: F4E6B1FF-8950-4B8E-85C9-85C6DD85D95D@solfertje.student.utwente.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

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);
HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(1);

Datum base, scale, exponent;
Datum result;
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...

Regards,

Alban Hertroys

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

!DSPAM:737,4b74028910442077341801!

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alban Hertroys 2010-02-11 13:16:55 Fwd: Handling Numeric Datums in C
Previous Message Pavel Stehule 2010-02-11 12:27:53 Re: Inserting exported bytea value