Programming with SQL Relay using the PHP API

Establishing a Session

To use SQL Relay, you have to identify the connection that you intend to use.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     ... execute some queries ...

     sqlrc_free($s);
?>

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, sqlrc_ping() or sqlrc_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 Queries

Call sqlrc_sendQuery() or sqlrc_sendFileQuery() to run a query.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_sendQuery($s,"select * from my_table");

     ... do some stuff that takes a short time ...

     sqlrc_sendFileQuery($s,"/usr/local/myprogram/sql","myquery.sql");
     sqlrc_endSession($s);

     ... do some stuff that takes a long time ...

     sqlrc_sendQuery($s,"select * from my_other_table");
     sqlrc_endSession($s);

     ... process the result set ...

     sqlrc_free($s);
?>

Note the call to sqlrc_endSession() after the call to sqlrc_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 sqlrc_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.

Catching Errors

If your call to sqlrc_sendQuery() or sqlrc_sendFileQuery() returns a 0, the query failed. You can find out why by calling sqlrc_errorMessage().

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     if (!sqlrc_sendQuery($s,"select * from my_nonexistant_table")) {
             echo sqlrc_errorMessage($s);
             echo "\n";
     }

     sqlrc_free($s);
?>
Substitution and Bind Variables

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-PHP 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 sqlrc_sendFileQuery() you call sqlrc_prepareFileQuery(), sqlrc_substitution(), sqlrc_inputBind() and sqlrc_executeQuery().

/usr/local/myprogram/sql/myquery.sql: select * from mytable $(whereclause) program code:
<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_prepareFileQuery($s,"/usr/local/myprogram/sql","myquery.sql");
     sqlrc_substitution($s,"whereclause","where col1=:value1");
     sqlrc_inputBind($s,"value1","true");
     sqlrc_executeQuery($s);

     ... process the result set ...

     sqlrc_free($s);
?>

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 sqlrc_defineOutputBind() and sqlrc_getOutputBind() methods.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_prepareQuery($s,"begin  :result:=addTwoNumbers(:num1,:num2);  end;");
     sqlrc_inputBind($s,"num1",10);
     sqlrc_inputBind($s,"num2",20);
     sqlrc_defineOutputBind($s,"result",100);
     sqlrc_executeQuery($s);
     $result=sqlrc_getOutputBind($s,"result");
     sqlrc_endSession($s);

     ... do something with the result ...

     sqlrc_free($s);
?>

The sqlrc_getOutputBind() function returns a NULL value as an empty string. If you would it to come back as undefined instead, you can call the sqlrc_getNullsAsUndefined() method. To revert to the default behavior, you can call sqlrc_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().

Accessing Fields in the Result Set

The sqlrc_rowCount(), sqlrc_colCount() and sqlrc_getField() methods are useful for processing result sets.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_sendQuery($s,"select * from my_table");
     sqlrc_endSession($s);

     for ($row=0; $row<sqlrc_rowCount($s); $row++) {
             for ($col=0; $col<sqlrc_colCount($s); $col++) {
                     echo sqlrc_getField($s,$row,$col);
                     echo ",";
             }
             echo "\n";
     }

     sqlrc_free($s);
?>

You can also use sqlrc_getRow() or sqlrc_getRowAssoc() to get the entire row.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_sendQuery($s,"select * from my_table");
     sqlrc_endSession($s);

     for ($row=0; $row<sqlrc_rowCount($s); $row++) {
             $rowarray=sqlrc_getRow($s,$row);
             for ($col=0; $col<sqlrc_colCount($s); $col++) {
                     echo rowarray[$col];
                     echo ",";
             }
             echo "\n";
     }

     sqlrc_free($s);
?>

The sqlrc_getField(), sqlrc_getRow() and sqlrc_getRowAssoc() methods return NULL fields as empty strings. If you would like them to come back as NULL's instead, you can call the sqlrc_getNullsAsNulls() method. To revert to the default behavior, you can call sqlrc_getNullsAsEmptyStrings().

Dealing With Large Result Sets

SQL 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 sqlrc_setResultSetBufferSize() to set the number of rows to buffer at a time. Calls to sqlrc_getRow(), sqlrc_getRowAssoc() and sqlrc_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 sqlrc_setResultSetBufferSize() and forget what you set it to, you can always call sqlrc_getResultSetBufferSize().

When buffering a result set in chunks, the sqlrc_rowCount() method returns the number of rows returned so far. The sqlrc_firstRowIndex() method returns the index of the first row of the currently buffered chunk.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_setResultSetBufferSize($s,5);

     sqlrc_sendQuery($s,"select * from my_table");

     while (!done) {
             for ($col=0; $col<sqlrc_colCount($s); $col++) {
                     if ($field=sqlrc_getField($s,$row,$col)) {
                             echo $field;
                             echo ",";
                     } else {
                             done=1;
                     }
             }
             echo "\n";
             $row++;
     }

    sqlrc_sendQuery($s,"select * from my_other_table");

    ... process this query's result set in chunks also ...

    sqlrc_setResultSetBufferSize($s,0);

    sqlrc_sendQuery($s,"select * from my_third_table");

    ... process this query's result set all at once ...

    sqlrc_endSession($s);

    sqlrc_free($s);
?>
Getting Column Information

The name, type, length and length of the longest field of each column are available.

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_sendQuery($s,"select * from my_table");
     sqlrc_endSession($s);

     for ($i=0; $i<sqlrc_colCount($s); $i++) {
             echo "Name: ";
             echo sqlrc_getColumnName($s,$i);
             echo "\n";
             echo "Type: ";
             echo sqlrc_getColumnType($s,$i);
             echo "\n";
             echo "Length: ";
             echo sqlrc_getColumnLength($s,$i);
             echo "\n";
             echo "Longest Field: ";
             echo sqlrc_getLongest($s,$i));
             echo "\n\n";
     }

     sqlrc_free($s);
?>
Caching The Result Set

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:

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_cacheOn($s);
     sqlrc_setCacheTtl($s,600);
     sqlrc_sendQuery($s,"select * from my_table");
     filename=getCacheFileName($s);
     sqlrc_endSession($s);
     sqlrc_cacheOff($s);

     ... pass the filename to the next page ...

     sqlrc_free($s);
?>

Second CGI:

<?
     dl(sqlrelay.so)

     ... get the filename from the previous page ...

     ... get the page to display from the previous page ...

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_openCachedResultSet($s,filename);
     sqlrc_endSession($s);

     for ($row=$pagetodisplay*20; $row<($pagetodisplay+1)*20; $row++) {
             for ($col=0; $col<sqlrc_colCount($s); $col++) {
                     echo sqlrc_getField($s,$row,$col);
                     echo ",";
             }
             echo "\n";
     }

     sqlrc_free($s);
?>
Suspending and Resuming Sessions

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:

<?
     dl(sqlrelay.so)

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_sendQuery($s,"insert into my_table values (1,2,3)");
     $port=getConnectionPort($s);
     $socket=getConnectionPort($s);
     sqlrc_suspendSession($s);

     ... pass the port and socket to the next page ...

     sqlrc_free($s);
?>

Second CGI:

<?
     dl(sqlrelay.so)

     ... get port and socket from previous page ...

     $s=sqlrc_alloc("host",8000,"","user","password",0,1);

     sqlrc_resumeSession($s,$port,$socket);
     sqlrc_sendQuery($s,"commit");
     sqlrc_endSession($s);

     sqlrc_free($s);
?>

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 sqlrc_resumeCachedSession() instead of sqlrc_resumeSession() however.