【问题标题】:PostgreSQL C function suggestionPostgreSQL C 函数建议
【发布时间】:2013-11-27 22:53:03
【问题描述】:

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

我需要用 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;
}

【问题讨论】:

    标签: c postgresql


    【解决方案1】:

    你错过了一个 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 贡献模块。一切都为你准备好了——makefile,一些简单的模板——https://github.com/postgres/postgres/tree/master/contrib

    【讨论】:

    • Pavel 你在这里发布的函数 hq​​o 如果 ARG 是 varchar 可以做到吗?我的意思是 arg[0] = PG_GETARG_TEXTP(0);对我不起作用..如何管理?卢卡
    • 可以有任何数据类型——你遇到了什么错误?它应该是“文本 *doct = PG_GETARG_TEXT_P(0);”见 postgresql/contrib/xml2/xslt_proc.c
    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多