3

有人可以在这个自定义功能的初步尝试中给我一个提示吗?

我需要使用 2 个参数、一个 varchar 和一个 unix 时间戳(一个整数)来构造查询,我用下面的几行花了 3 个小时和这个结果

查询测试可以是 select * from pdc_posot_cf_anno('MRDDCU83C12C433F',2012); 我只是想构造一个正确的 SQL 查询来传递给 SPI_exec。

非常感谢。

CREATE FUNCTION pdc_posot_cf_anno(varchar,integer)
RETURNS integer
AS 'pdc','posot_cf_anno'
LANGUAGE C STABLE STRICT;

Datum
posot_cf_anno(PG_FUNCTION_ARGS) {
  char timestring[1024] = "";
  char qanno[1024];
  Timestamp t;
  time_t time = 0;
  int tempo;
  Datum td;
  sprintf(timestring,"%d-01-01",PG_GETARG_INT32(1));
  elog(INFO, "tutto bene %s !",timestring);
  t = DatumGetTimestamp(DirectFunctionCall2(to_timestamp,
                        CStringGetTextDatum(timestring),
                        CStringGetTextDatum("YYYY-MM-DD")));

  sprintf(qanno,"SELECT DISTINCT o.idot FROM sit.otpos o "
                "WHERE btrim(o.codfis) = %s AND to_timestamp(validita) <= %s ORDER BY o.idot;",
          PG_GETARG_CSTRING(0), t);
  elog(INFO, "QUERY %s !",qanno);
//   SPI_connect();
//   res = SPI_exec(qanno,0);

  return 0;
}
4

1 回答 1

3

你错过了一个 C 函数签名和魔法信息

#include "postgres.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(foo);

Datum foo(PG_FUNCTION_ARGS);

Datum 
foo(PG_FUNCTION_ARGS)
{
    int ret;
    Datum args[1];
    Oid argtypes[1] = { INT4OID };
    Datum result;
    bool isnull;

    SPI_connect();

    args[0] = PG_GETARG_INT32(0);

    /* ensure expected result type by casting */
    ret = SPI_execute_with_args("SELECT ($1 + 10)::int", 
                                   1, argtypes, args, NULL,
                                   true, 1);

    Assert(SPI_processed == 1);

    result = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
    Assert(!isnull);

    SPI_finish();

    PG_RETURN_DATUM(result);
}

最好的开始是温和修改 PostgreSQL 贡献模块。一切都为你准备好了 - makefiles,一些简单的模板 - https://github.com/postgres/postgres/tree/master/contrib

于 2013-11-14T20:15:09.777 回答