Fwd: Handling Numeric Datums in C

Поиск
Список
Период
Сортировка
От Alban Hertroys
Тема Fwd: Handling Numeric Datums in C
Дата
Msg-id C933B683-362B-4D43-B0EC-DC7E19A494DC@solfertje.student.utwente.nl
обсуждение исходный текст
Ответ на Handling Numeric Datums in C  (Alban Hertroys <dalroi@solfertje.student.utwente.nl>)
Список 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
thelines 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
atall? 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
doxygento get as far as I am now... 

Alban Hertroys

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


!DSPAM:737,4b74034810441727621217!



В списке pgsql-general по дате отправления:

Предыдущее
От: Alban Hertroys
Дата:
Сообщение: Handling Numeric Datums in C
Следующее
От: "Khin, Gerald"
Дата:
Сообщение: trouble with unique constraint