2013-11-14 34 views
3

有人能給我一個暗示,在這個開始的嘗試中定製函數嗎?PostgreSQL C函數暗示

我需要有兩個參數,一個varchar和Unix時間戳(一個整數) 我花3小時以下幾行,且該結果

查詢測試可以選擇構造查詢*來自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; 
} 

回答

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的contrib模塊。所有爲你準備的 - makefiles,一些簡單的模板 - https://github.com/postgres/postgres/tree/master/contrib

+0

Pavel你在這裏發佈的函數hqo如果ARG是一個varchar,可以完成它?我的意思是arg [0] = PG_GETARG_TEXTP(0);對我不起作用.. 它怎麼能被管理? luca –

+0

可以有任何數據類型 - 你得到了什麼錯誤?它應該是「text * doct = PG_GETARG_TEXT_P(0);」請參閱postgresql/contrib/xml2/xslt_proc.c –