# SQLClient documentation

### Authors

Richard Frith-Macdonald (`rfm@gnu.org`)

Copyright: (C) 2004 Free Software Foundation, Inc.

### Contents -

1. The SQLClient library
2. What is the SQLClient library?
3. What backend bundles are available?
4. Where can you get it? How can you install it?
5. Software documentation for the SQLClient class
6. Software documentation for the SQLClientPool class
7. Software documentation for the SQLDictionaryBuilder class
8. Software documentation for the SQLLiteral class
9. Software documentation for the SQLRecord class
10. Software documentation for the SQLRecordKeys class
11. Software documentation for the SQLSetBuilder class
12. Software documentation for the SQLSingletonBuilder class
13. Software documentation for the SQLTransaction class
14. Software documentation for the NSObject(SQLClient) category
15. Software documentation for the SQLClient(Caching) category
16. Software documentation for the SQLClient(Convenience) category
17. Software documentation for the SQLClient(Logging) category
18. Software documentation for the SQLClient(Notifications) category
19. Software documentation for the SQLClient(Quote) category
20. Software documentation for the SQLClient(Subclass) category
21. Software documentation for the SQLClientPool(Convenience) category
22. SQLClient types
23. SQLClient constants
24. SQLClient variables
25. SQLClient functions

# The SQLClient library

## What is the SQLClient library?

The SQLClient library is designed to provide a simple interface to SQL databases for GNUstep applications. It does not attempt the sort of abstraction provided by the much more sophisticated GDL2 library, but rather allows applications to directly execute SQL queries and statements.

SQLClient provides for the Objective-C programmer much the same thing that JDBC provides for the Java programmer (though SQLClient is a bit faster, easier to use, and easier to add new database backends for than JDBC).

The major features of the SQLClient library are -

- Simple API for executing queries and statements... a variable length sequence of comma separated strings and other objects (NSNumber, NSDate, NSData) are concatenated into a single SQL statement and executed.
- Simple API ([SQLTransaction])for combining multiple SQL statements into a single transaction which can be used to minimise client-server interactions to get the best possible performance from your database.
- Supports multiple sumultaneous named connections to a database server in a thread-safe manner.
- Supports multiple simultaneous connections to different database servers with backend driver bundles loaded for different database engines. Clear, simple subclassing of the abstract base class to enable easy implementation of new backend bundles.
- Configuration for all connections held in one place and referenced by connection name for ease of configuration control. Changes via NSUserDefaults can even allow reconfiguration of client instances within a running application.
- Thread safe operation... The base class supports locking such that a single instance can be shared between multiple threads.
- Support for standalone web applications... eg to allow data to be added to the database by people posting web forms to the application.
- Supports notification of connection to and disconnection from the database server.

## What backend bundles are available?

Current backend bundles are -

- ECPG - a bundle using the embedded SQL interface for postgres.
  This is based on a similar code which was in production use for over eighteen months, so it should be reliable, but inefficient.
- Postgres - a bundle using the libpq native interface for postgres.
  This is the preferred backend as it allows 'SELECT FOR UPDATE', which the ECPG backend cannot support due to limitations in the postgres implementation of cursors. The code is now well tested and known to be efficient.
- MySQL - a bundle using the mysqlclient library for *recent* MySQL.
  I don't use MySQL... but the test program ran successfully with a vanilla install of the MySQL packages for recent Debian unstable.
- SQLite - a bundle using the sqlite3 library which supports an SQL-like API for direct access to a database file (rather than acting as a client of a database server process).
  Not as functional as the other backends (doesn't support dates for instance), but good enough for many purposes and very 'lightweight'. See http://www.sqlite.org
- Oracle - a bundle using embedded SQL for Oracle.
  Completely untested... may even need some work to compile... but this *is* based on code which was working about a year ago.
  No support for BLOBs yet.

## Where can you get it? How can you install it?

The SQLClient library is currently only available via CVS from the GNUstep CVS repository.
See <https://savannah.gnu.org/cvs/?group=gnustep>
You need to check out `gnustep/dev-libs/SQLClient`

To build this library you must have a basic GNUstep environment set up...

- The gnustep-make package must have been built and installed.
- The gnustep-base package must have been built and installed.
- The Performance library (from the dev-libs area in GNUstep CVS) must have been built and installed.
- If this environment is in place, all you should need to do is run 'make' to configure and build the library, 'make install' to install it.
- Then you can run the test programs.
- Your most likely problems are that the configure script may not detect the database libraries you want... Please figure out how to modify `configure.ac` so that it will detect the required headers and libraries on your system, and supply na patch.
- Once the library is installed, you can include the header file `<SQLClient/SQLClient.h%gt;` and link your programs with the `SQLClient` library to use it.

Bug reports, patches, and contributions (eg a backend bundle for a new database) should be entered on the GNUstep project page <http://savannah.gnu.org/projects/gnustep> and the bug reporting page <http://savannah.gnu.org/bugs/?group=gnustep>

# Software documentation for the SQLClient class

## SQLClient : NSObject

> Declared in:
>   SQLClient.h

The SQLClient class encapsulates dynamic SQL access to relational database systems. A shared instance of the class is used for each database (as identified by the name of the database), and the number of simultanous database connections is managed too.

SQLClient is an abstract base class... when you create an instance of it, you are actually creating an instance of a concrete subclass whose implementation is loaded from a bundle.

Instance Variables
Method summary

- -cache
- -cache:query:,...
- -cache:query:with:
- -cache:simpleQuery:
- -cache:simpleQuery:recordType:listType:
- -cacheCheckSimpleQuery:
- -setCache:
- -setCacheThread:
- +columns:
- +singletons:
- -batch:
- -columns:
- -queryRecord:,...
- -queryString:,...
- -singletons:
- -transaction
- +debugging
- +durationLogging
- +setDebugging:
- +setDurationLogging:
- -debug:,...
- -debugging
- -durationLogging
- -setDebugging:
- -setDurationLogging:
- -addObserver:selector:name:
- -postNotificationName:payload:
- -removeObserver:name:
- +autoquote
- +autoquoteWarning
- +setAutoquote:
- +setAutoquoteWarning:
- -backendConnect
- -backendDisconnect
- -backendExecute:
- -backendListen:
- -backendNotify:payload:
- -backendQuery:recordType:listType:
- -backendUnlisten:
- -copyEscapedBLOB:into:
- -insertBLOBs:intoStatement:length:withMarker:length:giving:
- -lengthOfEscapedBLOB:
- +allClients
- +clientWithConfiguration:name:
- +existingClient:
- +maxConnections
- +purgeConnections:
- +setAbandonFailedConnectionsAfter:
- +setMaxConnections:
- -begin
- -buildQuery:,...
- -buildQuery:with:
- -clientName
- -commit
- -committed
- -connect
- -connected
- -database
- -disconnect
- -execute:,...
- -execute:with:
- -initWithConfiguration:
- -initWithConfiguration:name:
- -initWithConfiguration:name:pool:
- -isEqual:
- -isInTransaction
- -lastConnect
- -lastOperation
- -lockBeforeDate:
- -longestIdle:
- -name
- -password
- -pool
- -prepare:,...
- -prepare:args:
- -prepare:with:
- -query:,...
- -query:with:
- -quote:
- -quoteArray:
- -quoteArray:toString:quotingStrings:
- -quoteArraySafe:
- -quoteBigInteger:
- -quoteCString:
- -quoteChar:
- -quoteFloat:
- -quoteInteger:
- -quoteName:
- -quoteSet:
- -quoteString:
- -quotef:,...
- -rollback
- -setClientName:
- -setDatabase:
- -setName:
- -setOptions:
- -setPassword:
- -setShouldTrim:
- -setUser:
- -simpleExecute:
- -simpleQuery:
- -simpleQuery:recordType:listType:
- -tryConnect
- -unlock
- -user

### allClients

+ (NSArray*) allClients;
Returns an array containing all the SQLClient instances.

### clientWithConfiguration: name:

+ (SQLClient*) clientWithConfiguration: (NSDictionary*)config name: (NSString*)reference;
Return an existing SQLClient instance (using +existingClient:) if possible, or creates one, initialises it using -initWithConfiguration:name: , and returns the new instance (autoreleased).
Returns `nil` on failure.

### existingClient:

+ (SQLClient*) existingClient: (NSString*)reference;
Return an existing SQLClient instance for the specified name if one exists, otherwise returns `nil`.

### maxConnections

+ (unsigned int) maxConnections;
Returns the maximum number of simultaneous database connections permitted (set by +setMaxConnections: and defaults to 8) for connections outside of SQLClientPool instances.

### purgeConnections:

+ (void) purgeConnections: (NSDate*)since;

Use this method to reduce the number of database connections currently active so that it is less than the limit set by the +setMaxConnections: method. This mechanism is used internally by the class to ensure that, when it is about to open a new connection, the limit is not exceeded.

If since is not `nil`, then any connection which has not been used more recently than that date is disconnected anyway.
You can (and probably should) use this periodically to purge idle connections, but you can also pass a date in the future to close all connections.

Purging does not apply to connections made by SQLClientPool instances.

### setAbandonFailedConnectionsAfter:

+ (void) setAbandonFailedConnectionsAfter: (NSTimeInterval)delay;
Sets the retry period after which connection attempts are abandoned. a delay less than or equal to zero means that connection attempts are abandoned after the first failure (the -connect method behaves the same way as the -tryConnect method).

### setMaxConnections:

+ (void) setMaxConnections: (unsigned int)c;

Set the maximum number of simultaneous database connections permitted (defaults to 8 and may not be set less than 1).

This value is used by the +purgeConnections: method to determine how many connections should be disconnected when it is called.

Connections used by SQLClientPool instances are not considered by this maximum.

### begin

- (void) begin;
Start a transaction for this database client.
You must match this with either a -commit or a -rollback .

Normally, if you execute an SQL statement without using this method first, the autocommit feature is employed, and the statement takes effect immediately. Use of this method permits you to execute several statements in sequence, and only have them take effect (as a single operation) when you call the -commit method.

NB. You must not execute an SQL statement which would start a transaction directly... use only this method.

Where possible, consider using the SQLTransaction class rather than calling -begin -commit or -rollback yourself.

### buildQuery: ,...

- (SQLLiteral*) buildQuery: (NSString*)stmt,...;

Build an sql query string using the supplied arguments to call [SQLClient -prepare:args:] to build a query and raises an exception if the result is not a simple query string.

This method has at least one argument, the string starting the query to be executed (which must have the prefix 'select ').

Additional arguments are a `nil` terminated list which also be strings, and these are appended to the statement.
Arguments in the list are automatically quoted as necessary, with the behavior for string arguments being controlled by the autoquote setting.

       sql = [db buildQuery: @"SELECT Name FROM ", table, nil];

Upon error, an exception is raised.

The method returns a string containing sql suitable for passing to the -simpleQuery:recordType:listType: or [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] methods.

### buildQuery: with:

- (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values;

Build an sql query string using the supplied arguments to call [SQLClient -prepare:with:] to build a query and raises an exception if the result is not a simple query string.
Takes the query statement and substitutes in values from the dictionary where markup of the format {key} is found.
Returns the resulting query string.

       sql = [db buildQuery: @"SELECT Name FROM {Table} WHERE ID = {ID}"
                       with: values];

Arguments in the dictionary are automatically quoted as necessary, with the behavior for string arguments being controlled by the autoquote setting.
The markup format may also be {key?default} where default is a string to be used if there is no value for the key in the dictionary.

The method returns a string containing sql suitable for passing to the -simpleQuery:recordType:listType: or [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] methods.

### clientName

- (NSString*) clientName;
Return the client name for this instance.
Normally this is useful only for debugging/reporting purposes, but if you are using multiple instances of this class in your application, and you are using embedded SQL, you will need to use this method to fetch the client/connection name and store its C-string representation in a variable 'connectionName' declared to the sql preprocessor, so you can then have statements of the form - 'exec sql at :connectionName...'.

### commit

- (void) commit;
Complete a transaction for this database client.
This must match an earlier -begin .

NB. You must not execute an SQL statement which would commit or rollback a transaction directly... use only this method or the -rollback method.

Where possible, consider using the SQLTransaction class rather than calling -begin -commit or -rollback yourself.

### committed

- (uint64_t) committed;
Returns the number of committed transactions.

### connect

- (BOOL) connect;
If the connected instance variable is `NO`, this method calls -backendConnect to ensure that there is a connection to the database server established. Returns the result.
Performs any necessary locking for thread safety.
This method also counts the number of consecutive failed connection attempts. A delay is enforced between each connection attempt, with the length of the delay growing with each failure. This ensures that applications which fail to deal with connection failures, and just keep trying to reconnect, will not overload the system/server.
The maximum delay is 30 seconds, so when the database server is restarted, the application can reconnect reasonably quickly.
If the connection attempt fails it is repeated until it succeds or until the time interval specified by +setAbandonFailedConnectionsAfter: has passed.

### connected

- (BOOL) connected;
Return a flag to say whether a connection to the database server is currently live (the value of the 'connected' instance variable).
This is mostly useful for debug/reporting.

### database

- (NSString*) database;
Return the database name for this instance (or `nil`).

### disconnect

- (void) disconnect;
If the connected instance variable is `YES`, this method calls -backendDisconnect to ensure that the connection to the database server is dropped.
Performs any necessary locking for thread safety.

### execute: ,...

- (NSInteger) execute: (NSString*)stmt,...;
Perform arbitrary operation which does not return any value.
This arguments to this method are a `nil` terminated list which are concatenated in the manner of the -query:,... method.
Arguments in the list are automatically quoted as necessary, with the behavior for string arguments being controlled by the autoquote setting.

       [db execute: @"UPDATE ", table, @" SET Name = ",
         myName, " WHERE ID = ", myId, nil];

Where the database backend support it, this method returns the count of the number of rows to which the operation applied. Otherwise this returns -1.

### execute: with:

- (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values;
Takes the statement and substitutes in values from the dictionary where markup of the format {key} is found.
Passes the result to the -execute:,... method.

       [db execute: @"UPDATE {Table} SET Name = {Name} WHERE ID = {ID}"
              with: values];

Arguments in the dictionary are automatically quoted as necessary, with the behavior for string arguments being controlled by the autoquote setting.
The markup format may also be {key?default} where default is a string to be used if there is no value for the key in the dictionary.
Where the database backend support it, this method returns the count of the number of rows to which the operation applied. Otherwise this returns -1.

### initWithConfiguration:

- (id) initWithConfiguration: (NSDictionary*)config;
Calls -initWithConfiguration:name: passing a `nil` reference name.

### initWithConfiguration: name:

- (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference;
Calls -initWithConfiguration:name:pool: passing `NO` to say the client is not in a pool.

### initWithConfiguration: name: pool:

- (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference pool: (SQLClientPool*)pool;
Initialise using the supplied configuration, or if that is `nil`, try to use values from NSUserDefaults (and automatically update when the defaults change).
Uses the reference name to determine configuration information... and if a `nil` name is supplied, defaults to the value of SQLClientName in the configuration dictionary (or in the standard user defaults). If there is no value for SQLClientName, uses the string 'Database'.
If pool is `nil` and a SQLClient instance already exists with the name used for this instance, the receiver is deallocated and the existing instance is retained and returned... there may only ever be one instance for a particular reference name which is not in a pool.
The config argument (or the SQLClientReferences user default) is a dictionary with names as keys and dictionaries as its values. Configuration entries from the dictionary corresponding to the database client are used if possible, general entries are used otherwise.
Database... is the name of the database to use, if it is missing then 'Database' may be used instead.
User... is the name of the database user to use, if it is missing then 'User' may be used instead.
Password... is the name of the database user password, if it is missing then 'Password' may be used instead.
ServerType... is the name of the backend server to be used... by convention the name of a bundle containing the interface to that backend. If this is missing then 'Postgres' is used.
The database name may be of the format 'name@host:port' when you wish to connect to a database on a different host over the network.

### isEqual:

- (BOOL) isEqual: (id)other;
Two clients are considered equal if they refer to the same database and are logged in as the same database user using the same protocol. These are the general criteria for transactions to be compatoible so that an SQLTransaction object generated by one client can be used by the other.

### isInTransaction

- (BOOL) isInTransaction;
Return the state of the flag indicating whether the library thinks a transaction is in progress. This flag is normally maintained by -begin , -commit , and -rollback .

### lastConnect

- (NSDate*) lastConnect;
Returns the date/time stamp of the last database connection established by the receiver, or `nil` if no connection has ever been established.

### lastOperation

- (NSDate*) lastOperation;
Returns the date/time stamp of the last database operation performed by the receiver, or `nil` if no operation has ever been done by it.
Simply connecting to or disconnecting from the databsse does not count as an operation.

### lockBeforeDate:

- (BOOL) lockBeforeDate: (NSDate*)limit;
This grabs the receiver for use by the current thread.
If limit is `nil` or in the past, makes a single immediate attempt.
Returns `NO` if it fails to obtain a lock by the specified date.
Must be matched by an -unlock if it succeeds.

### longestIdle:

- (SQLClient*) longestIdle: (SQLClient*)other;
Compares the receiver with the other client to see which one has been inactive but connected for longest (if they are connected) and returns that instance.
If neither is idle but connected, the method returns `nil`.
In a tie, the method returns the other instance.

### name

- (NSString*) name;
Return the database reference name for this instance (or `nil`).

### password

- (NSString*) password;
Return the database password for this instance (or `nil`).

### pool

- (SQLClientPool*) pool;
Return the pool to which the receiver belongs, or `nil` if it is not part of a connection pool.

### prepare: ,...

- (NSMutableArray*) prepare: (NSString*)stmt,...;
Calls [SQLClient -prepare:args:] where the argument list needs to be a `nil` terminated list of objects.

### prepare: args:

- (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args;
This is the method used to convert a query or statement to a standard form used internally by other methods.
This works to build an sql string by quoting any non-literal objects according to the autoquote setting, and concatenating the resulting strings in a `nil` terminated list.
Returns an array containing the statement as the first object and any NSData objects following. The NSData objects appear in the statement strings as the marker sequence - `'?'''?'`
If the returned array contains a single object, that object is a simple SQL query/statement.

### prepare: with:

- (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values;
This method is like [SQLClient -prepare:args:] but takes a dictionary of values to be substituted into the sql string.

### query: ,...

- (NSMutableArray*) query: (NSString*)stmt,...;

Perform arbitrary query which returns values.

This method handles its arguments in the same way as the -buildQuery:,... method and returns the result of the query.

       result = [db query: @"SELECT Name FROM ", table, nil];

Upon error, an exception is raised.

The query returns an array of records (each of which is represented by an SQLRecord object).

Each SQLRecord object contains one or more fields, in the order in which they occurred in the query. Fields may also be retrieved by name.

NULL field items are returned as NSNull objects.

Most other field items are returned as NSString objects.

Timestamp field items (a date and time) are returned as NSDate objects. If the database contains no timezone information, the local timezone is used.

### query: with:

- (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values;
Takes the query statement and substitutes in values from the dictionary (in the same manner as the -buildQuery:with: method) then executes the query and returns the response.

       result = [db query: @"SELECT Name FROM {Table} WHERE ID = {ID}"
                     with: values];

Any non-string values in the dictionary will be replaced by the results of the -quote: method.
The markup format may also be {key?default} where default is a string to be used if there is no value for the key in the dictionary.

### quote:

- (SQLLiteral*) quote: (id)obj;
Convert an object to a string suitable for use in an SQL query.
Normally the -execute:,... , and -query:,... methods will call this method automatically for everything apart from string objects.
Subclasses may override this method to provide appropriate quoting for types of object which need database backend specific quoting conventions. However, the default implementation should be OK for most cases:
This method makes use of -quoteString: to quote strings.
It formats NSDate objects as YYYY-MM-DD hh:mm:ss.mmm ?ZZZZ.
For NSNumber objects it simply uses their string descriptions.
For NSNull and `nil` the method returns NULL.
NSData objects are not quoted... they must not appear in queries, and where used for insert/update operations, they need to be passed to the -backendExecute: method unchanged.
NSArray and NSSet objects are quoted as sets containing the quoted elements from the collection. If you want to use SQL arrays (and your database backend supports it) you must explicitly use the -quoteArray: method to convert an NSArray to a literal database array representation.
Other classes are not supported unless they implement the -quoteForSQLClient: method to return a non-nil literal string value.
Attempts to quote an object of an unsupported class (one where the method returns `nil`) will cause an NSInvalidArgumentException.

### quoteArray:

- (SQLLiteral*) quoteArray: (NSArray*)a;
Description forthcoming.

### quoteArray: toString: quotingStrings:

- (NSMutableString*) quoteArray: (NSArray*)a toString: (NSMutableString*)s quotingStrings: (BOOL)q;
Description forthcoming.

### quoteArraySafe:

- (SQLLiteral*) quoteArraySafe: (NSArray*)a;
Description forthcoming.

### quoteBigInteger:

- (SQLLiteral*) quoteBigInteger: (int64_t)i;
Convert a big (64 bit) integer to a string suitable for use in an SQL query.

### quoteCString:

- (SQLLiteral*) quoteCString: (const char*)s;
Convert a 'C' string to a string suitable for use in an SQL query by using -quoteString: to convert it to a literal string format.
NB. a null pointer is treated as an empty string.

### quoteChar:

- (SQLLiteral*) quoteChar: (char)c;
Convert a single character to a string suitable for use in an SQL query by using -quoteString: to convert it to a literal string format.
NB. a nul character is not allowed and will cause an exception.

### quoteFloat:

- (SQLLiteral*) quoteFloat: (double)f;
Convert a float to a string suitable for use in an SQL query.

### quoteInteger:

- (SQLLiteral*) quoteInteger: (int)i;
Convert an integer to a string suitable for use in an SQL query.

### quoteName:

- (SQLLiteral*) quoteName: (NSString*)s;
Convert a string to a form suitable for use as a case sensitive table or column name in an SQL query. This uses the double quotes character rather than single quotes.

### quoteSet:

- (SQLLiteral*) quoteSet: (id)obj;
Quotes the values in any collection (responds to -objectEnumerator) as a set (bracketed list of values) for use in an SQL query.

### quoteString:

- (SQLLiteral*) quoteString: (NSString*)s;
Convert a string to a form suitable for use as a string literal in an SQL query.
Subclasses may override this for non-standard literal string quoting conventions.

### quotef: ,...

- (SQLLiteral*) quotef: (NSString*)fmt,...;
Produce a quoted string from the supplied arguments (printf style).

### rollback

- (void) rollback;
Revert a transaction for this database client.
If there is no transaction in progress, this method does nothing.

NB. You must not execute an SQL statement which would commit or rollback a transaction directly... use only this method or the -rollback method.

Where possible, consider using the SQLTransaction class rather than calling -begin -commit or -rollback yourself.

### setClientName:

- (void) setClientName: (NSString*)s;
Set the client name for this client.
If this is not set (or is set to nul) a globally unique string is used.
NB. Setting the name may not be reflected in the database server until the client disconnects and reconnects.

### setDatabase:

- (void) setDatabase: (NSString*)s;
Set the database host/name for this object.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.

### setName:

- (void) setName: (NSString*)s;
Set the database reference name for this object. This is used to differentiate between multiple connections to the database.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.
NB. attempts to change the name of an instance to that of an existing instance are ignored.

### setOptions:

- (void) setOptions: (NSDictionary*)o;
Sets any backend specific parameters for the database connection. The base class implementation does nothing; subclasses are expected to store any optional configuration information that they wish to use themselves.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.

### setPassword:

- (void) setPassword: (NSString*)s;
Set the database password for this object.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.

### setShouldTrim:

- (void) setShouldTrim: (BOOL)aFlag;
Sets an internal flag to indicate whether leading and trailing white space characters should be removed from values retrieved from the database by the receiver.

### setUser:

- (void) setUser: (NSString*)s;
Set the database user for this object.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.

### simpleExecute:

- (NSInteger) simpleExecute: (id)info;
Calls -backendExecute: in a safe manner.
Handles locking.
Maintains -lastOperation date.
Returns the result of the -backendExecute: method call.
Accepts a mutable array argument (as produced by the prepare methods) or a simple SQL statement (a string), otherwise raises an exception.

### simpleQuery:

- (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt;
Calls -simpleQuery:recordType:listType: with the default record class and default array class.

### simpleQuery: recordType: listType:

- (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype;
Calls -backendQuery:recordType:listType: in a safe manner.
Handles locking.
Maintains -lastOperation date.
The value of rtype must respond to the [SQLRecord +newWithValues:keys:count:] method.
If rtype is `nil` then the SQLRecord class is used.
The value of ltype must respond to the [NSObject +alloc] method to produce a container which must repond to the [NSMutableArray -initWithCapacity:] method to initialise itsself and the [NSMutableArray -addObject:] method to add records to the list.
If ltype is `nil` then the NSMutableArray class is used.
This library provides a few helper classes to provide alternative values for rtype and ltype.

### tryConnect

- (BOOL) tryConnect;
If there is no database connection, attempts to establish one.
This does not do automatic retries on connection failure.
Returns the current connection status.

### unlock

- (void) unlock;
Releases a lock previously obtained using -lockBeforeDate:

### user

- (NSString*) user;
Return the database user for this instance (or `nil`).

## Instance Variables for SQLClient Class

### _cache

@protected GSCache* _cache;
The cache for query results
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _cacheThread

@protected NSThread* _cacheThread;
Thread for cache queries
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _client

@protected NSString* _client;
Identifier within backend
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _committed

@protected uint64_t _committed;
Count of committed transactions
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _connectFails

@protected unsigned int _connectFails;
The count of connection failures
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _database

@protected NSString* _database;
The configured database name/host
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _debugging

@protected unsigned int _debugging;
The current debugging level
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _duration

@protected NSTimeInterval _duration;
Duration logging threshold
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _extra

@protected void* _extra;
Allow for extensions by allocating memory and pointing to it from the _extra ivar. That way we can avoid binary incompatibility between minor releases.
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _inTransaction

@protected BOOL _inTransaction;
A flag indicating whether this instance is currently within a transaction. This variable must only be set by the -begin , -commit or -rollback methods.
Are we inside a transaction?
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _lastConnect

@protected NSTimeInterval _lastConnect;
Last successful connect
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _lastOperation

@protected NSTimeInterval _lastOperation;
Timestamp of completion of last operation.
Maintained by -simpleExecute: -simpleQuery:recordType:listType: and [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] Also set for a failed connection attempt, but not reported by the -lastOperation method in that case.
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _lastStart

@protected NSTimeInterval _lastStart;
Last op start or connect
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _name

@protected NSString* _name;
Unique identifier for instance
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _names

@protected NSCountedSet* _names;
Track notification names
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _observers

@protected NSMapTable* _observers;
Observations of async events
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _password

@protected NSString* _password;
The configured password
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _pool

@protected SQLClientPool* _pool;
The pool of the client (or `nil`)
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _shouldTrim

@protected BOOL _shouldTrim;
A flag indicating whether leading and trailing white space in values read from the database should automatically be removed.
This should only be modified by the -setShouldTrim: method.
Should whitespace be trimmed?
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _statements

@protected NSMutableArray* _statements;
Uncommitted statements
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _user

@protected NSString* _user;
The configured user
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### connected

@protected BOOL connected;
A flag indicating whether this instance is currently connected to the backend database server. This variable must only be set by the -backendConnect or -backendDisconnect methods.

### extra

@protected void* extra;
For subclass specific data

### lock

@protected NSRecursiveLock* lock;
Maintain thread-safety

# Software documentation for the SQLClientPool class

## SQLClientPool : NSObject

> Declared in:
>   SQLClient.h

An SQLClientPool instance may be used to create/control a pool of client objects. Code may obtain autoreleased proxies to the clients from the pool and use them safe in the knowledge that they won't be used anywhere else... as soon as the client would be deallocated, it is returned to the pool.

All clients in the pool share the same cache object, so query results cached by one client will be available to other clients in the pool.

As a convenience, an SQLClientPool instance acts as a proxy for the clients it contains, so you may (where it makes sense) send the same messages to a pool that you would send to an individual client, and the pool will temporarily allocate one of its clients to handle it.
In this case the client will be returned to the pool immediately after the message has been handled (and subsequent messages may go to a different client), so you can't change settings or send any other method which would be required to be followed up by another message to the same client.

NB. Any client provided from a pool should be returned to the pool as soon as reasonably possible (and if left idle will have its connection to the server closed anyway) so that it can be used by other threads. If you want a permenantly open database connection you should use a normal SQLClient instance, not one from a pool. You must not call -addObserver:selector:name: on a client from a pool.

Instance Variables
Method summary

- -buildQuery:,...
- -buildQuery:with:
- -cache:query:,...
- -cache:query:with:
- -cache:simpleQuery:
- -cache:simpleQuery:recordType:listType:
- -cacheCheckSimpleQuery:
- -columns:
- -execute:,...
- -execute:with:
- -pool
- -prepare:,...
- -prepare:args:
- -prepare:with:
- -query:,...
- -query:with:
- -queryRecord:,...
- -queryString:,...
- -quote:
- -quoteArray:
- -quoteArray:toString:quotingStrings:
- -quoteArraySafe:
- -quoteBigInteger:
- -quoteCString:
- -quoteChar:
- -quoteFloat:
- -quoteInteger:
- -quoteName:
- -quoteSet:
- -quoteString:
- -quotef:,...
- -simpleExecute:
- -simpleQuery:
- -simpleQuery:recordType:listType:
- -singletons:
- -availableConnections
- -batch:
- -cache
- -committed
- -initWithConfiguration:name:max:min:
- -longDescription
- -maxConnections
- -minConnections
- -name
- -provideClient
- -provideClientBeforeDate:
- -provideClientBeforeDate:exclusive:
- -provideClientExclusive
- -purge
- -setCache:
- -setCacheThread:
- -setClientName:
- -setDebugging:
- -setDurationLogging:
- -setMax:min:
- -setPurgeAll:min:
- -statistics
- -status
- -swallowClient:
- -transaction

### availableConnections

- (int) availableConnections;
Returns the count of currently available connections in the pool.

### batch:

- (SQLTransaction*) batch: (BOOL)stopOnFailure;
Creates and returns an autoreleased SQLTransaction instance which will use the receiver as the database connection to perform transactions.

### cache

- (GSCache*) cache;
Returns the cache used by clients in the pool for storing the results of requests made through them. Creates a new cache if necessary.

### committed

- (uint64_t) committed;
Returns the number of committed transactions.

### initWithConfiguration: name: max: min:

- (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference max: (int)maxConnections min: (int)minConnections;
Creates a pool of clients using a single client configuration.
Calls -initWithConfiguration:name:pool: (passing `NO` to say the client is not in a pool) to create each client.
The value of maxConnections is the size of the pool (ie the number of clients created) and thus the maximum number of concurrent connections to the database server.
The value of minConnections is the minimum number of connected clients normally expected to be in the pool. The pool tries to ensure that it doesn't contain more than this number of idle connected clients.

### longDescription

- (NSString*) longDescription;
Returns a long description of the pool including statistics, status, and the description of a sample client.

### maxConnections

- (int) maxConnections;
Return the maximum number of database connections in the pool.

### minConnections

- (int) minConnections;
Return the minimum number of database connections in the pool.

### name

- (NSString*) name;
Returns the name of the database configuration for the connections in the pool.

### provideClient

- (SQLClient*) provideClient;
Fetches an (autoreleased) client from the pool.
This method blocks indefinitely waiting for a client to become available in the pool.
Calls -provideClientBeforeDate:exclusive: for a date in the distant future and for a non-exclusive client.

### provideClientBeforeDate:

- (SQLClient*) provideClientBeforeDate: (NSDate*)when;
Fetches an (autoreleased) client from the pool.
Calls -provideClientBeforeDate:exclusive: for a non-exclusive client.

### provideClientBeforeDate: exclusive:

- (SQLClient*) provideClientBeforeDate: (NSDate*)when exclusive: (BOOL)isLocal;
Fetches an (autoreleased) client from the pool.
If no client is or becomes available before the specified date then the method returns `nil`.
If when is `nil` then a date in the distant future is used so that the method will effectively wait forever to get a client.
If isLocal is `YES`, this method provides a client which will not be used elsewhere in the same thread until/unless the calling code returns it to the pool. Otherwise (isLocal is `NO`), the client may be used by other code in the same thread.
NB. Any client provided using this method should be returned to the pool as soon as reasonably possible (and if left idle will have its connection to the server closed anyway) so that it can be used by other threads. If you want a permenantly open database connection you should use a normal SQLClient instance, not one from a pool.

### provideClientExclusive

- (SQLClient*) provideClientExclusive;
Fetches an (autoreleased) client from the pool.
This method blocks indefinitely waiting for a client to become available in the pool.
Calls -provideClientBeforeDate:exclusive: for a date in the distant future and for an exclusive client.

### purge

- (void) purge;
Disconnects the least recently active unused database clients in the pool, but only while there are more than the minimum number of clients currently connected to the database, and only if the client has been idle for at least ten seconds.

### setCache:

- (void) setCache: (GSCache*)aCache;
Sets the cache for all the clients in the pool.

### setCacheThread:

- (void) setCacheThread: (NSThread*)aThread;
Sets the cache thread for all the clients in the pool.

### setClientName:

- (void) setClientName: (NSString*)s;
Set the client name for all the client connections in the pool.
If the argument is not `nil`, the name of each client in the pool is set to the argument with a suffix of '(x)' where x is the number of the client within the pool, otherwise (`nil` argument) each client is allocated a globally unique string as its name.
NB. This setting does not apply to new connections added when the pool maximum size is increased.

### setDebugging:

- (void) setDebugging: (unsigned int)level;
Set the debugging level for all clients in the pool.

### setDurationLogging:

- (void) setDurationLogging: (NSTimeInterval)threshold;
Set the duration logging threshold for all clients in the pool.

### setMax: min:

- (void) setMax: (int)maxConnections min: (int)minConnections;
Sets the pool size limits (number of connections we try to maintain).
The value of maxConnections is the size of the pool (ie the number of clients created) and thus the maximum number of concurrent connections to the database server.
The value of minConnections is the minimum number of connected clients normally expected to be in the pool. The pool tries to ensure that it contains at least this number of connected clients.
The value of maxConnections must be greater than or equal to that of minConnections and may not be greater than 100. The value of minConnections must be less than or equal to that of maxConnections and may not be less than 1.

### setPurgeAll: min:

- (void) setPurgeAll: (int)allSeconds min: (int)minSeconds;
Sets the ages (in seconds) after which idle connections are closed in the -purge method. Where there are excess connections (more than the minimum configured connection count) in the pool, minSeconds is used, otherwise allSeconds is used.

### statistics

- (NSString*) statistics;
Returns a string describing the usage of the pool.

### status

- (NSString*) status;
Returns a string describing the status of the pool.

### swallowClient:

- (BOOL) swallowClient: (SQLClient*)client;
Puts the client back in the pool. This happens automatically when a client from a pool would normally be deallocated so you don't generally need to do it.
Returns `YES` if the supplied client was from the pool, `NO` otherwise.

### transaction

- (SQLTransaction*) transaction;
Creates and returns an autoreleased SQLTransaction instance which will use the receiver as the database connection to perform transactions.

## Instance Variables for SQLClientPool Class

### _config

@protected NSDictionary* _config;
The pool configuration object
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _debugging

@protected unsigned int _debugging;
The current debugging level
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _delayWaits

@protected NSTimeInterval _delayWaits;
Time waiting for provisions
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _delayed

@protected uint64_t _delayed;
Count of delayed provisions
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _duration

@protected NSTimeInterval _duration;
Duration logging threshold
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _failWaits

@protected NSTimeInterval _failWaits;
Time waiting for timewouts
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _failed

@protected uint64_t _failed;
Count of timed out provisions
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _immediate

@protected uint64_t _immediate;
Immediate client provisions
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _items

@protected SQLClientPoolItem* _items;
The items in the pool
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _lock

@protected NSConditionLock* _lock;
Controls access to items
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _longest

@protected NSTimeInterval _longest;
Count of longest delay
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _max

@protected int _max;
Maximum connection count
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _min

@protected int _min;
Minimum connection count
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _name

@protected NSString* _name;
The pool configuration name
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _purgeAll

@protected NSTimeInterval _purgeAll;
Age to purge all connections
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _purgeMin

@protected NSTimeInterval _purgeMin;
Age to purge excess connections
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

# Software documentation for the SQLDictionaryBuilder class

## SQLDictionaryBuilder : NSObject

> Declared in:
>   SQLClient.h

Description forthcoming.

Instance Variables
Method summary

- -addObject:
- -alloc
- -content
- -initWithCapacity:
- -mutableCopyWithZone:
- -newWithValues:keys:count:

### addObject:

- (void) addObject: (id)anObject;
No need to do anything... the object will already have been added by the -newWithValues:keys:count: method.

### alloc

- (id) alloc;
When a container is supposed to be allocated, we just return the receiver (which will then quietly ignore -addObject: messages).

### content

- (NSMutableDictionary*) content;
Returns the content dictionary for the receiver.

### initWithCapacity:

- (id) initWithCapacity: (NSUInteger)capacity;
Creates a new content dictionary... this method will be called automatically by the SQLClient object when it performs a query, so there is no need to call it at any other time.

### mutableCopyWithZone:

- (id) mutableCopyWithZone: (NSZone*)aZone;
Makes a mutable copy of the content dictionary (called when a caching query uses this helper to produce the cached collection).

### newWithValues: keys: count:

- (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count;
This is the main workhorse of the class... it is called once for every record read from the database, and is responsible for adding that record to the content dictionary. The default implementation, instead of creating an object to hold the supplied record data, uses the two fields from the record as a key-value pair to add to the content dictionary, and returns `nil` as the record object. It's OK to return a `nil` object since we ignore the -addObject: argument.

## Instance Variables for SQLDictionaryBuilder Class

### content

@protected NSMutableDictionary* content;
Description forthcoming.

# Software documentation for the SQLLiteral class

## SQLLiteral : NSString

> Declared in:
>   SQLClient.h

The SQLLiteral subclass of NSString is used to tell [SQLClient -prepare:args:] and [SQLClient -prepare:with:] methods that a string is to be treated as a literal which should not be quoted when it is used as part of an SQL query or statement.
You should enable compile time checking of string types by defining the SQLCLIENT_COMPILE_TIME_QUOTE_CHECK preprocessor macro before including this header. When compile time checking is in place, the methods which expect a query or statement to be provided as a single string will be declared as taking an SQLLiteral argument rather than an NSString. The compiler will then complain about passing arguments of the wrong type.
NB. The runtime checking for literal strings actually uses different classes not the SQLLiteral class. In fact this class declaration is only used for compile time checking and you should not expect runtime checks to actually ever see an instance of this class.

# Software documentation for the SQLRecord class

## SQLRecord : NSArray

> Declared in:
>   SQLClient.h

An enhanced array to represent a record returned from a query. You should NOT try to create instances of this class except via the +newWithValues:keys:count: method.

SQLRecord is the abstract base class of a class cluster. If you wish to subclass it you must implement the primitive methods +newWithValues:keys:count: -count -keyAtIndex: -objectAtIndex: and -replaceObjectAtIndex:withObject:

NB. You do not need to use SQLRecord (or a subclass of it), all you actually need to supply is a class which responds to the +newWithValues:keys:count: method that the system uses to create new records... none of the other methods of the SQLRecord class are used internally by the SQLClient system.

Method summary

- +newWithValues:keys:
- +newWithValues:keys:count:
- -allKeys
- -count
- -dictionary
- -getKeys:
- -getObjects:
- -keyAtIndex:
- -keys
- -objectAtIndex:
- -objectForKey:
- -replaceObjectAtIndex:withObject:
- -setObject:forKey:
- -sizeInBytes:

### newWithValues: keys:

+ (id) newWithValues: (id*)v keys: (SQLRecordKeys*)k;
Create a new SQLRecord containing the specified fields.
NB. The values and keys are retained by the record rather than being copied.
A `nil` value is represented by [NSNull null].
This constructor will be used for subsequent records after the first in a query iff the first record created returns a non-nil result when sent the -keys method.

### newWithValues: keys: count:

+ (id) newWithValues: (id*)v keys: (NSString**)k count: (unsigned int)c;
Create a new SQLRecord containing the specified fields.
NB. The values and keys are retained by the record rather than being copied.
A `nil` value is represented by [NSNull null].
Keys must be unique string values (case insensitive comparison).

### allKeys

- (NSArray*) allKeys;
Returns an array containing the names of all the fields in the record.

### count

- (NSUInteger) count;
Returns the number of items in the record.
Subclasses must implement this method.

### dictionary

- (NSMutableDictionary*) dictionary;
Return the record as a mutable dictionary with the keys as the record field names standardised to be lowercase strings.

### getKeys:

- (void) getKeys: (id*)buf;
Optimised mechanism for retrieving all keys in order.

### getObjects:

- (void) getObjects: (id*)buf;
Optimised mechanism for retrieving all objects.

### keyAtIndex:

- (NSString*) keyAtIndex: (NSUInteger)index;
Subclasses must override this method.
Returns the key at the specified index.

### keys

- (SQLRecordKeys*) keys;
Returns the keys used by this record. The abstract class returns `nil`, so subclasses should override if they wish to make use of the +newWithValues:keys: method.

### objectAtIndex:

- (id) objectAtIndex: (NSUInteger)index;
Subclasses must override this method.
Returns the object at the specified indes.

### objectForKey:

- (id) objectForKey: (NSString*)key;
Returns the value of the named field.
The field name is case insensitive.

### replaceObjectAtIndex: withObject:

- (void) replaceObjectAtIndex: (NSUInteger)index withObject: (id)anObject;
Replaces the value at the specified index.
Subclasses must implement this method.

### setObject: forKey:

- (void) setObject: (id)anObject forKey: (NSString*)aKey;
Replaces the value of the named field.
The field name is case insensitive.
NB. You must be careful not to change the contents of a record which has been cached (unless you are sure you really want to), as you will be changing the contents of the cache, not just a private copy.

### sizeInBytes:

- (NSUInteger) sizeInBytes: (NSMutableSet*)exclude;
Return approximate size of this record in bytes.
The exclude set is used to specify objects to exclude from the calculation (to prevent recursion etc).

# Software documentation for the SQLRecordKeys class

## SQLRecordKeys : NSObject

> Declared in:
>   SQLClient.h

This class is used to hold key information for a set of SQLRecord objects produced by a single query.

Instance Variables
Method summary

- -count
- -indexForKey:
- -initWithKeys:count:
- -order

### count

- (NSUInteger) count;
Returns the number of keys in the receiver.

### indexForKey:

- (NSUInteger) indexForKey: (NSString*)key;
Returns the index of the object with the specified key, or NSNotFound if there is no such key.

### initWithKeys: count:

- (id) initWithKeys: (NSString**)keys count: (NSUInteger)c;
Initialiser

### order

- (NSArray*) order;
Returns an array containing the record field names in order.

## Instance Variables for SQLRecordKeys Class

### bytes

@protected NSUInteger bytes;
Description forthcoming.

### count

@protected NSUInteger count;
Description forthcoming.

### low

@protected NSMapTable* low;
Description forthcoming.

### map

@protected NSMapTable* map;
Description forthcoming.

### order

@protected NSArray* order;
Description forthcoming.

# Software documentation for the SQLSetBuilder class

## SQLSetBuilder : NSObject

> Declared in:
>   SQLClient.h

Description forthcoming.

Instance Variables
Method summary

- -addObject:
- -added
- -alloc
- -content
- -initWithCapacity:
- -mutableCopyWithZone:
- -newWithValues:keys:count:

### addObject:

- (void) addObject: (id)anObject;
No need to do anything... the object will already have been added by the -newWithValues:keys:count: method.

### added

- (NSUInteger) added;
Returns the number of objects actually added to the counted set.

### alloc

- (id) alloc;
When a container is supposed to be allocated, we just return the receiver (which will then quietly ignore -addObject: messages).

### content

- (NSCountedSet*) content;
Returns the counted set for the receiver.

### initWithCapacity:

- (id) initWithCapacity: (NSUInteger)capacity;
Creates a new content set... this method will be called automatically by the SQLClient object when it performs a query, so there is no need to call it at any other time.

### mutableCopyWithZone:

- (id) mutableCopyWithZone: (NSZone*)aZone;
Makes a mutable copy of the content dictionary (called when a caching query uses this helper to produce the cached collection).

### newWithValues: keys: count:

- (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count;
This is the main workhorse of the class... it is called once for every record read from the database, and is responsible for adding that record to the content set. The default implementation, instead of creating an object to hold the supplied record data, uses the singe field from the record to add to the content set, and returns `nil` as the record object. It's OK to return a `nil` object since we ignore the -addObject: argument.

## Instance Variables for SQLSetBuilder Class

### added

@protected NSUInteger added;
Description forthcoming.

### content

@protected NSCountedSet* content;
Description forthcoming.

# Software documentation for the SQLSingletonBuilder class

## SQLSingletonBuilder : NSObject

> Declared in:
>   SQLClient.h

Description forthcoming.
Method summary

- -newWithValues:keys:count:

### newWithValues: keys: count:

- (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count;
Description forthcoming.

# Software documentation for the SQLTransaction class

## SQLTransaction : NSObject

> Declared in:
>   SQLClient.h

> Conforms to:
>   NSCopying

The SQLTransaction transaction class provides a convenient mechanism for grouping together a series of SQL statements to be executed as a single transaction. It avoids the need for handling begin/commit, and should be as efficient as reasonably possible.
You obtain an instance by calling [SQLClient(Convenience) -transaction] , add SQL statements to it using the -add:,... and/or -add:with: methods, and then use the -execute method to perform all the statements as a single operation.
Any exception is caught and re-raised in the -execute method after any tidying up to leave the database in a consistent state.

Instance Variables
Method summary

- -add:,...
- -add:with:
- -addPrepared:
- -append:
- -copyWithZone:
- -count
- -execute
- -executeBatch
- -executeBatchReturningFailures:logExceptions:
- -insertTransaction:atIndex:
- -lock
- -owner
- -removeTransactionAtIndex:
- -reset
- -setResetOnExecute:
- -totalCount
- -transactionAtIndex:
- -unlock

### add: ,...

- (void) add: (NSString*)stmt,...;
Adds an SQL statement to the transaction. This is similar to [SQLClient -execute:,...] but does not cause any database operation until -execute is called, so it will not raise a database exception.

### add: with:

- (void) add: (NSString*)stmt with: (NSDictionary*)values;
Adds an SQL statement to the transaction. This is similar to [SQLClient -execute:with:] but does not cause any database operation until -execute is called, so it will not raise a database exception.

### addPrepared:

- (void) addPrepared: (NSArray*)statement;
Adds a prepared statement.

### append:

- (void) append: (SQLTransaction*)other;
Appends a copy of the other transaction to the receiver.
This provides a convenient way of merging transactions which have been built by different code modules, in order to have them all executed together in a single operation (for efficiency etc).
This does not alter the other transaction, so if the execution of a group of merged transactions fails, it is then possible to attempt to commit the individual transactions separately.
NB. All transactions appended must be using the same database connection (SQLClient/SQLClientPool instance).

### copyWithZone:

- (id) copyWithZone: (NSZone*)z;
Make a copy of the receiver.

### count

- (NSUInteger) count;
Returns the number of individual statements and/or subsidiary transactions which have been added to the receiver. For a count of the total number of statements, use the -totalCount method.

### execute

- (void) execute;

Performs any statements added to the transaction as a single operation. If any problem occurs, an NSException is raised, but the database connection is left in a consistent state and a partially completed operation is rolled back.

NB. If the database is not already in a transaction, this implicitly calls the -begin method to start the transaction before executing the statements.
The method always commits the transaction, even if the transaction was begun earlier rather than in -execute .
This behavior allows you to call [SQLClient -begin] , then run one or more queries, build up a transaction based upon the query results, and then -execute that transaction, causing the entire process to be commited as a single transaction.

### executeBatch

- (unsigned) executeBatch;
Convenience method which calls -executeBatchReturningFailures:logExceptions: with a `nil` failures argument and exception logging off.

### executeBatchReturningFailures: logExceptions:

- (unsigned) executeBatchReturningFailures: (SQLTransaction*)failures logExceptions: (BOOL)log;

This is similar to the -execute method, but may allow partial execution of the transaction if appropriate:

If the transaction was created using the [SQLClient(Convenience) -batch:] method and the transaction as a whole fails, individual statements are retried.
The stopOnFailure flag for the batch creation indicates whether the retries are stopped at the first statement to fail, or continue (skipping any failed statements).

If the transaction has had transactions appended to it, those subsidiary transactions may succeed or fail atomically depending on their individual attributes.

If the transaction was not created using [SQLClient(Convenience) -batch:] , then calling this method is equivalent to calling the -execute method.

If any statements/transactions in the batch fail, they are added to the transaction supplied in the failures parameter (if it's not `nil`) so that you can retry them later.
NB. statements/transactions which are not executed at all (because the batch is set to stop on the first failure) are also added to the failures transaction.

If the log argument is `YES`, then any exceptions encountered when executing the batch are logged using the [SQLClient(Logging) -debug:,...] method, even if debug logging is not enabled with [SQLClient(Logging) -setDebugging:] .

The method returns the number of statements which actually succeeded.

### insertTransaction: atIndex:

- (void) insertTransaction: (SQLTransaction*)trn atIndex: (unsigned)index;
Insert trn at the index'th position in the receiver.
The transaction trn must be non-empty and must use the same database client/pool as the receiver.

### lock

- (void) lock;
Explicitly obtains the transaction lock so that multiple methods may be called without another thread interfering. Each call to this method must be matched by a call to the -unlock method.

### owner

- (id) owner;
Returns the database client with which this instance operates.
This client is retained by the transaction.
If the transaction was created by/for an SQLClientPool, this method returns that pool rather than an individual client.

### removeTransactionAtIndex:

- (void) removeTransactionAtIndex: (unsigned)index;
Remove the index'th transaction or statement from the receiver.

### reset

- (void) reset;
Resets the transaction, removing all previously added statements. This allows the transaction object to be re-used for multiple transactions. See also the -setResetOnExecute: method.

### setResetOnExecute:

- (BOOL) setResetOnExecute: (BOOL)aFlag;
Configures the transaction to be reset automatically whenever it is successfully executed. Normally transaction execution leaves all the statements in the transaction after execution.
Returns the previous setting.

### totalCount

- (unsigned) totalCount;
Returns the total count of statements in this transaction including those in any subsidiary transactions. For a count of the statements and/or transactions directly added to the receiver, use the -count method.

### transactionAtIndex:

- (SQLTransaction*) transactionAtIndex: (unsigned)index;
Return an autoreleased copy of the index'th transaction or statement added to the receiver.
Since the returned transaction contains a copy of the statement/transaction in the receiver, you can modify it without effecting the original.

### unlock

- (void) unlock;
Explicitly unlocks the thransaction. This should only be called by code which has previously called the -lock method.

## Instance Variables for SQLTransaction Class

### _batch

@protected BOOL _batch;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _count

@protected unsigned int _count;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _info

@protected NSMutableArray* _info;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _lock

@protected NSRecursiveLock* _lock;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _owner

@protected id _owner;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _reset

@protected BOOL _reset;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

### _stop

@protected BOOL _stop;
Warning the underscore at the start of the name of this instance variable indicates that, even though it is not technically private, it is intended for internal use within the package, and you should not use the variable in other code.

# Software documentation for the NSObject(SQLClient) category

## NSObject(SQLClient)

> Declared in:
>   SQLClient.h

This category is to extend NSObject with SQL oriented helper methods.
Method summary

- -isNull
- -quoteBigInteger
- -quoteBigNatural
- -quoteBigPositive
- -quoteForSQLClient:
- -quoteInteger
- -quoteNatural
- -quotePositive

### isNull

- (BOOL) isNull;
Trivial method to test a field in a record returned from the database to see if it is a NULL. This is equivalent to
(receiver == [NSNull null] ? `YES` : `NO`)

### quoteBigInteger

- (SQLLiteral*) quoteBigInteger;
If the receiver can be represented as a 64bit integer, return the string literal representation as used in SQL, otherwise raise exception.

### quoteBigNatural

- (SQLLiteral*) quoteBigNatural;
If the receiver can be represented as a 64bit non-negative integer, return the string literal representation as used in SQL, otherwise raise exception.

### quoteBigPositive

- (SQLLiteral*) quoteBigPositive;
If the receiver can be represented as a 64bit positive (not zero) integer, return the string literal representation as used in SQL, otherwise raise exception.

### quoteForSQLClient:

- (SQLLiteral*) quoteForSQLClient: (SQLClient*)db;
Classes may override this method to provide a value for use as part of an SQL query or statement. The method is used internally when quoting objects.
The db argument may be examined to enable a class to support different quoting for different database backends, but an implementation must at least support quoting appropriate for standard SQL.
The default NSObject implementation simply returns `nil`, which means that the object may not be used in an SQL query/statement.

### quoteInteger

- (SQLLiteral*) quoteInteger;
If the receiver can be represented as a 32bit integer, return the string literal representation as used in SQL, otherwise raise exception.

### quoteNatural

- (SQLLiteral*) quoteNatural;
If the receiver can be represented as a 32bit non-negative integer, return the string literal representation as used in SQL, otherwise raise exception.

### quotePositive

- (SQLLiteral*) quotePositive;
If the receiver can be represented as a 32bit positive (not zero) integer, return the string literal representation as used in SQL, otherwise raise exception.

# Software documentation for the SQLClient(Caching) category

## SQLClient(Caching)

> Declared in:
>   SQLClient.h

This category provides methods for caching the results of queries in order to reduce the number of client-server trips and the database load produced by an application which needs update its information from the database frequently.
Method summary

- -cache
- -cache:query:,...
- -cache:query:with:
- -cache:simpleQuery:
- -cache:simpleQuery:recordType:listType:
- -cacheCheckSimpleQuery:
- -setCache:
- -setCacheThread:

### cache

- (GSCache*) cache;
Returns the cache used by the receiver for storing the results of requests made through it. Creates a new cache if necessary.

### cache: query: ,...

- (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt,...;
Calls [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] with the default record class, array class, and with a query string formed from stmt and the following values (if any).

### cache: query: with:

- (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt with: (NSDictionary*)values;
Calls [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] with the default record class array class and with a query string formed from stmt and values.

### cache: simpleQuery:

- (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt;
Calls [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] with the default record class and array class.

### cache: simpleQuery: recordType: listType:

- (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype;
If the result of the query is already cached and has not expired, return an autoreleased mutable copy. Otherwise, perform the query and cache the result giving it the specified lifetime in seconds.
If seconds is negative, the query is performed irrespective of whether it is already cached, and its absolute value is used to set the lifetime of the results.
If seconds is zero, the cache for this query is emptied.
Handles locking.
Maintains -lastOperation date.
The value of rtype must respond to the [SQLRecord +newWithValues:keys:count:] method.
If rtype is `nil` then the SQLRecord class is used.
The value of ltype must respond to the [NSObject +alloc] method to produce a container which must repond to the [NSMutableArray -initWithCapacity:] method to initialise itsself, the [NSMutableArray -addObject:] method to add records to the list, and the [NSMutableArray -count] method to return the number of records added.
If ltype is `nil` then the NSMutableArray class is used.
The list produced by this argument is used as the return value of this method.
NB. cache lookups for the instance created from ltype will be provided by sending -mutableCopy and autorelease messages to the original instance.
If a cache thread has been set using the -setCacheThread: method, and the [SQLClient(Caching) -cache:simpleQuery:recordType:listType:] method is called from a thread other than the cache thread, then any query to retrieve uncached data will be performed in the cache thread, and for cached (but expired) data, the old (expired) results may be returned... in which case an asynchronous query to update the cache will be executed as soon as possible in the cache thread.

### cacheCheckSimpleQuery:

- (NSMutableArray*) cacheCheckSimpleQuery: (NSString*)stmt;
Returns an autoreleased mutable copy of the cached object corresponding to the supplied query/statement (or `nil` if no such object is cached).

### setCache:

- (void) setCache: (GSCache*)aCache;
Sets the cache to be used by the receiver for storing the results of requests made through it.
If aCache is `nil`, the current cache is released, and a new cache will be automatically created as soon as there is a need to cache anything.

### setCacheThread:

- (void) setCacheThread: (NSThread*)aThread;
Sets the thread to be used to retrieve data to populate the cache.
All cached queries will be performed in this thread (if non-nil).
The setting of a thread for the cache also implies that expired items in the cache may not be removed when they are queried from another thread, rather they can be kept (if they are not too old) and an asynchronous query to update them will be run on the cache thread.
The rule is that, if the item's age is more than twice its nominal lifetime, it will be retrieved immediately, otherwise it will be retrieved asynchronously.
Currently this may only be the main thread or `nil`. Any attempt to set another thread will use the main thread instead.

# Software documentation for the SQLClient(Convenience) category

## SQLClient(Convenience)

> Declared in:
>   SQLClient.h

This category contains convenience methods including those for frequently performed database operations... message logging etc.
Method summary

- +columns:
- +singletons:
- -batch:
- -columns:
- -queryRecord:,...
- -queryString:,...
- -singletons:
- -transaction

### columns:

+ (NSMutableArray*) columns: (NSMutableArray*)records;
Convenience method to deal with the results of a query converting the normal array of records into an array of record columns. Each column in the array is an array containing all the values from that column.

### singletons:

+ (void) singletons: (NSMutableArray*)records;
Convenience method to deal with the results of a query where each record contains a single field... it converts the array of records returned by the query to an array containing the fields.
NB. This does not check that the contents of the records array are actually instances of SQLRecord , so you must ensure you don't call it more than once on the same array (something that may happen if you retrieve the array using a cache based query).

### batch:

- (SQLTransaction*) batch: (BOOL)stopOnFailure;
Returns a transaction object configured to handle batching and execute part of a batch of statements if execution of the whole using the [SQLTransaction -executeBatch] method fails.
If stopOnFailure is `YES` than execution of the transaction will stop with the first statement to fail, otherwise it will execute all the statements it can, skipping any failed statements.

### columns:

- (NSMutableArray*) columns: (NSMutableArray*)records;
The same as the [SQLClient(Convenience) +columns:] method.

### queryRecord: ,...

- (SQLRecord*) queryRecord: (NSString*)stmt,...;
Executes a query (like the -query:,... method) and checks the result (raising an exception if the query did not contain a single record) and returns the resulting record.

### queryString: ,...

- (NSString*) queryString: (NSString*)stmt,...;
Executes a query (like the -query:,... method) and checks the result.
Raises an exception if the query did not contain a single record, or if the record did not contain a single field.
Returns the resulting field as a string.

### singletons:

- (void) singletons: (NSMutableArray*)records;
The same as the [SQLClient(Convenience) +singletons:] method.

### transaction

- (SQLTransaction*) transaction;
Creates and returns an autoreleased SQLTransaction instance which will use the receiver as the database connection to perform transactions.

# Software documentation for the SQLClient(Logging) category

## SQLClient(Logging)

> Declared in:
>   SQLClient.h

This category porovides basic methods for logging debug information.
Method summary

- +debugging
- +durationLogging
- +setDebugging:
- +setDurationLogging:
- -debug:,...
- -debugging
- -durationLogging
- -setDebugging:
- -setDurationLogging:

### debugging

+ (unsigned int) debugging;
Return the class-wide debugging level, which is inherited by all newly created instances.

### durationLogging

+ (NSTimeInterval) durationLogging;
Return the class-wide duration logging threshold, which is inherited by all newly created instances.

### setDebugging:

+ (void) setDebugging: (unsigned int)level;
Set the debugging level to be inherited by all new instances.
See [SQLClient(Logging) -setDebugging:] for controlling an individual instance of the class.

### setDurationLogging:

+ (void) setDurationLogging: (NSTimeInterval)threshold;
Set the duration logging threshold to be inherited by new instances.
See [SQLClient(Logging) -setDurationLogging:] for controlling an individual instance of the class.

### debug: ,...

- (void) debug: (NSString*)fmt,...;
The default implementation calls NSLogv to log a debug message.
Override this in a category to provide more sophisticated logging.
Do NOT override with code which can be slow or which calls (directly or indirectly) any SQLCLient methods, since this method will be used inside locked regions of the SQLClient code and you could cause deadlocks or long delays to other threads using the class.

### debugging

- (unsigned int) debugging;
Return the current debugging level.
A level of zero (default) means that no debug output is produced, except for that concerned with logging the database transactions taking over a certain amount of time (see the -setDurationLogging: method).

### durationLogging

- (NSTimeInterval) durationLogging;
Returns the threshold above which queries and statements taking a long time to execute are logged. A negative value (default) indicates that this logging is disabled. A value of zero means that all statements are logged.

### setDebugging:

- (void) setDebugging: (unsigned int)level;
Set the debugging level of this instance... overrides the default level inherited from the class.

### setDurationLogging:

- (void) setDurationLogging: (NSTimeInterval)threshold;
Set a threshold above which queries and statements taking a long time to execute are logged. A negative value (default) disables this logging. A value of zero logs all statements.

# Software documentation for the SQLClient(Notifications) category

## SQLClient(Notifications)

> Declared in:
>   SQLClient.h

This category contains methods for asynchronous notification of events via the database (for those database backends which support it: currently only PostgreSQL).
Method summary

- -addObserver:selector:name:
- -postNotificationName:payload:
- -removeObserver:name:

### addObserver: selector: name:

- (void) addObserver: (id)anObserver selector: (SEL)aSelector name: (NSString*)name;
Adds anObserver to receive notifications when the backend database server sends an asynchronous event identified by the specified name (which must be a valid database identifier).
When a notification (NSNotification instance) is received by the method specified by aSelector, its object will be the SQLClient instance to which anObserver was added and its userInfo dictionary will contain the key 'Local' and possibly the key 'Payload'.
If the 'Local' value is the boolean `YES`, the notification originated as an action by this SQLClient instance.
If the 'Payload' value is not `nil`, then it is a string providing extra information about the notification.
Notifications are posted asynchronously using the default notification queue for the thread which receives them (or the main thread if the receiving thread run loop is not active), so they should be delivered to the observer after the database statement in which they were detected has completed. However, delivery of the notification could still occur inside a transaction if the -begin and -commit statements are used. For this reason, observing code may want to use the -lockBeforeDate: -isInTransaction and -unlock methods to ensure that they don't interfere with ongoing transactions.
For observation of notifications to be immediately effective, the instance must be connected to the database (and remain connected), so you can't call this method on a client from a pool, and you should make sure that you don't close the client connection (or if you do, that you make sure to re-open it in order to start receiving notifications again).
Each observer, may only have one observation set up for a particular name. If an attempt is made to add a second observation for the same name it will be silently ignored.

### postNotificationName: payload:

- (void) postNotificationName: (NSString*)name payload: (NSString*)more;
Posts a notification via the database. The name is an SQL identifier (for which observers may have registered) and the extra payload information may be `nil` if not required.

### removeObserver: name:

- (void) removeObserver: (id)anObserver name: (NSString*)name;
Removes anObserver as an observer for asynchronous notifications from the database server.
If name is omitted, the observer will be removed for all names.
If anObserver is `nil`, the removal will be performed for all current observers (and if both name and anObserver are `nil`, then all observations are removed).
Any attempt to remove a non existent observation is silently ignored.

# Software documentation for the SQLClient(Quote) category

## SQLClient(Quote)

> Declared in:
>   SQLClient.h

This category encapsulates methods used to control automatic quoting of non-literal strings.
The point of this feature is to help prevent SQL injection attacks on your software (where you read in something from some UI, and use that data in creating a database query/statement, and an attacker might try to fool your code into doing something bad to the database).
When autoquote is turned on, the methods to build queries/statements ([SQLClient-prepare:args:] and [SQLClient -prepare:with:] and other methods based on those) will perform a runtime check for strings in the arguments list they are given, and will automatically quote any string which is not considered a literal.
The types of literal string are:

compiler literal
  A string literal in your source code of the form @"text", generated by the compiler.
  The rationale is that if it's a literal constant in the source code, the programmer should know (and be able to clearly see) that it's properly quoted for the context in which it is used.
copy literal
  A string of a special class which has been produced by calling one of the quote methods, or by calling the SQLClientCopyLiteral() , SQLClientMakeLiteral() , or SQLClientNewLiteral() functions to make a copy of a string to be treated as a literal.
proxy literal
  A string of a special class which has been produced by calling the SQLClientProxyLiteral() function to wrap an existing string to mark it to be treated as a literal. This should only be used as a performance tweak when a programmer has built a very large SQL statement, and copying it would hurt performance.

NB. column values in the results of a database query are not returned as literals unless they are NULL or come from a column whose actual type is a form of number or boolean (since booleans and numbers do not need any form of quoting in an SQL query/statement).
Method summary

- +autoquote
- +autoquoteWarning
- +setAutoquote:
- +setAutoquoteWarning:

### autoquote

+ (BOOL) autoquote;
Returns a BOOL saying whether autoquote is on or off.

### autoquoteWarning

+ (BOOL) autoquoteWarning;
Returns a BOOL saying whether autoquote warnings are on or off.

### setAutoquote:

+ (void) setAutoquote: (BOOL)aFlag;
Turns autoquote on/off for the process.
When autoquote is on, the arguments to the [SQLClient -prepare:args:] method (and therefore all methods that use it) are automatically quoted unless they are literal strings.
The purpose of autoquoting is to help prevent SQL injection attacks on your software; it helps ensure that only strings you really want to use literally are embedded in the SQL without quoting.

### setAutoquoteWarning:

+ (void) setAutoquoteWarning: (BOOL)aFlag;
Turns autoquote warning on/off for the process.
When autoquote warning is on, an NSLog() warning is generated whenever the arguments to the [SQLClient -prepare:args:] method (and therefore all methods that use it) are automatically quoted (or would be if autoquote was turned on).
Turn this on when using software which you expect to migrate to using autoquote.

# Software documentation for the SQLClient(Subclass) category

## SQLClient(Subclass)

> Declared in:
>   SQLClient.h

This category contains the methods which a subclass must override to provide a working instance, and helper methods for the backend implementations.
Application programmers should not call the backend methods directly.

When subclassing to produce a backend driver bundle, please be aware that the subclass must NOT introduce additional instance variables. Instead the extra instance variable is provided for use as a pointer to subclass specific data.

Method summary

- -backendConnect
- -backendDisconnect
- -backendExecute:
- -backendListen:
- -backendNotify:payload:
- -backendQuery:recordType:listType:
- -backendUnlisten:
- -copyEscapedBLOB:into:
- -insertBLOBs:intoStatement:length:withMarker:length:giving:
- -lengthOfEscapedBLOB:

### backendConnect

- (BOOL) backendConnect;
Subclasses must override this method.
Attempts to establish a connection to the database server.
Returns a flag to indicate whether the connection has been established.
If a connection was already established, returns `YES` and does nothing.
You should not need to use this method normally, as it is called for you automatically when necessary.

Subclasses must implement this method to establish a connection to the database server process (and initialise the extra instance variable if necessary), setting the connected instance variable to indicate the state of the object.

This method must call +purgeConnections: to ensure that there is a free slot for the new connection.

Application code must not call this method directly, it is for internal use only. The -connect method calls this method if the connected instance variable is `NO`.

### backendDisconnect

- (void) backendDisconnect;
Subclasses must override this method.
Disconnect from the database unless already disconnected.

This method is called automatically when the receiver is deallocated or reconfigured, and may also be called automatically when there are too many database connections active.

If the receiver is an instance of a subclass which uses the extra instance variable, it must clear that variable in the -backendDisconnect method, because a reconfiguration may cause the class of the receiver to change.

This method must set the connected instance variable to `NO`.

Application code must not call this method directly, it is for internal use only. The -disconnect method calls this method if the connected instance variable is `YES`.

### backendExecute:

- (NSInteger) backendExecute: (NSArray*)info;
Subclasses must override this method.
Perform arbitrary operation which does not return any value.
This method has a single argument, an array containing the string representing the statement to be executed as its first object, and an optional sequence of data objects following it.

       [db backendExecute: [NSArray arrayWithObject:
         @"UPDATE MyTable SET Name = 'The name' WHERE ID = 123"]];

The backend implementation is required to perform the SQL statement using the supplied NSData objects at the points in the statement marked by the `'?'''?'` sequence. The marker saequences are inserted into the statement at an earlier stage by the -execute:,... and -execute:with: methods.

Callers should lock the instance using the lock instance variable for the duration of the operation, and unlock it afterwards.

NB. callers (other than the -begin , -commit , and -rollback methods) should not pass any statement to this method which would cause a transaction to begin or end.

Application code must not call this method directly, it is for internal use only.

Where the database backend support it, this method returns the count of the number of rows to which the operation applied. Otherwise this returns -1.

### backendListen:

- (void) backendListen: (NSString*)name;
Subclasses must override this method.
Called to enable asynchronous notification of database events using the specified name (which must be a valid identifier consisting of ascii letters, digits, and underscore characters, starting with a letter).
Repeated calls to list on the same name should be treated as a single call.
The backend is responsible for implicitly unlistening when a connection is closed.
There is a default implementation which does nothing ... for backends which don't support asynchronous notifications.
If a backend does support asynchronous notifications, it should do so by posting NSNotification instances to the main thread [NSNotificationQueue defaultQueue] with the posting style NSPostASAP (to post asynchronously) and using the SQLClient instance as the notification object and supplying any payload as a string using the 'Payload' key in the NSNotification userInfo dictionary. The userInfo dictionary should also contain a boolean (NSNumber) value, using the 'Local' key, to indicate whether the notification was sent by the current SQLClient instance or by some other client/

### backendNotify: payload:

- (void) backendNotify: (NSString*)name payload: (NSString*)more;
Subclasses must override this method.
The backend should implement this to send asynchronous notifications to anything listening for them. The name of the notification is an SQL identifier used for listening for the asynchronous data.
The payload string may be `nil` if no additional information is needed in the notification.

### backendQuery: recordType: listType:

- (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype;
Subclasses must override this method.

Perform arbitrary query which returns values.

       result = [db backendQuery: @"SELECT Name FROM Table"
                      recordType: [SQLRecord class]]
                        listType: [NSMutableArray class]];

Upon error, an exception is raised.

The query returns an array of records (each of which is represented by an SQLRecord object).

Each SQLRecord object contains one or more fields, in the order in which they occurred in the query. Fields may also be retrieved by name.

NULL field items are returned as NSNull objects.

Callers should lock the instance using the lock instance variable for the duration of the operation, and unlock it afterwards.

Application code must not call this method directly, it is for internal use only.

The rtype argument specifies an object to be used to create the records produced by the query.
This is provided as a performance optimisation when you want to store data directly into a special class of your own.
The object must respond to the [SQLRecord +newWithValues:keys:count:] method to produce a new record initialised with the supplied data.

The ltype argument specifies an object to be used to create objects to store the records produced by the query.
The should be a subclass of NSMutableArray. It must at least implement the [NSObject +alloc] method to create an instance to store records. The instance must implement [NSMutableArray -initWithCapacity:] to initialise itsself, [NSMutableArray -addObject:] to allow the backend to add records to it, and -count to return the number of records added.
For caching to work, it must be possible to make a mutable copy of the instance using the mutableCopy method.

### backendUnlisten:

- (void) backendUnlisten: (NSString*)name;
Subclasses must override this method.
Called to disable asynchronous notification of database events using the specified name. This has no effect if the name has not been used in an earlier call to -backendListen: , or if the name has already been unlistened since the last call to listen. on it.
There is a default implementation which does nothing... for backends which don't support asynchronous notifications.

### copyEscapedBLOB: into:

- (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf;
Subclasses must override this method.
This method is only for the use of the -insertBLOBs:intoStatement:length:withMarker:length:giving: method.
Subclasses which need to insert binary data into a statement must implement this method to copy the escaped data into place and return the number of bytes actually copied.

### insertBLOBs: intoStatement: length: withMarker: length: giving:

- (const void*) insertBLOBs: (NSArray*)blobs intoStatement: (const void*)statement length: (unsigned)sLength withMarker: (const void*)marker length: (unsigned)mLength giving: (unsigned*)result;

This method is a convenience method provided for subclasses which need to insert escaped binary data into an SQL statement before sending the statement to a backend server process. This method makes use of the -copyEscapedBLOB:into: and -lengthOfEscapedBLOB: methods, which must be implemented by the subclass.

The blobs array is an array containing the original SQL statement string (unused by this method) followed by the data items to be inserted.

The statement and sLength arguments specify the datastream to be copied and into which the BLOBs are to be inserted.

The marker and mLength arguments specify the sequence of marker bytes in the statement which indicate a position for insertion of an escaped BLOB.

The method returns either the original statement or a copy containing the escaped BLOBs. The length of the returned data is stored in result.

### lengthOfEscapedBLOB:

- (unsigned) lengthOfEscapedBLOB: (NSData*)blob;
Subclasses must override this method.
This method is only for the use of the -insertBLOBs:intoStatement:length:withMarker:length:giving: method.
Subclasses which need to insert binary data into a statement must implement this method to return the length of the escaped bytestream which will be inserted.

# Software documentation for the SQLClientPool(Convenience) category

## SQLClientPool(Convenience)

> Declared in:
>   SQLClient.h

This category lists the convenience methods provided by a pool instance for proxying messages to a one-off client instance in the pool.
The behavior of each method is, of course, as documentf for instances of the SQLClient class.
Method summary

- -buildQuery:,...
- -buildQuery:with:
- -cache:query:,...
- -cache:query:with:
- -cache:simpleQuery:
- -cache:simpleQuery:recordType:listType:
- -cacheCheckSimpleQuery:
- -columns:
- -execute:,...
- -execute:with:
- -pool
- -prepare:,...
- -prepare:args:
- -prepare:with:
- -query:,...
- -query:with:
- -queryRecord:,...
- -queryString:,...
- -quote:
- -quoteArray:
- -quoteArray:toString:quotingStrings:
- -quoteArraySafe:
- -quoteBigInteger:
- -quoteCString:
- -quoteChar:
- -quoteFloat:
- -quoteInteger:
- -quoteName:
- -quoteSet:
- -quoteString:
- -quotef:,...
- -simpleExecute:
- -simpleQuery:
- -simpleQuery:recordType:listType:
- -singletons:

### buildQuery: ,...

- (SQLLiteral*) buildQuery: (NSString*)stmt,...;
Description forthcoming.

### buildQuery: with:

- (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values;
Description forthcoming.

### cache: query: ,...

- (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt,...;
Description forthcoming.

### cache: query: with:

- (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt with: (NSDictionary*)values;
Description forthcoming.

### cache: simpleQuery:

- (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt;
Description forthcoming.

### cache: simpleQuery: recordType: listType:

- (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype;
Description forthcoming.

### cacheCheckSimpleQuery:

- (NSMutableArray*) cacheCheckSimpleQuery: (NSString*)stmt;
Description forthcoming.

### columns:

- (NSMutableArray*) columns: (NSMutableArray*)records;
Description forthcoming.

### execute: ,...

- (NSInteger) execute: (NSString*)stmt,...;
Description forthcoming.

### execute: with:

- (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values;
Description forthcoming.

### pool

- (SQLClientPool*) pool;
Description forthcoming.

### prepare: ,...

- (NSMutableArray*) prepare: (NSString*)stmt,...;
Description forthcoming.

### prepare: args:

- (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args;
Description forthcoming.

### prepare: with:

- (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values;
Description forthcoming.

### query: ,...

- (NSMutableArray*) query: (NSString*)stmt,...;
Description forthcoming.

### query: with:

- (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values;
Description forthcoming.

### queryRecord: ,...

- (SQLRecord*) queryRecord: (NSString*)stmt,...;
Description forthcoming.

### queryString: ,...

- (NSString*) queryString: (NSString*)stmt,...;
Description forthcoming.

### quote:

- (SQLLiteral*) quote: (id)obj;
Description forthcoming.

### quoteArray:

- (SQLLiteral*) quoteArray: (NSArray*)a;
Description forthcoming.

### quoteArray: toString: quotingStrings:

- (NSMutableString*) quoteArray: (NSArray*)a toString: (NSMutableString*)s quotingStrings: (BOOL)_q;
Description forthcoming.

### quoteArraySafe:

- (SQLLiteral*) quoteArraySafe: (NSArray*)a;
Description forthcoming.

### quoteBigInteger:

- (SQLLiteral*) quoteBigInteger: (int64_t)i;
Description forthcoming.

### quoteCString:

- (SQLLiteral*) quoteCString: (const char*)s;
Description forthcoming.

### quoteChar:

- (SQLLiteral*) quoteChar: (char)c;
Description forthcoming.

### quoteFloat:

- (SQLLiteral*) quoteFloat: (double)f;
Description forthcoming.

### quoteInteger:

- (SQLLiteral*) quoteInteger: (int)i;
Description forthcoming.

### quoteName:

- (SQLLiteral*) quoteName: (NSString*)s;
Description forthcoming.

### quoteSet:

- (SQLLiteral*) quoteSet: (id)obj;
Description forthcoming.

### quoteString:

- (SQLLiteral*) quoteString: (NSString*)s;
Description forthcoming.

### quotef: ,...

- (SQLLiteral*) quotef: (NSString*)fmt,...;
Description forthcoming.

### simpleExecute:

- (NSInteger) simpleExecute: (NSArray*)info;
Description forthcoming.

### simpleQuery:

- (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt;
Description forthcoming.

### simpleQuery: recordType: listType:

- (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype;
Description forthcoming.

### singletons:

- (void) singletons: (NSMutableArray*)records;
Description forthcoming.

# SQLClient types

### SQLClientPoolItem

typedef struct _SQLClientPoolItem SQLClientPoolItem;
Description forthcoming.

# SQLClient constants

### SQLClientDidConnectNotification

NSString* const SQLClientDidConnectNotification;
Notification sent when an instance becomes connected to the database server. The notification object is the instance connected.

### SQLClientDidDisconnectNotification

NSString* const SQLClientDidDisconnectNotification;
Notification sent when an instance becomes disconnected from the database server. The notification object is the instance disconnected.

# SQLClient variables

### SQLConnectionException

NSString* SQLConnectionException;
Exception for when a connection to the server is lost.

### SQLEmptyException

NSString* SQLEmptyException;
Exception for when a query is supposed to return data and doesn't.

### SQLException

NSString* SQLException;
Exception raised when an error with the remote database server occurs.

### SQLUniqueException

NSString* SQLUniqueException;
Exception for when an insert/update would break the uniqueness of a field or index.

# SQLClient functions

### SQLClientCopyLiteral

SQLLiteral* SQLClientCopyLiteral(NSString* aString);
Creates and returns a copy of aString as a literal, whether or not aString is already a literal string.

### SQLClientIsLiteral

BOOL SQLClientIsLiteral(NSString* aString);
Function to test an object to see if it is considered to be a literal string by SQLClient. Use this rather than trying to chewck the class hierarchy (which is not reliable).

### SQLClientMakeLiteral

SQLLiteral* SQLClientMakeLiteral(NSString* aString);
Returns a literal string version of aString.
A literal is an instance of the literal string class produced by the compiler or the SQLString class (which subclasses it).
If aString is already a literal string, this method returns it unchanged, otherwise the returned value is an autoreleased newly created copy of the argument.

### SQLClientNewLiteral

SQLLiteral* SQLClientNewLiteral(const char* bytes, unsigned int count);
Function to create an SQL literal (string which won't be autoquoted) from a UTF8 or ASCII C string whose length (not including any nul terminator) is the specified count.

### SQLClientProxyLiteral

SQLLiteral* SQLClientProxyLiteral(NSString* aString);
Creates and returns an autoreleased proxy to aString, recording the fact that the programmer considers the string to be a valid literal (ie one that doesn't need to be quoted when used as part of an SQL statement or query). The original string is retained by the object returned.
Use this when aString is large and the overheads of the SQLClientCopyLiteral() or SQLClientMakeLiteral() functions would be too high.
NB. Manipulation of proxy objects is inefficient... you should leave creation of the proxy to the last moment before passing it to a method which would otherwise autoquote your string.

### SQLClientTimeLast

NSTimeInterval SQLClientTimeLast();
Returns the timestamp of the most recent call to SQLClientTimeNow() .

### SQLClientTimeNow

NSTimeInterval SQLClientTimeNow();
Convenience function to provide timing information quickly.
This returns the current date/time, and stores the value for use by the SQLClientTimeLast() function.

### SQLClientTimeStart

NSTimeInterval SQLClientTimeStart();
This returns the timestamp from which any of the SQLClient classes was first used or SQLClientTimeNow() was first called (whichever came first).

### SQLClientTimeTick

unsigned int SQLClientTimeTick();
A convenience method to return the current clock 'tick'... which is the current second based on the time we started. This does not check the current time, but relies on SQLClientTimeLast() returning an up to date value (so if you need an accurate tick, you should ensure that SQLClientTimeNow() is called at least once a second).
The returned value is always greater than zero, and is basically calculated as (SQLClientTimeLast() - SQLClientTimeStart() + 1).
In the event that the system clock is reset into the past, the value of SQLClientTimeStart() is automatically adjusted to ensure that the result of a call to SQLClientTimeTick() is never less than the result of any earlier call to the function.

### SQLClientUnProxyLiteral

NSString* SQLClientUnProxyLiteral(id aString);
Returns the original string which was previously wrapped by a call to SQLClientProxyLiteral() . If aString is not an SQLLiteral proxy, this returns aString.