Programming with SQL Relay using the PHP API
To use SQL Relay, you have to identify the connection that you intend to use.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); ... execute some queries ... sqlrcon_free($con); ?>
An alternative to running dl(sql_relay.so) is to put a line like:
extension=sql_relay.so
In your php.ini file. Doing this will improve performance as the library isn't loaded and unloaded each time a script runs, but only once when the web-server is started.
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.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $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 sqlrcur_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 functions. 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 functions for that database rather than issuing them as queries. If the API's have no commit or rollback functions, 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.
Temporary TablesSome databases support temporary tables. That is, tables which are automatically dropped or truncated when an application closes it's connection to the database or when a transaction is committed or rolled back.
For databases which drop or truncate tables when a transaction is committed or rolled back, temporary tables work naturally.
However, for databases which drop or truncate tables when an application closes it's connection to the database, there is an issue. Since SQL Relay maintains persistent database connections, when an application disconnects from SQL Relay, the connection between SQL Relay and the database remains, so the database does not know to drop or truncate the table. To remedy this situation, SQL Relay parses each query to see if it created a temporary table, keeps a list of temporary tables and drops (or truncates them) when the application disconnects from SQL Relay. Since each database has slightly different syntax for creating a temporary table, SQL Relay parses each query according to the rules for that database.
In effect, temporary tables should work when an application connects to SQL Relay in the same manner that they would work if the application connected directly to the database.
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<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); if (!sqlrcur_sendQuery($cur,"select * from my_nonexistant_table")) { echo sqlrcur_errorMessage($cur); echo "\n"; } sqlrcur_free($cur); sqlrcon_free($con); ?>
Programs rarely execute fixed queries. More often than not, some part of the query is dynamically generated. The SQL Relay API provides methods for making substitutions and binds in those queries.
For a detailed discussion of substitutions and binds, see this document.
Rather than just calling sendQuery() you call prepareQuery(), substitution(), inputBind() and executeQuery(). If you using queries stored in a file, you can call prepareFileQuery() instead of prepareQuery().
When passing a floating point number in as a bind or substitution variable, you have to supply precision and scale for the number. See this page for a discussion of precision and scale.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_prepareQuery($cur,"select * from mytable $(whereclause)") sqlrcur_substitution($cur,"whereclause","where stringcol=:stringval and integercol>:integerval and floatcol>floatval"); sqlrcur_inputBind($cur,"stringval","true"); sqlrcur_inputBind($cur,"integerval",10); sqlrcur_inputBind($cur,"floatval",1.1,2,1); sqlrcur_executeQuery($cur); ... process the result set ... sqlrcur_free($cur); sqlrcon_free($con); ?>
If you are curious how many bind variables have been declared in a query, you can call countBindVariables() after preparing the query.
If you're using a database with an embedded procedural language, you may want to retrieve data from function calls. To facilitate this, SQL Relay provides methods for defining and retrieving output bind variables.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_prepareQuery($cur,"begin :result1:=addTwoIntegers(:integer1,:integer2); :result2=addTwoFloats(:float1,:float2); :result3=convertToString(:integer3); end;"); sqlrcur_inputBind($cur,"integer1",10); sqlrcur_inputBind($cur,"integer2",20); sqlrcur_inputBind($cur,"float1",1.1,2,1); sqlrcur_inputBind($cur,"float2",2.2,2,1); sqlrcur_inputBind($cur,"integer3",30); sqlrcur_defineOutputBindInteger($cur,"result1"); sqlrcur_defineOutputBindDouble($cur,"result2"); sqlrcur_defineOutputBindString($cur,"result3",100); sqlrcur_executeQuery($cur); $result1=sqlrcur_getOutputBindInteger($cur,"result1"); $result2=sqlrcur_getOutputBindDouble($cur,"result2"); $result3=sqlrcur_getOutputBindString($cur,"result3"); sqlrcon_endSession($con); ... do something with the result ... sqlrcur_free($cur); sqlrcon_free($con); ?>
The getOutputBindString() method returns a NULL value as an empty string. If you would it to come back as a NULL instead, you can call the getNullsAsNulls() method. To revert to the default behavior, you can call getNullsAsEmptyStrings().
If you are using Oracle 8i or higher, you can insert data into BLOB and CLOB columns using the inputBindBlob(), inputBindClob() methods.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_executeQuery($cur,"create table images (image blob, description clob)"); $imagedata=""; $imagelength=0; ... read an image from a file into imagedata and the length of the file into imagelength ... $description=""; $desclength=0; ... read a description from a file into description and the length of the file into desclength ... sqlrcur_prepareQuery($cur,"insert into images values (:image,:desc)"); sqlrcur_inputBindBlob($cur,"image",$imagedata,$imagelength); sqlrcur_inputBindClob($cur,"desc",$description,$desclength); sqlrcur_executeQuery($cur); sqlrcur_free($cur); sqlrcon_free($con); ?>
Likewise, with Oracle 8i, you can retreive BLOB or CLOB data using defineOutputBindBlob()/getOutputBindBlob() and defineOutputBindClob()/getOutputBindClob().
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_prepareQuery($cur,"begin select image into :image from images; select description into :desc from images; end;"); sqlrcur_defineOutputBindBlob($cur,"image"); sqlrcur_defineOutputBindClob($cur,"desc"); sqlrcur_executeQuery($cur); $image=sqlrcur_getOutputBindBlob($cur,"image"); $imagelength=sqlrcur_getOutputBindLength($cur,"image"); $desc=sqlrcur_getOutputBindClob($cur,"desc"); $desclength=sqlrcur_getOutputBindLength($cur,"desc"); sqlrcon_endSession($con); ... do something with image and desc ... sqlrcur_free($cur); sqlrcon_free($con); ?>
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, however 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<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $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_getField() functions are useful for processing result sets.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $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++) { echo sqlrcur_getField($cur,$row,$col); echo ","; } echo "\n"; } sqlrcur_free($cur); sqlrcon_free($con); ?>
The sqlrcur_getField() function returns a string. If you would like to get a field as a long or double, you can use sqlrcur_getFieldAsLong() and sqlrcur_getFieldAsDouble().
You can also use sqlrcur_getRow() or sqlrcur_getRowAssoc() to get the entire row.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_sendQuery($cur,"select * from my_table"); sqlrcon_endSession($con); for ($row=0; $row<sqlrcur_rowCount($cur); $row++) { $rowarray=sqlrcur_getRow($cur,$row); for ($col=0; $col<sqlrcur_colCount($cur); $col++) { echo rowarray[$col]; echo ","; } echo "\n"; } sqlrcur_free($cur); sqlrcon_free($con); ?>
The sqlrcur_getField(), sqlrcur_getRow() and sqlrcur_getRowAssoc() 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() function. 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() function 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_getRowAssoc() and sqlrcur_getField() 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, getField(0,0) will return NULL and getField(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() function returns the number of rows returned so far. The sqlrcur_firstRowIndex() function returns the index of the first row of the currently buffered chunk.
Cursors<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $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_getField($cur,$row,$col)) { echo $field; echo ","; } else { done=1; } } echo "\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:
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cursor1=sqlrcur_alloc($con); $cursor2=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.
If you are using stored procedures with Oracle 8i or higher, a stored procedure can execute a query and return a cursor. A cursor bind variable can then retrieve that cursor. Your program can retrieve the result set from the cursor. All of this can be accomplished using defineOutputBindCursor(), getOutputBindCursor() and fetchFromOutputBindCursor().
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_prepareQuery($cur,"begin :curs:=sp_mytable; end;"); sqlrcur_defineOutputBindCursor($cur,"curs"); sqlrcur_executeQuery($cur); sqlrcur bindcur=sqlrcur_getOutputBindCursor($cur,"curs"); sqlrcur_fetchFromBindCursor($bindcur); # print fields from table for ($i=0; $i<sqlrcur_rowCount($bindcur); $i++) { for ($j=0; $j<sqlrcur_colCount($bindcur); $j++) { echo sqlrcur_getField($bindcur,$i,$j); echo ", "; } echo "\n"; } sqlrcur_free($bindcur); sqlrcur_free($cur); sqlrcon_free($con); ?>
The number of cursors simultaneously available per-connection is set at compile time and defaults to 5.
Getting Column InformationFor each column, the API supports getting the name, type and length of each field. All databases support these attributes. The API also supports getting the precision, scale (see this page for a discussion of precision and scale), length of the longest field, and whether the column is nullable, the primary key, unique, part of a key, unsigned, zero-filled, binary, or an auto-incrementing field. However, not all databases support these attributes. If a database doesn't support an attribute, it is always returned as false.
<? dl("sql_relay.so"); $con=sqlrcon_alloc("host",9000,"","user","password",0,1); $cur=sqlrcur_alloc($con); sqlrcur_sendQuery($cur,"select * from my_table"); sqlrcon_endSession($con); for ($i=0; $i<sqlrcur_colCount($cur); $i++) { echo "Name: "; echo sqlrcur_getColumnName($cur,$i); echo "\n"; echo "Type: "; echo sqlrcur_getColumnType($cur,$i); echo "\n"; echo "Length: "; echo sqlrcur_getColumnLength($cur,$i); echo "\n"; echo "Precision: "; echo sqlrcur_getColumnPrecision($cur,$i); echo "\n"; echo "Scale: "; echo sqlrcur_getColumnScale($cur,$i); echo "\n"; echo "Longest Field: ";