PostgreSQL Guide

SQLAPI++ allows to seamlessly work with a variety of SQL database servers. It provides unified API to access any database, keeping your code portable. But each server has some specific features which a developer has to know in order to leverage server's unique features and avoid potential errors.

For complete information on using SQLAPI++ check out Getting Started and Documentation. This guide covers specific information related to working with PostgreSQL server using SQLAPI++ library in the following areas:

Connecting to a database

To connect to a database you need to initialize a connection object. A connection object is represented by SAConnection class.

Minimum Version
SQLAPI++ library requires libpq version 7.1.x or higher.

After the connection is created you need to call SAConnection::Connect method to establish connection with PostgreSQL server:

void Connect(
    const SAString &sDBString,
    const SAString &sUserID, 
    const SAString &sPassword, 
    SAClient_t eSAClient = SA_Client_NotSpecified);
Parameters

sDBString

Connection string in the following format:

[<server_name>@][<database_name>][;<options>]
  • "" or "@" - empty string or '@' character, connects to a local server
  • <database_name> or @<database_name> - connects to a database with the specified name on local server
  • <serve_name>@ - connects to the specified server
  • <server_name>@<database_name> - connects to a database with the specified name on the specified server

<server_name> can have the following formats:

  • hostname[,port]
  • pathname of the Unix socket that is used to connect to the server

<options> string used for PQsetdbLogin function pgoptions parameter (these are the server process parameters).

<database_name> string defines the database name for the connection but it can also define the client options like: "dbname=mydb connect_timeout=10".

sUserID

A string containing a user name to use when establishing the connection.

sPassword

A string containing a password to use when establishing the connection.

eSAClient

Optional. One of the following values from SAClient_t enum:
  • SA_PostgreSQL_Client PostgreSQL client
  • SA_Client_NotSpecified – used by default if eSAClient parameter is omitted. You can use this default value only if you have SAConnection::setAPI method with SAPI object initialized with SA_PostgreSQL_Client constant before

For more details see Getting Started - Connect to Database, SAConnection object, SAConnection::Connect.

Transaction isolation levels

SQL-92 defines four isolation levels, all of which are supported by SQLAPI++:

  • Read uncommitted (the lowest level where transactions are isolated just enough to ensure that physically corrupt data is not read)
  • Read committed
  • Repeatable read
  • Serializable (the highest level, where transactions are completely isolated from one another)

SQLAPI++ maps different isolation levels on PostgreSQL in the following way:

SA_ReadUncommittedREAD UNCOMMITTED
SA_ReadCommittedREAD COMMITTED
SA_RepeatableReadREPEATABLE READ
SA_SerializableSERIALIZABLE

In addition to the SQL-92 levels, if you specify 'snapshot' isolation level, it will be mapped as: SA_Snapshot SERIALIZABLE.

For more details see SAConnection::setIsolationLevel.

Working with Long or Lob (CLob, BLob) data

When fetching data SQLAPI++ detects data types of the columns in the result set and maps those types to internal library types. The mapping determines which native APIs the library will use for fetching LOB data.

The table below shows how SQLAPI++ maps PostgreSQL server data types to Long/Lob library types:

BYTEASA_dtLongBinary
TEXTSA_dtLongChar
OIDSA_dtBLob
only if 'OidTypeInterpretation' command option set to 'LargeObject'

When binding input data from your program the reverse mapping is taking place. The SQLAPI++ data type you use for input markers determines what native API program types will be used for sending Long/Lob data to the server.

The table below shows how SQLAPI++ maps its internal library types to PostgreSQL API data types:
SA_dtLongBinaryHEX string of the binary data
SA_dtLongCharescaped string
SA_dtBLobOID
Oid of an object that contains the binary data
SA_dtCLobOID
Oid of an object that contains the text data

Working with PostgreSQL Large Objects data (Oid field type) includes some special considerations.

Generally, when you fetch Oid field data (which can point to any object, not necessary PostgreSQL Large Object) SQLAPI++ returns its value as a number (SQLAPI++ returns an object identifier).

If you want to retrieve Oid field as PostgreSQL Large Object you should set command-related option OidTypeInterpretation to "LargeObject" value before the command execution, by calling SACommand::setOption.

For additional information see Getting Started - Handle Long/CLob/BLob.

Returning output parameters

In PostgreSQL output parameters are available immediately after calling SACommand::Execute.

SQLAPI++ library automatically creates SAParam object to represent function return value. You can refer to this SAParam object using SQLAPI++ predefined name "RETURN_VALUE".

For additional information see SACommand::Execute, SAParam object, Getting Started - Get Output Parameters.

Cancelling queries

Using SACommand::Cancel method you can cancel the following types of processing on a statement:

  • function running asynchronously on the statement
  • function running on the statement on another thread

SQLAPI++ calls PQrequestCancel function to cancel a query. To get more details see PQrequestCancel function description in native PostgreSQL documentation.

For additional information see SACommand::Cancel.

Connection, command, parameter and field options

Server specific options can be applied at the API, connection, command, parameter or field levels.

We recommend you specify each option at the appropriate level, although it is possible to specify them at the parent object level as well. In that case the option affects all the child objects.

API level options must be specified in SAPI object. If an internal SAPI object is used for the DBMS API initialization (implicit DBMS API initialization, see SAConnection::Connect method) the related DBMS specific options are taken from the initial connection object.

Connection level options may be specified in either SAPI object or SAConnection object. If specified in SAPI object an option affects all connections on that API.

Command level options may be specified in SAPI object, SAConnection object or SACommand object. If specified in a parent object an option affects all commands on that SAPI or SAConnection object.

Parameter level options may be specified in SAPI object, SAConnection object, SACommand object or SAParam object. If specified in a parent object an option affects all parameters on that SAPI, SAConnection or SACommand object.

Field related options may be specified in SAPI object, SAConnection object, SACommand object or SAField object. If specified in a parent object an option affects all fields on that SAPI , SAConnection or SACommand object.

Specific options applicable to PostgreSQL:

LIBPQ.LIBS
Api Scope
Forces SQLAPI++ Library to use specified LIBPQ library.
Valid values: Any valid LIBPQ library name list. Names separated by ';' on Windows or ':' on other operating systems.
Default value:
  • Windows - "libpq.dll;pq.dll
  • Linux - "libpq.so:libpq.so.5:libpq.so.4:libpq.so.3"
Special values: "STATIC", forces using the linked PostgreSQL client API functions when the library is compiled with SA_STATIC_PQSQL build option.
APPNAME
Connection Scope
Specifies the client application name (PostgreSQL 9.0 and higher 'application_name' configuration parameter).
Valid values: client application name string
Default value: none
ClientEncoding
Connection Scope
Uses PQsetClientEncoding to set up PostgreSQL client encoding (for non-Unicode SQLAPI++ version only).
Valid values: See PostgreSQL documentation
OidTypeInterpretation
Command Scope
Forces SQLAPI++ Library to interpret fields of Oid type as an object identifier or a Large Object. After you set "LargeObject" value to this option, SQLAPI++ interprets Oid type fields data as BLob data. Otherwise, it reads them as object identifiers (as ordinary numbers).
Valid values: "LargeObject" and "Oid"
Default value: "Oid"
PreFetchRows
Command Scope
Forces SQLAPI++ library to fetch rows in bulk, rather than retrieving records one by one.
Valid values: String containing number of rows in the fetch buffer
Default value: "1"
UseDynamicCursor
Scrollable
Command Scope
Forces SQLAPI++ to use scrollable dynamic server side cursor.
Valid values: "True", "1"
Default value: "False"
UseCursor
Command Scope
Forces SQLAPI++ to use server side cursor within "select .." statement.
Valid values: "True", "1"
Default value: "False"
SetCursorName
Command Scope
Allows to define the cursor name SQLAPI++ uses for the server side cursor within "select .." statement.
Valid values: See PostgreSQL documentation
Default value: none
SNAPSHOT_ID
Command Scope
Allows to define the transaction snapshot that SQLAPI++ uses within the next transaction block.
Valid values: See PostgreSQL documentation
Default value: none
UsePrepared
Command Scope
Forces SQLAPI++ to use prepared statement with the current SACommand.
Valid values: "True", "1"
Default value: "False"

For additional information see SAOptions::setOption.

Using native PostgreSQL API

You can call client specific API functions which are not directly supported by SQLAPI++ library. SAConnection::NativeAPI method returns a pointer to the set of native API functions available for PostgreSQL. To use the database API directly you have to downcast this IsaAPI pointer to the appropriate type and use its implementation-specific members. The following example shows what type cast you have to make and what additional header file you have to include to work with PostgreSQL API. Note that using appropriate type casting depends on an API (that generally mean that you have to explicitly check client version before casting, see SAConnection::ClientVersion method).

To use native API you need to add PostgreSQL specific #include and cast the result of SAConnection::NativeAPI to class pgAPI:

#include "pgAPI.h"

IsaAPI *pApi = con.NativeAPI();
pgAPI *pNativeAPI = (pgAPI *)pApi;

To get more information about PostgreSQL API functions see PostgreSQL documentation.

For additional information see SAConnection::NativeAPI.

Getting native PostgreSQL connection related handles

You have to use native API handles when you want to call specific PostgreSQL API functions which are not directly supported by the library. API functions usually need to receive one or more active handles as parameters. SAConnection::NativeHandles method returns a pointer to the set of native API connection related handles. To use API handles directly you have to downcast saConnectionHandles pointer to the appropriate type and use its implementation-specific members.

To access native connection handles you need to add PostgreSQL specific #include and cast the result to class pgConnectionHandles:

#include "pgAPI.h"

saConnectionHandles *pHandles = con.NativeHandles();
pgConnectionHandles *pNativeHandles = (pgConnectionHandles*)pHandles;

To get more information about PostgreSQL API functions and handles see PostgreSQL specific documentation.

For additional information see SAConnection::NativeHandles.

Getting native PostgreSQL command related handles

You have to use native API handles when you want to call specific PostgreSQL API functions which are not directly supported by the library. API functions usually need to receive one or more active handles as parameters. SACommand::NativeHandles method returns a pointer to the set of native API command related handles. To use API handles directly you have to downcast saCommandHandles pointer to the appropriate type and use its implementation-specific members.

To access native command handles you need to add PostgreSQL specific #include and cast the result to class pgCommandHandles:

#include "pgAPI.h"

saCommandHandles *pHandles = cmd.NativeHandles();
pgCommandHandles *pNativeHandles = (pgCommandHandles*)pHandles;

To get more information about PostgreSQL API functions and handles see PostgreSQL specific documentation.

For additional information see SACommand::NativeHandles.

Error handling

When an error occurs when executing a SQL statement SQLAPI++ library throws an exception of type SAException and SAException::ErrPos method returns error position in the SQL statement.

In PostgreSQL server SAException::ErrPos method returns -1 because PostgreSQL does not support this function.

For additional information see Getting Started - Error Handling, SAException object.