473,795 Members | 2,924 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Executing a query and returning the result set using the SPI


Hello all,

I'm messing around with the Server Programming Interface and the
particular example presented at:

http://www.postgresql.org/docs/curre...-examples.html

Ideally, I would want to make the example function return the
information as a "set" and not through elog() so I can later access it
and print it using PHP.

I have a few ideas on how this can be accomplished but I haven't found
any simple example to fully elucidate me. I have been reading:

http://www.postgresql.org/docs/curre...e/xfunc-c.html (33.7.9)

The code right now compiles fine but it crashes the server on loading:

veiculos=# CREATE FUNCTION teste(text) RETURNS setof veiculo AS
'teste.so' LANGUAGE C;
veiculos=# select * from teste('select * from veiculo');
server closed the connection unexpectedly

This is PostgreSQL version: 7.4.1

I'm compiling the code with:

$ gcc -Wall -fpic -c -I` pg_config --includedir` teste.c
$ gcc -shared -o teste.so teste.o

Here's the code:

#include "server/postgres.h"
#include "server/fmgr.h"
#include "server/executor/spi.h"
#include "server/funcapi.h"
#include "server/access/heapam.h"
#include "server/catalog/pg_type.h"
#include "server/storage/lock.h"
#include "server/storage/proc.h"
#include "server/utils/builtins.h"

PG_FUNCTION_INF O_V1(teste);

Datum teste(PG_FUNCTI ON_ARGS) {
char *command;
int ret;
FuncCallContext *funcctx;
TupleDesc tupdesc;
TupleTableSlot *slot;
AttInMetadata *attinmeta;
int call_cntr;
int max_calls;
text *sql_command = PG_GETARG_TEXT_ P(0);

command = DatumGetCString (DirectFunction Call1(textout,
PointerGetDatum (sql_command))) ;
SPI_connect();

ret = SPI_exec(comman d, 0);

if (SRF_IS_FIRSTCA LL()) {
MemoryContext oldcontext;

/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_I NIT();

/* switch to memory context appropriate for multiple function calls */
oldcontext = MemoryContextSw itchTo(funcctx->multi_call_mem ory_ctx);

/* total number of tuples to be returned */
funcctx->max_calls = PG_GETARG_UINT3 2(0);

/*
* Build a tuple description for a tuple
*/
tupdesc = SPI_tuptable->tupdesc;

/* allocate a slot for a tuple with this tupdesc */
slot = TupleDescGetSlo t(tupdesc);

/* assign slot to function context */
funcctx->slot = slot;

/*
* Generate attribute metadata needed later to produce tuples from raw
* C strings
*/
attinmeta = TupleDescGetAtt InMetadata(tupd esc);
funcctx->attinmeta = attinmeta;

MemoryContextSw itchTo(oldconte xt);
}

/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SET UP();

call_cntr = funcctx->call_cntr;
max_calls = funcctx->max_calls;
slot = funcctx->slot;
attinmeta = funcctx->attinmeta;

if (call_cntr < max_calls) { /* do when there is more left to
send */ char **values;
HeapTuple tuple;
Datum result;

/*
* Prepare a values array for storage in our slot.
* This should be an array of C strings which will
* be processed later by the appropriate "in" functions.
*/
values = (char **) palloc(3 * sizeof(char *));
values[0] = (char *) palloc(16 * sizeof(char));
values[1] = (char *) palloc(16 * sizeof(char));
values[2] = (char *) palloc(16 * sizeof(char));

snprintf(values[0], 16, "%d", 1 * PG_GETARG_INT32 (1));
snprintf(values[1], 16, "%d", 2 * PG_GETARG_INT32 (1));
snprintf(values[2], 16, "%d", 3 * PG_GETARG_INT32 (1));

/* build a tuple */
tuple = BuildTupleFromC Strings(attinme ta, values);

/* make the tuple into a datum */
result = TupleGetDatum(s lot, tuple);

/* Clean up (this is not actually necessary) */
pfree(values[0]);
pfree(values[1]);
pfree(values[2]);
pfree(values);

SRF_RETURN_NEXT (funcctx, result);
}
else { /* do when there is no more left */
SRF_RETURN_DONE (funcctx);
}

SPI_finish();
pfree(command);

}

--
Nuno Morgadinho
Undergraduate Computer Science Student
Évora University, Portugal

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 22 '05 #1
1 2885
On Monday 26 January 2004 18:37, Nuno Morgadinho wrote:
Hello all,

I'm messing around with the Server Programming Interface and the
particular example presented at:

http://www.postgresql.org/docs/curre...-examples.html

Ideally, I would want to make the example function return the
information as a "set" and not through elog() so I can later access it
and print it using PHP.


Don't do C functions myself, but I believe you might find the code in
/contrib/tablefunc useful

--
Richard Huxton
Archonet Ltd

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 22 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3435
by: jaysonsch | last post by:
Hello! I am having some problems with a database query that I am trying to do. I am trying to develop a way to search a database for an entry and then edit the existing values. Upon submit, the new values are updated in all corresponding tables (the function of the pages in question). However, on the page that does the DB update, I also want to do some checks on the data before performing the update. Now, the problem that I am...
4
8852
by: Praveen | last post by:
Hi All, I have a query something like this.. select col1, col2, col3 from ( select col1,col2,col3,col4 from table1 union all select col1,col2,col3,col4 from table2 )
0
1479
by: Chris | last post by:
Hi all - Hope you can help me with this SQL / PHP problem. I have the following tables with (in brackets) the following columns: PLAYER (playerid, forename, surname, birthdate, birthplace) PLAYERHISTORY (playerhistid, playerid, boughtfor, joined_date) PLAYERAPPS (playerappsid, playerhistid, apps, goals)
8
3706
by: san | last post by:
Hi, I wanted to know if this is possible and if so, how do I do it. Say, I have a query "SELECT * FROM Table WHERE Column="some_value". This executes on a very large data set and I would like to return the results as they query executes rather than wait for the whole query to execute. Basically, I want to get the results as they are prepared by the database. Any way to do this?
3
5225
by: Paul Mateer | last post by:
Hi, I have been running some queries against a table in a my database and have noted an odd (at least it seems odd to me) performance issue. The table has approximately 5 million rows and includes the following columns: DocID (INTEGER, PRIMARY KEY, CLUSTERED) IsRecord (INTEGER, NONCLUSTERED)
7
6219
by: Rick Caborn | last post by:
Does anyone know of a way to execute sql code from a dynamically built text field? Before beginning, let me state that I know this db architecture is built solely for frustration and I hope to make it better soon. Unfortunately, there is never a non-crucial time in which we can do an upgrade, so we are stuck for now. Point 1: There are multiple tables: students, courses, cross-reference
20
5227
by: Neil Robbins | last post by:
I am trying to execute a make table query in my vb.net program. The db that I am accessing is an Access 2000 format db. The SQL code that I am using has been cut and pasted from the SQL View having designed the query in the design view of Access. The code in question is below, I apologise for the length of the SQL statement Dim SqlComText As String = "SELECT TblCentreSession.ID, TblCentreSession.Session AS , TblSession.SessionYear AS...
13
2557
by: Karl Groves | last post by:
I'm missing something very obvious, but it is getting late and I've stared at it too long. TIA for responses I am writing a basic function (listed at the bottom of this post) that returns data from a query into an array. The intent is that the following code:
7
2843
by: wingsss | last post by:
i am currently using WindowsXP SP2 all updated apache 2.2.4 PHP 5.2.3 MySQL 5.0 and apache hang up when running this code // ------------------------------------------------------------------------------ function query($query="show tables")
0
9522
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10443
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7543
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2921
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.