Search Postgresql Archives

Fwd: Handling Numeric Datums in C

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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!



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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux