I'm writing a c-language user defined function for postgresql 9.3.5. I didn't use pl/pgsql or pl/python because part of it needs to be written in C for speed.
The function gets an existing OID as an argument. How can I access & modify the OID data from within the c-language function? I can't find any docs for that!
What I have so far inside the function is just the part that reads the arguments:
#include "postgres.h"
#include "fmgr.h"
PG_MODULE_MAGIC;
Datum tsdb_write_lob(PG_FUNCTION_ARGS) ;
PG_FUNCTION_INFO_V1(tsdb_write_lob);
Datum tsdb_write_lob(PG_FUNCTION_ARGS) {
int16 arg_dataformat = PG_GETARG_INT16(0);
int16 arg_granularity_days = PG_GETARG_INT16(1);
Oid arg_dataoid = PG_GETARG_OID(2);
ereport( INFO, (errcode( ERRCODE_SUCCESSFUL_COMPLETION ),
errmsg("Arguments were: %d, %d, %ld\n",arg_dataformat,arg_granularity_days,arg_dataoid)));
/*TODO:
* open oid (lo_open ?)
* read data
* decompress data
* parse data
* add new data
* compress data
* save to same oid
*/
PG_RETURN_VOID();
}
UPDATE: This seems to be an example:
https://github.com/postgres/postgres/blob/master/src/backend/libpq/be-fsstubs.c
This is an Idea
#include <postgres.h>
#include <utils/rel.h>
#include <utils/array.h>
#include <commands/trigger.h>
#include <executor/spi.h>
PG_MODULE_MAGIC;
Datum tsdb_write_lob(PG_FUNCTION_ARGS) ;
extern SPITupleTable *SPI_tuptable;
PG_FUNCTION_INFO_V1(tsdb_write_lob);
Datum tsdb_write_lob(PG_FUNCTION_ARGS) {
{
int16 arg_dataformat = PG_GETARG_INT16(0);
int16 arg_granularity_days = PG_GETARG_INT16(1);
Oid arg_dataoid = PG_GETARG_OID(2);
char command[128];
if (SPI_ERROR_CONNECT == SPI_connect())
PG_RETURN_VOID();
snprintf(command, sizeof(command), "SELECT lo_open(INV_READ, %d)", arg_dataoid);
if (SPI_OK_SELECT != SPI_execute(command, false, 0))
PG_RETURN_VOID();
.
.
.
/* do loread here the same way by using SPI_execute("SELECT loread ...") */
SPI_finish();
PG_RETURN_VOID();
}
You need to read about SPI_tubtable
pointer to find out how to parse the queries, as well as the whole SPI
Server Programming Interface .
I found a solution, thanks to the pgsql mailing list:
int inv_fd;
Oid arg_dataoid = PG_GETARG_OID(0);
...
//open
inv_fd = DatumGetInt32(DirectFunctionCall2(lo_open, arg_dataoid, Int32GetDatum(INV_READ|INV_WRITE)));
if (inv_fd < 0) {
elog(ERROR, "lo_open: lookup failed for oid:%ld", DatumGetInt64(arg_dataoid));
PG_RETURN_INT32(-1);
}
//write
if ( lo_write(inv_fd, cstr, nbytes ) != nbytes)
elog(ERROR, "error while writing large object");
//close LO
DirectFunctionCall1(lo_close, Int32GetDatum(inv_fd));
Lots of examples for other lo* functions can be found here and here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.