![]()
|
Programming with SQL Relay using the C API
When writing an SQL Relay client program using the C API, you need to include the sqlrclientwrapper.h file.
#include <sqlrelay/sqlrclientwrapper.h> You'll also need to link against the sqlrclientwrapper, sqlrclient and rudiments libraries. The include file is usually found in /usr/local/firstworks/include and the libraries are usually found in /usr/local/firstworks/lib. The command to compile your .c file to object code will look something like this (assuming you're using the GNU C compiler): gcc -I/usr/local/firstworks/include -c myprogram.c The command to compile your .o file to an executable will look something like this (assuming you're using the GNU C++ compiler): g++ -o myprogram myprogram.o -L/usr/local/firstworks/lib -lsqlrclientwrapper -lsqlrclient -lrudiments Note that g++ was used to link, not gcc. You could alternatively link using gcc like this: gcc -o myprogram myprogram.o -L/usr/local/firstworks/lib -lsqlrclientwrapper -lsqlrclient -lrudiments -lstdc++ When using the C API, it is important to compile the .c files to object code using the C compiler before linking them using the C++ compiler. Compiling/Linking in one step using the C++ compiler the will most likely fail as it will generate C++ style symbols for function calls which will not be resolved in the sqlrclientwrapper library since it contains C style function symbols. Compiling to object code using the C compiler as a seperate step ensures that C style symbols will be generated for function calls. Establishing a SessionTo use SQL Relay, you have to identify the connection that you intend to use. #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); ... execute some queries ... sqlrcon_free(con); } After calling the constructor, a session is established when the first query, sqlrcur_ping() or sqlrcur_identify() is run. For the duration of the session, the client stays connected to a database connection daemon. While one client is connected, no other client can connect. Care should be taken to minimize the length of a session. If you're using a transactional database, ending a session has a catch. Database connection daemons can be configured to send either a commit or rollback at the end of a session if DML queries were executed during the session with no commit or rollback. Program accordingly. Executing QueriesCall sqlrcur_sendQuery() or sqlrcur_sendFileQuery() to run a query. #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_sendQuery(cur,"select * from my_table"); ... do some stuff that takes a short time ... sqlrcur_sendFileQuery(cur,"/usr/local/myprogram/sql","myquery.sql"); sqlrcon_endSession(con); ... do some stuff that takes a long time ... sqlrcur_sendQuery(cur,"select * from my_other_table"); sqlrcon_endSession(con); ... process the result set ... sqlrcur_free(cur); sqlrcon_free(con); } Note the call to sqlrcon_endSession() after the call to sqlrcur_sendFileQuery(). Since the program does some stuff that takes a long time between that query and the next, ending the session there allows another client an opportunity to use that database connection while your client is busy. The next call to sqlrcur_sendQuery() establishes another session. Since the program does some stuff that takes a short time between the first two queries, it's OK to leave the session open between them. Commits and RollbacksIf you need to execute a commit or rollback, you should use the sqlrcon_commit() and sqlrcon_rollback() functions rather than sending a "commit" or "rollback" query. There are two reasons for this. First, it's much more efficient to call the methods. Second, if you're writing code that can run on transactional or non-transactional databases, some non-transactional databases will throw errors if they receive a "commit" or "rollback" query, but by calling the sqlrcon_commit() and sqlrcon_rollback() functions you instruct the database connection daemon to call the commit and rollback API methods for that database rather than issuing them as queries. If the API's have no commit or rollback methods, the calls do nothing and the database throws no error. This is especially important when using SQL Relay with ODBC. You can also turn Autocommit on or off with the sqlrcon_autoCommitOn() and sqlrcon_autoCommitOff() functions. When Autocommit is on, the database performs a commit after each successful DML or DDL query. When Autocommit is off, the database commits when the client instructs it to, or (by default) when a client disconnects. For databases that don't support Autocommit, sqlrcon_autoCommitOn() and sqlrcon_autoCommitOff() have no effect. Catching ErrorsIf your call to sqlrcur_sendQuery() or sqlrcur_sendFileQuery() returns a 0, the query failed. You can find out why by calling sqlrcur_errorMessage(). Substitution and Bind Variables#include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); if (!sqlrcur_sendQuery(cur,"select * from my_nonexistant_table")) { printf("%s\n",sqlrcur_errorMessage(cur)); } sqlrcur_free(cur); sqlrcon_free(con); } Programs rarely execute fixed queries. More often than not, some part of the query is dynamically generated. It's convenient to store queries in files so they can be changed by a non-C programmer. The SQL Relay API provides functions for making substitutions and binds in those queries. For a detailed discussion of substitutions and binds, see this document. Rather than just calling sqlrcur_sendFileQuery() you call sqlrcur_prepareFileQuery(), one or more of sqlrcur_subString(), sqlrcur_subLong() or sqlrcur_subDouble, one or more of sqlrcur_inputBindString(), sqlrcur_inputBindLong() or sqlr_inputBindDouble() and sqlrcur_executeQuery(). /usr/local/myprogram/sql/myquery.sql: select * from mytable $(whereclause) program code:#include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_prepareFileQuery(cur,"/usr/local/myprogram/sql","myquery.sql"); sqlrcur_subString(cur,"whereclause","where col1=:value1"); sqlrcur_inputBindString(cur,"value1","true"); sqlrcur_executeQuery(cur); ... process the result set ... sqlrcur_free(cur); sqlrcon_free(con); } If you're using a database with an embedded procedural language, you may want to retrieve data from a call to one of it's functions. To facilitate this, SQL Relay provides the sqlrcur_defineOutputBind() and sqlrcur_getOutputBind() methods. #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int result; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_prepareQuery(cur,"begin :result:=addTwoNumbers(:num1,:num2); end;"); sqlrcur_inputBind(cur,"num1",10); sqlrcur_inputBind(cur,"num2",20); sqlrcur_defineOutputBind(cur,"result",100); sqlrcur_executeQuery(cur); result=atoi(sqlrcur_getOutputBind(cur,"result")); sqlrcon_endSession(con); ... do something with the result ... sqlrcur_free(cur); sqlrcon_free(con); } The sqlrcur_getOutputBind() function returns a NULL value as an empty string. If you would it to come back as a NULL instead, you can call the sqlrcur_getNullsAsNulls() method. To revert to the default behavior, you can call sqlrcur_getNullsAsEmptyStrings(). Sometimes it's convenient to bind a bunch of variables that may or may not actually be in the query. For example, if you are building a web based application, it may be easy to just bind all the form variables/values from the previous page, even though some of them don't appear in the query. Databases usually generate errors in this case. Calling validateBinds() just prior to calling executeQuery() causes the API to check the query for each bind variable before actually binding it, preventing those kinds of errors. There is a performance cost associated with calling validateBinds(). Re-Binding and Re-ExecutionAnother feature of the prepare/bind/execute paradigm is the ability to prepare, bind and execute a query once, then re-bind and re-execute the query over and over without re-preparing it. If your backend database natively supports this paradigm, you can reap a substantial performance improvement. Accessing Fields in the Result Set#include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_prepareQuery(cur,"select * from mytable where mycolumn>:value"); sqlrcur_inputBind(cur,"value",1); sqlrcur_executeQuery(cur); ... process the result set ... sqlrcur_clearBinds(cur); sqlrcur_inputBind(cur,"value",5); sqlrcur_executeQuery(cur); ... process the result set ... sqlrcur_clearBinds(cur); sqlrcur_inputBind(cur,"value",10); sqlrcur_executeQuery(cur); ... process the result set ... sqlrcur_free(cur); sqlrcon_free(con); } The sqlrcur_rowCount(), sqlrcur_colCount() and sqlrcur_getFieldByIndex() methods are useful for processing result sets. #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int row,col; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_sendQuery(cur,"select * from my_table"); sqlrcon_endSession(con); for (row=0; row<sqlrcur_rowCount(cur); row++) { for (col=0; col<sqlrcur_colCount(cur); col++) { printf("%s,",sqlrcur_getFieldByIndex(cur,row,col)); } printf("\n"); } sqlrcur_free(cur); sqlrcon_free(con); } You can also use sqlrcur_getRow() which returns a NULL-terminated array of the fields in the row. #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int row,col; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_sendQuery(cur,"select * from my_table"); sqlrcon_endSession(con); for (row=0; row<sqlrcur_rowCount(cur); row++) { char **rowarray=sqlrcur_getRow(cur,row); for (col=0; col<sqlrcur_colCount(cur); col++) { printf("%s,",rowarray[col]); } printf("\n"); } sqlrcur_free(cur); sqlrcon_free(con); } The sqlrcur_getFieldByIndex(), sqlrcur_getFieldByName() and sqlrcur_getRow() functions return NULL fields as empty strings. If you would like them to come back as NULL's instead, you can call the sqlrcur_getNullsAsNulls() method. To revert to the default behavior, you can call sqlrcur_getNullsAsEmptyStrings(). If you want to access the result set, but don't care about the column information (column names, types or sizes) and don't mind getting fields by their numeric index instead of by name, you can call the sqlrcur_dontGetColumnInfo() method prior to executing your query. This can result in a performance improvement, especially when many queries with small result sets are executed in rapid succession. You can call sqlrcur_getColumnInfo() again later to turn off this feature. Dealing With Large Result SetsSQL Relay normally buffers the entire result set. This can speed things up at the cost of memory. With large enough result sets, it makes sense to buffer the result set in chunks instead of all at once. Use sqlrcur_setResultSetBufferSize() to set the number of rows to buffer at a time. Calls to sqlrcur_getRow(), sqlrcur_getFieldByIndex() and sqlrcur_getFieldByName() cause the chunk containing the requested field to be fetched. Rows in that chunk are accessible but rows before it are not. For example, if you setResultSetBufferSize(5) and execute a query that returns 20 rows, rows 0-4 are available at once, then rows 5-9, then 10-14, then 15-19. When rows 5-9 are available, getFieldByIndex(0,0) will return NULL and getFieldByIndex(11,0) will cause rows 10-14 to be fetched and return the requested value. When buffering the result set in chunks, don't end the session until after you're done with the result set. If you call sqlrcur_setResultSetBufferSize() and forget what you set it to, you can always call sqlrcur_getResultSetBufferSize(). When buffering a result set in chunks, the sqlrcur_rowCount() method returns the number of rows returned so far. The sqlrcur_firstRowIndex() method returns the index of the first row of the currently buffered chunk. Cursors#include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int done=0; int row=0; int col; char *field; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_setResultSetBufferSize(cur,5); sqlrcur_sendQuery(cur,"select * from my_table"); while (!done) { for (col=0; col<sqlrcur_colCount(cur); col++) { if (field=sqlrcur_getFieldByIndex(cur,row,col)) { printf("%s,",field); } else { done=1; } } printf("\n"); row++; } sqlrcur_sendQuery(cur,"select * from my_other_table"); ... process this query's result set in chunks also ... sqlrcur_setResultSetBufferSize(cur,0); sqlrcur_sendQuery(cur,"select * from my_third_table"); ... process this query's result set all at once ... sqlrcon_endSession(con); sqlrcur_free(cur); sqlrcon_free(con); } Cursors make it possible to execute queries while processing the result set of another query. You can select rows from a table in one query, then iterate through it's result set, inserting rows into another table, using only 1 database connection for both operations. For example: #include <sqlrelay/sqlrclientwrapper.h> main() { sqlrcon con; sqlrcur cursor1; sqlrcur cursor2; int index; con=new sqlrcon_alloc("host",9000,"","user","password",0,1); cursor1=new sqlrcur_alloc(con); cursor2=new sqlrcur_alloc(con); sqlrcur_setResultSetBufferSize(cursor1,10); sqlrcur_sendQuery(cursor1,"select * from my_huge_table"); index=0; while (!sqlrcur_endOfResultSet(cursor1)) { sqlrcur_prepareQuery(cursor2,"insert into my_other_table values (:1,:2,:3)"); sqlrcur_inputBind(cursor2,"1",sqlrcur_getField(cursor1,index,1)); sqlrcur_inputBind(cursor2,"2",sqlrcur_getField(cursor1,index,2)); sqlrcur_inputBind(cursor2,"3",sqlrcur_getField(cursor1,index,3)); sqlrcur_executeQuery(cursor2); } sqlrcur_free(cursor2); sqlrcur_free(cursor1); sqlrcon_free(con); } Prior to SQL Relay version 0.25, you would have had to buffer the first result set or use 2 database connections instead of just 1. The number of cursors simultaneously available per-connection is set at compile time and defaults to 5. Getting Column InformationThe name, type, length and length of the longest field of each column are available. Caching The Result Set#include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int i; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_sendQuery(cur,"select * from my_table"); sqlrcon_endSession(con); for (i=0; i<sqlrcur_colCount(cur); i++) { printf("Name: %s\n",sqlrcur_getColumnName(cur,i)); printf("Type: %s\n",sqlrcur_getColumnType(cur,i)); printf("Length: %s\n",sqlrcur_getColumnLength(cur,i)); printf("Longest Field: %s\n",sqlrcur_getLongest(cur,i)); printf("\n"); } sqlrcur_free(cur); sqlrcon_free(con); } Say you're writing a web-based report where a query with a huge result set is executed and 20 rows are displayed per page. Rather than rerunning the query for every page every time and dumping all but the 20 rows you want to display, you can run the query once, cache the result set to a local file and just open the file for each page of the report. First CGI: #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { char *filename; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); ... generate a unique file name ... sqlrcur_cacheToFile(cur,filename); sqlrcur_setCacheTtl(cur,600); sqlrcur_sendQuery(cur,"select * from my_table"); sqlrcon_endSession(con); sqlrcur_cacheOff(cur); ... pass the filename to the next page ... sqlrcur_free(cur); sqlrcon_free(con); } Second CGI: Suspending and Resuming Sessions#include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int row,col; ... get the filename from the previous page ... ... get the page to display from the previous page ... sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_openCachedResultSet(cur,filename); sqlrcon_endSession(con); for (row=pagetodisplay*20; row<(pagetodisplay+1)*20; row++) { for (col=0; col<sqlrcur_colCount(cur); col++) { printf("%s,",sqlrcur_getFieldByIndex(cur,row,col)); } printf("\n"); } sqlrcur_free(cur); sqlrcon_free(con); } Sometimes web-based applications need a single database transaction to span multiple pages. Since SQL Relay sessions can be suspended and resumed, this is possible. First CGI: #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { int port; char *socket; int rs; sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcur_sendQuery(cur,"insert into my_table values (1,2,3)"); port=getConnectionPort(cur); socket=getConnectionPort(cur); rs=sqlrcur_getResultSetId(cur); sqlrcur_suspendResultSet(cur); sqlrcon_suspendSession(con); ... pass the rs, port and socket to the next page ... sqlrcur_free(cur); sqlrcon_free(con); } Second CGI: #include <sqlrelay/sqlrclientwrapper.h> #include <stdio.h> main() { ... get rs, port and socket from previous page ... sqlrcon con=sqlrcon_alloc("host",9000,"","user","password",0,1); sqlrcur cur=sqlrcur_alloc(con); sqlrcon_resumeSession(con,port,socket); sqlrcur_resumeResultSet(cur,rs); sqlrcur_sendQuery(cur,"commit"); sqlrcon_endSession(con); sqlrcur_free(cur); sqlrcon_free(con); } You can also distribute the processing of a result set across a series of CGI's using suspended sessions. If you're buffering a result set in chunks instead of all at once and suspend a session, when you resume the session you can continue to retrieve rows from the result set. Similarly, if you're buffering a result set in chunks, caching that result set and suspend your session. When you resume the session, you can continue caching the result set. You must use sqlrcur_resumeCachedResultSet() instead of sqlrcur_resumeResultSet() however. |