Programming with SQL Relay using the C++ API

Establishing a Session

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

#include <sqlrclient.h>
#include <iostream.h>

main() {

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

        ... execute some queries ...

        delete s;
}

After calling the constructor, a session is established when the first query, ping() or 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 sendQuery() or sendFileQuery() to run a query.

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->sendQuery("select * from my_table");

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

        s->sendFileQuery("/usr/local/myprogram/sql","myquery.sql");
        s->endSession();

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

        s->sendQuery("select * from my_other_table");
        s->endSession();

        ... process the result set ...

        delete s;
}

Note the call to endSession() after the call to 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 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 sendQuery() or sendFileQuery() returns a 0, the query failed. You can find out why by calling errorMessage().

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        if (!s->sendQuery("select * from my_nonexistant_table")) {
                cout << s->errorMessage() << endl;
        }

        delete 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-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 sendFileQuery() you call prepareFileQuery(), substitution(), inputBind() and executeQuery().

/usr/local/myprogram/sql/myquery.sql: select * from mytable $(whereclause) program code:
#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->prepareFileQuery("/usr/local/myprogram/sql","myquery.sql");
        s->substitution("whereclause","where col1=:value1");
        s->inputBind("value1","true");
        s->executeQuery();

        ... process the result set ...

        delete 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 defineOutputBind() and getOutputBind() methods.

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->prepareQuery("begin  :result:=addTwoNumbers(:num1,:num2);  end;");
        s->inputBind("num1",10);
        s->inputBind("num2",20);
        s->defineOutputBind("result",100);
        s->executeQuery();
        int     result=atoi(s->getOutputBind("result"));
        s->endSession();

        ... do something with the result ...

        delete s;
}

The 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 getNullsAsNulls() method. To revert to the default behavior, you can call 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 rowCount(), colCount() and getField() methods are useful for processing result sets.

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->sendQuery("select * from my_table");
        s->endSession();

        for (int row=0; row<s->rowCount(); row++) {
                for (int col=0; col<s->colCount(); col++) {
                        cout << s->getField(row,col) << ",";
                }
                cout << endl;
        }

        delete s;
}

You can also use getRow() which returns a NULL-terminated array of the fields in the row.

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->sendQuery("select * from my_table");
        s->endSession();

        for (int row=0; row<s->rowCount(); row++) {
                char    **rowarray=s->getRow(row);
                for (int col=0; col<s->colCount(); col++) {
                        cout << rowarray[col] << ",";
                }
                cout << endl;
        }

        delete s;
}

The getField() and getRow() methods return NULL fields as empty strings. If you would like them to come back as NULL's instead, you can call the getNullsAsNulls() method. To revert to the default behavior, you can call 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 setResultSetBufferSize() to set the number of rows to buffer at a time. Calls to getRow() and 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 setResultSetBufferSize() and forget what you set it to, you can always call getResultSetBufferSize().

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

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->setResultSetBufferSize(5);

        s->sendQuery("select * from my_table");

        int     done=0;
        int     row=0;
        char    *field;
        while (!done) {
                for (int col=0; col<s->colCount(); col++) {
                        if (field=s->getField(row,col)) {
                                cout << field << ",";
                        } else {
                                done=1;
                        }
                }
                cout << endl;
                row++;
        }

        s->sendQuery("select * from my_other_table");

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

        s->setResultSetBufferSize(0);

        s->sendQuery("select * from my_third_table");

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

        s->endSession();

        delete s;
}
Getting Column Information

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

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->sendQuery("select * from my_table");
        s->endSession();

        for (int i=0; i<s->colCount(); i++) {
                cout << "Name:          " << s->getColumnName(i) << endl;
                cout << "Type:          " << s->getColumnType(i) << endl;
                cout << "Length:        " << s->getColumnLength(i) << endl;
                cout << "Longest Field: " << s->getLongest(i) << endl;
                cout << endl;
        }

        delete 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:

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->cacheOn();
        s->setCacheTtl(600);
        s->sendQuery("select * from my_table");
        char    *filename=getCacheFileName();
        s->endSession();
        s->cacheOff();

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

        delete s;
}

Second CGI:

#include <sqlrclient.h>
#include <iostream.h>

main() {

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

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

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->openCachedResultSet(filename);
        s->endSession();

        for (int row=pagetodisplay*20; row<(pagetodisplay+1)*20; row++) {
                for (int col=0; col<s->colCount(); col++) {
                        cout << s->getField(row,col) << ",";
                }
                cout << endl;
        }

        delete 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:

#include <sqlrclient.h>
#include <iostream.h>

main() {

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->sendQuery("insert into my_table values (1,2,3)");
        int     port=getConnectionPort();
        char    *socket=getConnectionPort();
        s->suspendSession();

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

        delete s;
}

Second CGI:

#include <sqlrclient.h>
#include <iostream.h>

main() {

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

        sqlrclient      *s=new sqlrclient("host",8000,"","user","password",0,1);

        s->resumeSession(port,socket);
        s->sendQuery("commit");
        s->endSession();

        delete 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 resumeCachedSession() instead of resumeSession() however.