Oracle® TimesTen In-Memory Database TTClasses Guide Release 11.2.1 Part Number E13074-02 |
|
|
View PDF |
This chapter contains descriptions of all classes in the external interface to TTClasses and brief descriptions of some of the internal TTClasses. It is divided into the following sections:
This section includes the following classes:
The TTStatus
class is used by other classes in the TTClasses collection to catch error and warning exceptions. You can think of TTStatus
as a value-added C++ wrapper around the SQLError
ODBC function.
TTStatus
has the following subclasses:
TTError
is a subclass of TTStatus
and is used to encapsulate ODBC errors (return codes: SQL_ERROR, SQL_INVALID_HANDLE).
TTWarning
is a subclass of TTStatus
and is used to encapsulate ODBC warnings (return code: SQL_SUCCESS_WITH_INFO).
ODBC warnings are usually not as serious as ODBC errors and should be handled with different logic. Logging ODBC warnings to an application's log is usually appropriate, but ODBC errors usually need to be programmatically handled.
Member | Description |
---|---|
rc |
Return code from the failing ODBC call. Typical values for this field are SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_ERROR, SQL_NO_DATA_FOUND, and SQL_INVALID_HANDLE. |
native_error |
TimesTen native error number (if any) for the failing ODBC call. |
odbc_error |
ODBC error code for the failing ODBC call. |
err_msg |
ASCII printable error message for the failing ODBC call. |
Method | Description |
---|---|
ostream() | Prints errors to a stream. |
friend ostream& operator<<(ostream&, TTStatus&)
This method can be used to print the error to a stream.
You must build the library with the TTEXCEPT preprocessor variable defined. TTStatus
objects are thrown as exceptions whenever an error occurs. This allows C++ applications to use {try/catch}
to detect and recover from failure.
Example 4-1 shows the use of TTStatus
with TTEXCEPT defined.
Example 4-1 Using TTStatus with TTEXCEPT defined
try { cmd1.Prepare(&conn, "select * from foo", stat); cmd2.Prepare(&conn, "insert into foo values(?,?,?)", stat); cmd3.Prepare(&conn, "update foo set x = ? where y=?", stat); conn.Commit(stat); } catch (TTStatus st) { cerr << "Error preparing statements: " << st << endl; // Rollback, exit(), throw -- whatever is appropriate }
Example 4-2 Error reporting with TTError and TTWarning versus TTStatus
TTError
objects are thrown for ODBC errors, and TTWarning
objects are thrown for ODBC warnings. This example shows TTError
and TTWarning
for error handling.
// catching TTError & TTWarning exceptions try { // some TTClasses method calls } catch (TTWarning warn) { cerr << "Warning encountered: " << warn << endl; } catch (TTError err) { cerr << "Error encountered: " << err << endl; }
The TTConnection
class encapsulates the concept of a connection to a TimesTen database. You can think of TTConnection
as a value-added C++ wrapper around the ODBC HDBC handle.
All applications that use TimesTen must create at least one TTConnection
object.
Multithreaded applications that wish to use TimesTen from multiple threads simultaneously must create more than one TTConnection
object. Use one of the following strategies:
Create one TTConnection
object for each thread when the thread is created.
Create a pool of TTConnection
objects when the application process starts. They are shared by the threads in the process. See the "TTConnectionPool" for additional information about this option.
A TimesTen connection cannot be inherited from a parent process. If a process opens a database connection before creating a child process, the child cannot use the same connection.
It is not desirable for an application to be constantly connecting to and disconnecting from TimesTen because it degrades performance. Instead, establish database connections at the beginning of the application process and reuse them for the life of the process.
Method | Description |
---|---|
Connect() | Opens a new connection to a TimesTen data store. |
Disconnect() | Closes a connection to a TimesTen data store. |
Rollback() | Rolls back changes made to the database through this connection since the last call to Commit() or Rollback() methods. |
isConnected() | Returns TRUE if the object is connected to TimesTen. |
getHdbc() | Returns the ODBC level "HDBC" associated with this connection. |
SetIsoReadCommitted() | Sets the transaction isolation level of the connection to be TXN_READ_COMMITTED. |
SetIsoSerializable() | Sets the transaction isolation level of the connection to be TXN_SERIALIZABLE. |
CheckpointBlocking() | Performs a blocking checkpoint operation on the data store by calling the ttCkptBlocking TimesTen built-in procedure. |
CheckpointNonBlocking() | Performs a "true fuzzy" checkpoint operation on the data store by calling the ttCkpt TimesTen built-in procedure. |
DurableCommit() | Performs a durable commit operation on the data store. |
SetLockWait() | Sets the lock timeout interval for the connection by calling the ttLockWait TimesTen built-in procedure. |
SetPrefetchCloseOn() | Turns on the TT_PREFETCH_CLOSE connection option. This is useful for optimizing SELECT query performance for client/server connections to TimesTen. |
SetPrefetchCloseOff() | Turns off the TT_PREFETCH_CLOSE connection option. |
SetPrefetchCount() | Allows a user application to tune the number of rows that the TimesTen ODBC driver SQLFetch call will prefetch for a SELECT statement. |
SetAutocommitOff() | Sets AUTOCOMMIT off for the connection. |
SetAutoCommitOn() | Sets AUTOCOMMIT on for the connection. |
GetTTContext() | Returns the connection's context value. |
void Connect(const char* connStr, TTStatus&)
Opens a new connection to a TimesTen data store. The connection string specified in the connStr
parameter is used to create the connection.
Example 4-3 Using the Connect() method and checking for errors
A TTStatus
object is thrown as an exception if an error occurs. When calling this method, any warnings returned can often be safely ignored. The following logic is preferred when using the Connect()
method.
Note that TTWarning
and TTError
are subclasses of TTStatus
.
TTConnection conn; TTStatus stat; ... try { conn.Connect("DSN=mydsn", stat); } catch (TTWarning warn) { // warnings from Connect() are usually informational cerr << ''Warning while connecting to TimesTen: '' << warn << endl; } catch (TTError err) { // handle the error; this could be a serious problem }
void Disconnect(TTStatus&)
Closes a connection to a TimesTen data store. A TTStatus
object is thrown as an exception if an error occurs.
void Commit(TTStatus&)
Commits a transaction to the TimesTen database. All other operations performed on this connection since the last call to the Commit()
or Rollback()
methods will be committed. A TTStatus
object is thrown as an exception if an error occurs.
void Rollback(TTStatus&)
Abandons a transaction. Any changes made to the database through this connection since the last call to Commit()
or Rollback()
methods will be undone. A TTStatus
object is thrown as an exception if an error occurs.
bool isConnected()
Returns TRUE if the object is connected to TimesTen (using the Connect()
method) or FALSE if not.
void SetIsoReadCommitted(TTStatus &)
Sets the transaction isolation level of the connection to be TXN_READ_COMMITTED. Read-committed isolation offers the best combination of single-transaction performance and good multiconnection concurrency.
void SetIsoSerializable(TTStatus &)
Sets the transaction isolation level of the connection to be TXN_SERIALIZABLE. In general, serializable isolation offers fair individual transaction performance but extremely poor concurrency. READ_COMMITTED isolation level (see "SetIsoReadCommitted()") should be preferred over SERIALIZABLE isolation level in almost all situations.
void CheckpointBlocking(int timeout, int retries, TTStatus &)
Performs a blocking checkpoint operation on the data store by calling the ttCkptBlocking
TimesTen built-in procedure with the timeout
and retries
parameters.
See the Oracle TimesTen In-Memory Database Reference for more information about ttCkptBlocking
.
void CheckpointNonBlocking(TTStatus &)
Note:
This is the preferred type of checkpoint.Performs a "true fuzzy" checkpoint operation on the data store by calling the ttCkpt
TimesTen built-in procedure.
See the Oracle TimesTen In-Memory Database Reference for more information about ttCkpt
.
void DurableCommit(TTStatus &)
Performs a durable commit operation on the data store. A durable commit operation flushes the in-memory transaction log buffer to disk. It calls the ttDurableCommit
TimesTen built-in procedure.
See the Oracle TimesTen In-Memory Database Reference for more information about ttDurableCommit
.
void SetLockWait(int secs, TTStatus &)
Sets the lock timeout interval for the connection by calling the ttLockWait
TimesTen built-in procedure with the secs
parameter. In general, a 2 or 3 second lock timeout is sufficient for most applications. The default lock timeout interval is 10 seconds.
See the Oracle TimesTen In-Memory Database Reference for more information about ttLockWait
.
void SetPrefetchCloseOn(TTStatus &)
Turns on the TT_PREFETCH_CLOSE connection option, which is useful for optimizing SELECT query performance for client/server connections to TimesTen. Note that this method provides no benefit for directly connected TimesTen applications (for example, non-client/server programs).
See "Bulk fetch rows of TimesTen data" in the Oracle TimesTen In-Memory Database C Developer's Guide for more information about TT_PREFETCH_CLOSE.
void SetPrefetchCloseOff(TTStatus &)
Turns off the TT_PREFETCH_CLOSE connection option.
void SetPrefetchCount(int numrows, TTStatus &)
Allows a user application to tune the number of rows that the TimesTen ODBC driver internally fetches at a time for a SELECT statement. The value of numrows
must be between 1 and 128, inclusive.
Note:
This method is not equivalent to executingTTCmd::FetchNext()
multiple times. Instead, proper use of this parameter reduces the amount of time for each call to TTCmd::FetchNext()
.See "Bulk fetch rows of TimesTen data" in the Oracle TimesTen In-Memory Database C Developer's Guide for more information about TT_PREFETCH_COUNT.
void SetAutoCommitOff(TTStatus &)
Sets AUTOCOMMIT off for the connection.
Note that this method is automatically called by TTConnection::Connect()
because TimesTen runs with optimal performance only with AUTOCOMMIT turned off.
void SetAutoCommitOn(TTStatus &)
Sets AUTOCOMMIT on for the connection, which means that every SQL statement now occurs in its own transaction.
Note that TimesTen generally runs much faster with AUTOCOMMIT turned off.
When AUTOCOMMIT is off, committing SELECT statements requires explicit calls to TTCmd::Close()
.
void GetTTContext(char * output, TTStatus &)
Returns the connection's context value, which is unique to each connection to a TimesTen data store. The context of a connection can be used to correlate TimesTen connections with PIDs using the ttStatus
TimesTen utility, for example.
The context value is returned through the output
parameter. This method must be called with an array of CHAR[17] or larger for the output
parameter.
This method calls the ttContext
TimesTen built-in procedure. See the Oracle TimesTen In-Memory Database C Developer's Guide for more information about ttContext
.
Encapsulates a single SQL statement that will be used multiple times in an application program. You can think of TTCmd
as a value-added C++ wrapper around the ODBC HSTMT handle.
Method | Description |
---|---|
Prepare() | Associates a SQL statement with TTCmd . |
RePrepare() | Allows a statement to be reprepared. |
Execute() | Invokes a SQL statement that has been prepared for execution. |
ExecuteImmediate() | Invoke a SQL statement that has not been previously prepared. |
FetchNext() | Fetches rows from the answer set, one at a time. It returns 0 when a row was successfully fetched, and 1 when no more rows are available. |
Close() | Closes the answer set when the application has finished fetching rows. |
Drop() | Frees a prepared SQL statement and all resources associated with it. |
setQueryTimeout() | Sets a timeout value for a query. |
setQueryThreshold() | Sets a threshold for writing a warning to the support log and throwing an SNMP trap when the execution time of a SQL statement exceeds the specified value. |
setMaxRows() | Sets a limit on the number of rows returned by a SELECT statement. |
getMaxRows() | Returns the current limit on the number of rows returned by a SELECT statement. |
getRowCount() | Returns the number of rows that were affected by the recently executed SQL operation. |
setParam() | Sets the value of parameters before executing a prepared SQL statement. |
setParamNull() | Sets the value of a parameter to NULL before executing a prepared SQL statement. |
getParamPrecision() | Returns the precision of the specified parameter in a prepared statement. |
getParamScale() | Returns the scale of the specified parameter in a prepared statement. |
getParamNull() | Indicates whether the specified parameter can be NULL. |
getColumn() | Returns the values associated with a particular column. |
isColumnNull() | Indicates whether the specified column's value is NULL. |
getColumnLength() | Returns the length of the specified column, in bytes. |
getColumnNullable() | Returns the values for columns of the current row of the answer set and indicates whether a column's value is NULL. |
getNextColumn() | Returns the values for columns of the next row of the answer set. |
getNextColumnNullable() | Returns the values for columns of the next row of the answer set and indicates whether a column's value is NULL. |
getQueryThreshold() | Retrieves the query threshold value. |
printColumn() | Prints a specified column to an output stream. |
Method | Description |
---|---|
getNParameters() | Returns the number of input parameters. |
getNColumns() | Returns the number of output columns. |
getParamType() | Returns the ODBC data type of the specified parameter. |
getColumnName() | Returns the name of the specified column. |
getColumnType() | Returns the ODBC data type of the specified column. |
getColumnPrecision() | Returns the precision of the specified column. |
getColumnScale() | Returns the scale of the specified column. |
Method | Description |
---|---|
PrepareBatch() | Prepares batch INSERT, UPDATE, and DELETE statements. |
BindParameter() | Binds an array of values for a statement compiled using PrepareBatch() . |
setParamLength() | Sets the length, in bytes, of one of the bound parameter values before execution of the prepared statement. |
setParamNull() | Sets one of the bound parameters to NULL before execution of the prepared statement. |
ExecuteBatch() | Invokes a SQL statement that has been prepared for execution by PrepareBatch() . It returns the number of rows in the batch that were updated. |
void Prepare(TTConnection*, const char* sqlP, TTStatus&)
This method associates a SQL statement with TTCmd
. It takes three parameters:
A pointer to a TTConnection
object, which should be already connected to the database by a call to TTConnection::Connect()
A const char *
parameter, which is the SQL string being prepared
A TTStatus
object
Before TTCmd
can be used, a SQL statement (such as SELECT, INSERT, UPDATE or DELETE) must be associated with it. The association is accomplished by using the Prepare()
method, which also compiles and optimizes the SQL statement to ensure that it will be executed in an efficient manner. The Prepare()
method does not execute the statement.
With TimesTen, statements are typically parameterized for better performance. Consider the following SQL statements:
SELECT col1 FROM table1 WHERE C = 10 SELECT col1 FROM table1 WHERE C = 11
It is more efficient to prepare a single parameterized statement and execute it multiple times:
SELECT col1 FROM table1 WHERE C = ?
The value for "?" is specified at runtime by using the TTCmd::setParam()
method.
There is no need to explicitly bind columns or parameters to a SQL statement, as is necessary when you use ODBC directly. TTCmd
automatically defines and binds all necessary columns and parameters at prepare time.
Note that prepare is a relatively expensive operation. When an application establishes a connection to TimesTen, using TTConnection::Connect()
, the application should prepare all TTCmd
objects associated with the connection. A TTStatus
object is thrown as an exception if an error occurs.
void RePrepare(TTConnection *cP, TTStatus & stat)
This method allows a statement to be reprepared. It is useful only when a statement handle in a prepared statement has been invalidated.
void Execute(TTStatus&)
This method invokes a SQL statement that has been prepared for execution.
Use Execute
to invoke a SQL statement previously prepared with the Prepare()
method, after any necessary parameter values are defined using setParam()
methods.
If the SQL statement is a SELECT statement, this method executes the query but does not return any rows from the result set. Use the FetchNext()
method to fetch rows from the result set one at a time. Use the Close()
method to close the result set when all appropriate rows have been fetched. For SQL statements other than SELECT, no cursor is opened, and the Close()
method does not need to be called. A TTStatus
object is thrown as an exception if an error occurs.
int ExecuteImmediate(TTConnection*, const char * sqlP, TTStatus& stat)
This method invokes a SQL statement that has not been previously prepared.
ExecuteImmediate()
is a convenient alternative to using Prepare()
and Execute()
when a SQL statement is only executed a few times. Use ExecuteImmediate()
for DDL statements such as CREATE TABLE and DROP TABLE and infrequently used DML statements that do not return a result set (for example, DELETE FROM table_name
).
ExecuteImmediate()
is incompatible with SQL statements that return a result set. In addition, statements executed through ExecuteImmediate()
cannot subsequently be queried by getRowCount()
to get the number of rows affected by a DML operation. Because of this, ExecuteImmediate()
calls getRowCount()
automatically, and its value is the integer return value of this method.
int FetchNext(TTStatus& stat)
After executing a prepared SQL SELECT statement using the Execute()
method, use the FetchNext()
method to fetch rows from the answer set, one at a time.
After fetching a row of the answer set, use one of the overloaded versions of the getColumn()
method to fetch values from the current row.
If no more rows remain in the answer set, FetchNext()
returns 1. If a row is returned, FetchNext()
returns 0.
After executing a SELECT using the Execute()
method, the answer set must be closed using the Close()
method after all desired rows have been fetched. Note that after the Close()
method is called, the FetchNext()
method cannot be used to fetch additional rows from the answer set. A TTStatus
object is thrown as an exception if an error occurs.
void Close(TTStatus&)
If a SQL SELECT statement is executed using the Execute()
method, a cursor is opened which may be used to fetch rows from the answer set. When the application is finished fetching rows from the answer set, it must be closed with the Close()
method.
Failure to close the answer set may result in locks being held on rows for too long, causing concurrency problems as well as memory leaks and other errors. A TTStatus
object is thrown as an exception if an error occurs.
void Drop(TTStatus&)
If a prepared SQL statement will not be used in the future, the statement and resources associated with it can be freed by calling the Drop()
method. The TTCmd
object may be reused for another statement by calling Prepare()
again.
It is more efficient to use multiple TTCmd
objects to execute multiple SQL statements. Use the Drop()
method only if it is certain that a particular SQL statement will not be used again. A TTStatus
object is thrown as an exception if an error occurs.
void setQueryTimeout(const int nSecs, TTStatus&)
This method allows applications to stop long running queries as needed by setting a timeout value on the query. The nSecs
value specifies the timeout in seconds.
Note that there is no default query timeout value.
void TTCmd::setQueryThreshold(const int seconds, TTStatus &stat)
This method sets a threshold for writing a warning to the support log and throwing an SNMP trap when the execution time of a SQL statement exceeds the specified value.
void setMaxRows(const int nRows, TTStatus &stat)
This method sets a limit on the number of rows returned by a SELECT statement. If the number of rows in the result set exceeds the set limit, fetching beyond the max number of rows set will cause the statement to return SQL_NO_DATA_FOUND. The TTCmd
object will TRUE if the eof()
method is called. The default is to return all rows. To reset a limit to again return all rows, call setMaxRows()
with nRows
set to 0. The limit is only meaningful for SELECT statements.
int getMaxRows(TTStatus &stat)
This method returns the current limit of number of rows returned by a SELECT statement from this TTCmd
object. A return value of 0 means all rows are returned.
int getRowCount()
This method can be called immediately after Execute()
to return the number of rows that were affected by the recently executed SQL operation. For example, after execution of a DELETE statement that deletes 10 rows, getRowCount()
returns 10.
void setParam(int pno, ...)
All overloaded setParam()
versions are described in this section.
The various setParam()
versions are used to set the value of parameters before executing a prepared SQL statement. SQL statements are prepared before use with the Prepare method and are executed with the Execute()
method. If the SQL statement contains any parameter markers (the "?" character used where a literal constant would be legal), values must be assigned to these parameters before the SQL statement can be executed. The setParam()
method is used to define a value for each parameter before executing the statement. See "Dynamic parameters" in the Oracle TimesTen In-Memory Database SQL Reference.
The first argument passed to setParam()
is the position of the parameter to be set. The first (left-most) parameter in a SQL statement is parameter 1. The second argument passed to setParam()
is the value of the parameter. Overloaded versions of setParam()
take different data types for the second argument.
The TTClasses library does not support a large set of data type conversions. The appropriate overloaded version of setParam()
must be called for each parameter in the prepared SQL. Calling the wrong version (attempting to set an integer parameter to a char*
value, for example) may result in program failure.
Values passed to setParam()
are copied into internal buffers maintained by the TTCmd
object. These buffers are statically allocated and bound by the Prepare()
method. The parameter value is the value passed into setParam()
at the time of the setParam()
call, not the value at the time of a subsequent Execute()
method call.
Table 4-1 shows the supported SQL data types and the appropriate versions of setParam()
to use for each parameter type. Note that SQL data types not mentioned are not supported in this version of TTClasses.
Note:
In this table, the lengthlen
is in bytes.Table 4-1 TTCmd::setParam() variants for supported data types
Data type | setParam variants supported |
---|---|
TT_TINYINT |
|
TT_SMALLINT |
|
TT_INTEGER |
|
TT_BIGINT |
|
BINARY_FLOAT |
|
BINARY_DOUBLE |
|
NUMBER TT_DECIMAL |
Note: The integer type methods are appropriate only for columns declared with the scale parameter set to zero, such as NUMBER(8) or NUMBER(8,0). |
TT_CHAR CHAR TT_VARCHAR VARCHAR2 |
|
TT_NCHAR NCHAR NVARCHAR2 |
|
BINARY VARBINARY |
|
DATE TT_TIMESTAMP TIMESTAMP |
|
TT_DATE |
|
TT_TIME |
|
void setParamNull(int pno)
This method can be used to indicate that the value for parameter number pno
should be the SQL NULL value.
See "setParam()".
int getParamPrecision(int pno)
This method returns the precision of parameter number pno
.
bool getParamNull(int pno);
This method indicates whether parameter number pno
can be NULL.
void getColumn (int cno, ...)
The getColumn()
method, as well as the getColumnNullable()
method (described shortly), can be used to fetch the values for columns of the current row of the answer set. Before the getColumn()
and getColumnNullable()
methods can be used, the FetchNext()
method must be used to fetch the first (or next) row from the answer set of a SELECT statement. SQL statements are executed using the Execute()
method.
The getColumn()
method returns the value associated with a particular column. Columns are referred to by ordinal number, with "1" indicating the first column specified in the SELECT statement. In all cases the first argument passed to the getColumn()
method is the ordinal number of the column whose value is to be fetched. The second argument passed to the getColumn()
method is a pointer to a variable which is to receive the value of the specified column. The type of this argument varies depending on the type of the column being returned.
This version of the TTClasses library does not support a large set of data type conversions. The appropriate overloaded version of getColumn()
must be called for each output column in the prepared SQL. Calling the wrong version (attempting to fetch an integer column into a char*
value, for example) may result in program failure.
Integer type methods include one of the following functions: SQLTINYINT, SQLSMALLINT, SQLINTEGER, or SQLBIGINT. They are appropriate only for columns with the scale parameter set to zero, such as NUMBER(p) or NUMBER(p,0). The functions have the following range of precision:
Function | Precision Range |
---|---|
SQLTINYINT | 0<=p <=2 |
SQLSMALLINT | 0<=p <=4 |
SQLINTEGER | 0<=p <=9 |
SQLBIGINT | 0<=p <=18 |
To ensure that all values in the column will fit into the variable that the application uses to retrieve information from the database, you can use SQLBIGINT for all table columns of data type NUMBER(p), where 0 <= p
<= 18. For example:
getColumn(int cno, SQLBIGINT*)
Table 4-2 shows the supported SQL data types and the appropriate versions of getColumn() and getColumnNullable() to use for each parameter type.
Note:
In this table, lengthlenP
is in bytes.Table 4-2 TTCmd::getColumn()/getColumnNullable() variants for supported data types
Data type | getColumn variants supported |
---|---|
TT_TINYINT |
|
TT_SMALLINT |
|
TT_INTEGER |
|
TT_BIGINT |
|
BINARY_FLOAT |
|
BINARY_DOUBLE |
|
NUMBER TT_DECIMAL |
Note: The integer type methods are appropriate only for columns declared with the scale parameter set to zero. |
TT_CHAR CHAR TT_VARCHAR VARCHAR2 |
|
TT_NCHAR NCHAR TT_NVARCHAR NVARCHAR2 |
|
BINARY VARBINARY |
|
DATE TT_TIMESTAMP TIMESTAMP |
|
TT_DATE |
|
TT_TIME |
|
Other SQL data types are not supported in this release of the TTClasses library.
bool isColumnNull(int cno)
This method provides another way to determine whether the value of column number cno
is NULL.
See information about the getColumnNullable()
method, following shortly.
int getColumnLength(int cno)
This method returns the length, in bytes, of column number cno
, not counting the NULL terminator; or, it returns SQL_NULL_DATA if the value is NULL. This method is generally useful only when accessing columns of type VARBINARY or NVARCHAR2. The value returned is between 0 and the column precision, inclusive. See "getColumnPrecision()".
bool getColumnNullable(int cno, ...)
The getColumnNullable()
method is similar to the getColumn()
method, described previously. However, in addition to the behavior of getColumn()
, the getColumnNullable()
method also returns an indication of whether the value is the SQL NULL pseudo-value. If the value is NULL, the second parameter is set to a distinctive value (for example, -9999), and the return value from the method is TRUE. If the value is not NULL, it is returned in the variable pointed to by the second parameter and the getColumnNullable()
method returns FALSE.
See "getColumn()".
void getNextColumn(int iP, ...)
The getNextColumn()
method, as well as the getNextColumnNullable()
method (described shortly), can be used to fetch the values for columns of the next row of the result set. Before the getNextColumn()
and getNextColumnNullable()
methods can be used, the FetchNext()
method must be used to fetch the first row from the result set of a SELECT statement. The iP
parameter represents a pointer to an internal column number. When you use getNextColumn()
, the columns are fetched in order. You cannot change the fetch order.
See Table 4-3 for the supported SQL data types and the appropriate versions of getColumn()
(described previously) to use for each parameter type. This information can be used for getNextColumn()
.
bool getColumnNullable(int iP, ...)
The getNextColumnNullable()
method is similar to the getNextColumn()
method (described previously). However, in addition to the behavior of getColumn()
, the getNextColumnNullable()
method returns an indication of whether the value is the SQL NULL pseudo-value. If the value is NULL, the second parameter is set to a distinctive value (for example, -9999), and the return value from the method is TRUE. If the value is not NULL, it is returned in the variable pointed to by the second parameter and the getColumnNullable()
method returns FALSE.
The iP
parameter represents a pointer to an internal column number. When you use getNextColumn()
, the columns are fetched in order. You cannot change the fetch order.
See Table 4-3 for the supported SQL data types and the appropriate versions of getColumn() to use for each parameter type. This information can be used for getNextColumnNullable()
.
int TTCmd::getQueryThreshold(TTStatus &stat)
Retrieves the query threshold value. See "setQueryThreshold()".
Each SQL statement executed multiple times in a program should have its own TTCmd
object. During program initialization each of these TTCmd
objects should be prepared once and then executed with the Execute()
method multiple times as the program runs.
Only database operations that need to be executed only once should use the ExecuteImmediate()
method. Note that ExecuteImmediate()
is not compatible with any type of SELECT statement. All queries must use Prepare()
plus Execute()
instead. ExecuteImmediate()
is also incompatible with INSERT, UPDATE, or DELETE statements that are subsequently polled using getRowcount()
to see how many rows were inserted, updated or deleted. These limitations have been placed on ExecuteImmediate()
to discourage its use except in a few particular situations (for example, for creating or dropping a table).
There are several useful methods for asking questions about properties of the bound input parameters and output columns of a prepared TTCmd
object. These methods generally provide meaningful results only when a statement has previously been prepared.
int getParamType(int pno)
This method returns the data type of parameter number pno
. The value returned is the ODBC type (for example, SQL_INTEGER, SQL_REAL, SQL_BINARY, SQL_CHAR) as found in sql.h
. Additional TimesTen types (SQL_WCHAR, SQL_WVARCHAR) can be found in the TimesTen header file timesten.h
.
const char * getColumnName(int cno)
This method returns the name of column number cno
.
int getColumnType(int cno)
This method returns the data type of column number cno
. The value returned is the parameter's ODBC type (for example, SQL_INTEGER, SQL_REAL, SQL_BINARY, SQL_CHAR) as found in sql.h
. Additional TimesTen types (SQL_WCHAR, SQL_WVARCHAR) can be found in the TimesTen header file timesten.h
.
int getColumnPrecision(int cno)
This method returns the precision of column number cno
. This value is generally interesting only when generating output from table columns of type CHAR, VARCHAR2, BINARY, VARBINARY, NCHAR and NVARCHAR2.
TimesTen supports the ODBC function SQLBindParams
for batch insert, update and delete operations. TTClasses provides an interface to SQLBindParams
.
Performing batch operations with TTClasses is similar to performing non-batch operations. SQL statements are first compiled using PrepareBatch()
. Then each parameter in that statement is bound to an array of values using BindParameter()
. Finally, the statement is executed using ExecuteBatch()
. Note the similarity to normal TTClasses (non-batch) operations, where a statement is compiled using Prepare
, which also performs the binding of all parameters automatically, and then executed using Execute()
.
See the TTClasses bulktest
sample program for an example of using a batch operation.
This section describes the TTCmd
methods that expose the batch INSERT/UPDATE/DELETE functionality to TTClasses users.
void PrepareBatch(TTConnection*, const char * sqlP, TTCmd::TTCMD_USER_BIND_LEVEL level, unsigned short batchSize, TTStatus&)
PrepareBatch()
is the analog of the Prepare()
method for batch INSERT, UPDATE, or DELETE statements. The TTConnection*
and sqlP
and TTStatus&
parameters are used the in the same as for the Prepare()
method.
There is only one valid value for the level
parameter, as follows:
TTCmd::TTCMD_USER_BIND_PARAMS
The batchSize
parameter specifies the maximum number of insert/update/delete operations that will be performed using subsequent calls to ExecuteBatch()
.
void BindParameter(int pno, unsigned short batchSize, TYPE*, [SQLLEN*], TTStatus&)
The overloaded BindParameter()
method is used to bind an array of values (one for each parameter) for a statement compiled using PrepareBatch()
. The batchSize
value of this call must match the batchSize
value specified in PrepareBatch()
. Similarly, the bound arrays should contain at least as many values as the bound arrays in PrepareBatch()
. You must determine the correct data type for each parameter. Note that if an inappropriate type is specified, a runtime error will be written to the TTClasses global logging facility at the TTLog::TTLOG_ERR
logging level.
Before each invocation of ExecuteBatch()
, the application should fill these arrays with valid parameter values.
For the SQL types SQL_BINARY, SQL_VARBINARY, SQL_WCHAR, and SQL_WVARCHAR), an additional SQLLEN* parameter, for an array of parameter lengths, in bytes, is required. This additional array must be at least batchSize
in length and filled with valid length values before ExecuteBatch()
is called.
Table 4-3 shows the supported SQL data types and the appropriate versions of BindParameter()
to use for each parameter type.
Table 4-3 TTCmd::BindParameter() variants for supported data types
SQL data type | BindParameter variants supported |
---|---|
TT_TINYINT |
|
TT_SMALLINT |
|
TT_INTEGER |
|
TT_BIGINT |
|
BINARY_FLOAT |
|
BINARY_DOUBLE |
|
NUMBER TT_DECIMAL |
|
TT_CHAR CHAR TT_VARCHAR VARCHAR2 |
|
TT_NCHAR NCHAR TT_NVARCHAR NVARCHAR2 |
|
BINARY VARBINARY |
|
DATE TT_TIMESTAMP TIMESTAMP |
|
TT_DATE |
|
TT_TIME |
|
setParamLength(int pno, unsigned short rowno, int len)
This method sets the length of one of the bound parameter values before a call to ExecuteBatch()
. The pno
parameter specifies which parameter in the statement will be set. The rowno
parameter specifies for which row the length will be set. The len
parameter specifies the length being set, in bytes, not counting the NULL terminator; or, it can be set to SQL_NTS for a null-terminated string. (It could also be set to SQL_NULL_DATA, but TimesTen provides the setParamNull()
method for this case.)
For types apart from SQL_BINARY, SQL_VARBINARY, SQL_WCHAR, and SQL_WVARCHAR, this is the only method available to explicitly set the length of a parameter before an ExecuteBatch()
call. For these types, the length can also be explicitly set through manipulation of the SQLLEN*
array, which is the fourth parameter of the BindParameter()
call.
setParamNull(int pno, unsigned short rowno)
This method sets one of the bound parameter values to NULL before a call to ExecuteBatch()
. The first parameter, pno
, specifies which parameter in the statement will be set. The second parameter, rowno
, specifies for which row the length will be set.
For types apart from SQL_BINARY, SQL_VARBINARY, SQL_WCHAR, and SQL_WVARCHAR, this is the only method available to explicitly set the NULL value of a parameter before an ExecuteBatch()
call. For these types, nullability can also be explicitly set through manipulation of the SQLLEN*
array, which is the fourth parameter to the BindParameter()
call.
void ExecuteBatch(unsigned short numRows, TTStatus&)
This method returns the number of rows in a batch that have been updated. The number represents *pirow
from the ODBC SQLSetParams
call.
After preparing a SQL statement with PrepareBatch()
and calling BindParameter()
for each parameter ("?") in the SQL statement, use ExecuteBatch()
to execute the statement numRows
times. The value of numRows
must be no more than the batchSize
specified in the PrepareBatch()
and BindParameter()
calls. The numRows
parameter can be less than the batchSize
value, as required by the application logic.
Before calling ExecuteBatch()
, the application should fill the arrays of parameters bound using BindParameter()
with valid values. Null values can be specified as necessary using by using setParamNull()
.
Example 4-4 also shows how to use the ExecuteBatch()
method. (The bulktest
demo also shows usage of this method.)
Example 4-4 Using the ExecuteBatch() method
Create a table with two columns:
CREATE TABLE batch_table (a TT_INTEGER, b VARCHAR2(100));
Populate the rows of the table in batches of 50:
#define BATCH_SIZE 50 #define VARCHAR_SIZE 100 int int_array[BATCH_SIZE]; char char_array[BATCH_SIZE][VARCHAR_SIZE]; // Prepare the statement TTCmd insert; TTConnection connection; TTStatus stat; // (assume a connection has already been established) try { insert.PrepareBatch (&connection, (const char*)"insert into batch_table values (?,?)", TTCmd::TTCMD_USER_BIND_PARAMS, BATCH_SIZE stat); // Commit the prepared statement connection.Commit(stat); // Bind the arrays of parameters insert.BindParameter(1, BATCH_SIZE, int_array, stat); insert.BindParameter(2, BATCH_SIZE, char_array, stat); // Execute 5 batches, inserting 5 * BATCH_SIZE rows into // the database for (int iter = 0; iter < 5; iter++) { // Populate the value arrays with values. // (A better way of putting meaningful data into // the database is to read values from a file, // rather than generating them arbitrarily.) for (int i = 0; i < BATCH_SIZE; i++) { int_array[i] = i * iter + i; sprintf(char_array[i], "varchar value # %d", i*iter+ i); } // Execute the batch insert statement, // which inserts the entire contents of the // integer and char arrays in one operation. int num_ins = insert.ExecuteBatch(BATCH_SIZE, stat); cerr << "Inserted " << num_ins << " rows." << endl; connection.Commit(stat); } // for iter
The number of rows (num_ins
in the example) can be less than BATCH_SIZE
if, for example, there is a uniqueness constraint on one of the columns. You can use code similar to that in Example 4-5 to check for this situation and roll back the transaction as necessary.
Example 4-5 Using ExecuteBatch() and checking against BATCH_SIZE
for (int iter = 0; iter < 5; iter++) { // Populate the value arrays with values. // (A better way of putting meaningful data into // the database is to read values from a file, // rather than generating them arbitrarily.) for (int i = 0; i < BATCH_SIZE; i++) { int_array[i] = i * iter + i; sprintf(char_array[i], "varchar value # %d", i*iter+i); } // now we execute the batch insert statement, // which does the work of inserting the entire // contents of the integer and char arrays in // one operation int num_ins = insert.ExecuteBatch(BATCH_SIZE, stat); cerr << "Inserted " << num_ins << " rows (expected " << << BATCH_SIZE << " rows)." << endl; if (num_ins == BATCH_SIZE) { cerr << "Committing batch" << endl; connection.Commit(stat); } else { cerr << "Some rows were not inserted as expected, rolling back " << "transaction." << endl; connection.Rollback(stat); break; // jump out of batch insert loop } } // for iter
The integer output of TTCmd::ExecuteBatch()
is *pirow
, equivalent to the third parameter of an ODBC SQLParamOptions
call. See the ODBC Programmer's Manual for information about SQLParamOptions
.
The TTConnectionPool
class is used by multithreaded applications to manage a pool of connections.
In general, multithreaded applications can be written using one of two basic strategies:
If there is a relatively small number of threads and the threads are long-lived, each thread can be assigned to a different connection, which is used for the duration of the application. In this scenario, the TTConnectionPool
class is not necessary.
If there is a large number of threads in the process, or if the threads are short-lived, a pool of idle connections can be established which are used for the duration of the application. When a thread needs to perform a database transaction, it checks out an idle connection from the pool, performs its transaction, and then returns the connection to the pool. This is the scenario that the TTConnectionPool
class assists with.
Note:
For best overall performance, TimesTen recommends having one or two concurrent direct-memory database connections for each CPU of the database server. For no reason should your number of concurrent direct-memory database connections (the size of your connection pool) be more than twice as many CPUs on the database server. In client/server mode, however, TimesTen supports many more connections per CPU efficiently.To use the TTConnectionPool
class, an application creates a single instance of the class. It then creates a number of TTConnection
objects, but does not call their Connect()
methods, which would actually connect them to TimesTen. The application uses the TTConnectionPool::AddConnectionToPool()
method to place the connection objects into the pool. Then, the application calls TTConnectionPool::ConnectAll()
to connect all the connections to TimesTen. Threads wanting to use TimesTen use the getConnection()
method and freeConnection()
methods to get and return idle connections.
Method | Description |
---|---|
AddConnectionToPool() | Adds a TTConnection object, or an object of a class derived from TTConnection , to the connection pool. |
ConnectAll() | Connects all of the TTConnection objects to TimesTen simultaneously |
getConnection() | Checks out an idle connection from the connection pool for a thread. |
freeConnection() | Returns a connection to the pool for reassignment to another thread. |
DisconnectAll() | Disconnects all connections in the connection pool from TimesTen. |
getStats() | Queries the TTConnectionPool for status information. |
int AddConnectionToPool(TTConnection*)
This method is used to add a TTConnection
object, or an object of a class derived from TTConnection
, to the connection pool.
void ConnectAll(const char* connStr, TTStatus&)
After TTConnection
objects have been added to the connection pool by AddConnectionToPool()
, the ConnectAll()
method can be used to connect all of the TTConnection
objects to TimesTen simultaneously. A TTStatus
object is thrown as an exception if an error occurs.
TTConnection* getConnection(int timeout_millis=0)
Checks out an idle connection from the connection pool for a thread. A pointer to an idle TTConnection
object is returned. The thread should then perform a transaction, ending with either Commit()
or Rollback()
, and then should return the connection to the pool using the freeConnection()
method.
If no idle connections are in the pool, the thread calling getConnection()
will block until a connection is returned to the pool by a call to freeConnection()
. An optional timeout, in milliseconds, can be provided. If this is provided, getConnection()
waits for a free connection for no more than timeout
milliseconds. If no connection is available in that time then getConnection()
returns NULL to the caller.
void freeConnection(TTConnection*)
Returns a connection to the pool for reassignment to another thread. Applications should not free connections that are in the midst of a transaction. TTConnection::Commit()
or TTConnection::Rollback()
should be called immediately prior to calling freeConnection()
.
void DisconnectAll(TTStatus&)
Disconnects all connections in the connection pool from TimesTen.
Applications must call DisconnectAll()
prior to termination in order to avoid overhead associated with process failure analysis and recovery. A TTStatus
object is thrown as an exception if an error occurs.
void getStats(int *nGets, int *nFrees, int *nWaits, int *nTimeouts, int *maxInUse, int *nForcedCommits)
Queries the TTConnectionPool
for status information. Data returned is:
nGets
: Number of calls to getConnection()
.
nFrees
: Number of calls to freeConnection()
.
nWaits
: Number of times a call to getConnection()
had to wait before returning a connection.
nTimeouts
: Number of calls to getConnection()
that timed out.
maxInUse
: High-water mark for the most number of connections in use at one time.
nForcedCommits
: Number of times that freeConnection()
had to call Commit()
on a connection before checking it into the pool. If this counter is non-zero then the user application is not calling TTConnection::Commit()
or Rollback()
before returning a connection to the pool.
The TTGlobal
class provides a logging facility within TTClasses.
Method | Description |
---|---|
setLogStream() | Specifies where TTClasses logging information should be sent. |
setLogLevel() | Specifies the verbosity level of TTClasses logging. |
disableLogging() | Disables TTClasses logging. |
static void setLogStream(ostream & str)
Specifies where TTClasses logging information should be sent. By default, if TTClasses logging is enabled, logging is to stderr
. Using this method, a user application can specify logging to a file (or any other ostream&
), such as in the following example that sets logging to app_log.txt
:
ofstream log_file("app_log.txt"); TTGlobal::setLogStream(log_file);
static void setLogLevel(TTLog::TTLOG_LEVEL level)
This method specifies the verbosity level of TTClasses logging. Table 4-4 describes TTClasses logging levels. The levels are cumulative.
Table 4-4 TTClasses logging levels
Logging level | Description |
---|---|
|
No logging. |
|
Logs fatal errors (serious misuse of TTClasses methods). |
|
Logs all errors, such as SQL_ERROR return codes. |
|
(Default) Also logs warnings and all calls to |
|
Also logs informational messages, such as calls to most methods on |
|
Also logs debugging information, such as all bound parameter values for each call to |
To set the logging level to TTLog::TTLOG_ERR
, for example, add the following line to your program:
TTGlobal::setLogLevel (TTLog::TTLOG_ERR);
static void disableLogging()
This method disables all TTClasses logging. Note that the following two statements are identical:
TTGlobal::disableLogging(); TTGlobal::setLogLevel (TTLog::TTLOG_NIL);
The TTGlobal
logging facility can be very useful for debugging problems inside a TTClasses program. Note, however, that the most verbose logging levels (TTLog::TTLOG_INFO
and TTLog::TTLOG_DEBUG
) can generate an extremely large amount of output. Use these logging levels during development or when trying to diagnose a bug instead of during production.
When logging from a multithreaded program, you may encounter a problem where log output from different program threads is intermingled when written to disk. To alleviate this problem, disable ostream
buffering with the ios_base::unitbuf
I/O stream manipulator, as in the following example, which sends TTClasses logging to the app_log.txt
file at logging level TTLog::TTLOG_ERR
:
ofstream log_file("app_log.txt"); log_file << std::ios_base::unitbuf; TTGlobal::setLogStream(log_file); TTGlobal::setLogLevel(TTLog::TTLOG_ERR);
See "TTClasses logging" for more information about using TTGlobal
.
TTCatalog
is included in the TimesTen C++ Interface Classes to facilitate reading metadata from the database system catalog.
The TTCatalog
class is different from using the other classes in the TimesTen C++ Interface Classes. After connecting to the database and reading its system catalogs, the TTCatalog
constructor disconnects from the database, and no further direct database interaction is done. The resulting object contains data structures that contains all of the information that was read from the database catalog, and which is easily accessible to a user program.
Each TTCatalog
internally contains an array of TTCatalogTable
objects. Each TTCatalogTable
contains an array of TTCatalogColumn
objects and an array of TTCatalogIndex
objects. When accessing by index, access to these arrays is zero-based.
The following ODBC functions are used inside TTCatalog
:
SQLTables()
SQLColumns()
SQLSpecialColumns()
SQLStatistics()
This section includes the following classes:
The TTCatalog
class is the top-level class used for programmatically accessing metadata information about tables in a database. A TTCatalog
object has an internal array of TTCatalogTable
objects inside it. Apart from the constructor, all public methods of TTCatalog
are used to gain read-only access to that TTCatalogTable
array.
The TTCatalog
constructor caches the TTConnection*
parameter and initializes all the internal data structures appropriately.
TTCatalog (TTConnection*)
Then to use the TTCatalog
object, call its fetchCatalogData()
method, described shortly.
Method | Description |
---|---|
fetchCatalogData() | Reads the catalogs in the data store for information about tables and indexes as it constructs itself and stores this information into its internal data structures |
getNumTables() | Returns the total number of tables in the database, both user and system tables. |
getNumUserTables() | Returns the number of user tables in the database. |
getNumSysTables() | Returns the number of system tables in the database. |
getTable() | Returns a constant reference to the TTCatalogTable object corresponding to the specified database table. |
getTable() | Returns a constant reference to the TTCatalogTable corresponding to the n th table in the system (where n is specified). |
getUserTable() | Returns a constant reference to the TTCatalogTable corresponding to the n th user table in the system (where n is specified). |
getTableIndex() | Returns the index in the TTCatalog object for the specified table. |
fetchCatalogData(TTStatus &)
This method is the only one that interacts with the data store. The connection to the data store was cached by the constructor, so the only parameter is a TTStatus
object. This method reads the catalogs in the database for information about tables, and indexes as it constructs itself, storing the information into its internal data structures.
Subsequent use of the constructed TTCatalog
object is completely offline after it is constructed. It is no longer attached to the database.
You must call this method before you use any other TTCatalog
accessor method.
This example demonstrates the use of TTCatalog
. It does not check stat.rc
after the two database calls.
Example 4-6 Fetching catalog data
TTConnection conn; TTStatus stat; conn.Connect(DSN=TptbmData37, stat); TTCatalog cat (&conn); cat.fetchCatalogData(stat); // TTCatalog cat is no longer connected to the database; // you can now query it through its read-only methods. cerr << "There are " << cat.getNumTables() << " tables in this database:" << endl; for (int i=0; i < cat.getNumTables(); i++) cerr << cat.getTable(i).getTableOwner() << "." << cat.getTable(I).getTableName() << endl;
int getNumTables()
Returns the total number of tables in the database, both user and system tables.
int getNumUserTables()
Returns the number of user tables in the database.
int getNumSysTables()
Returns the number of system tables in the database.
There is no corresponding getSysTable()
method.
const TTCatalogTable & getTable(const char * owner, const char * tblname)
Returns a constant reference to the TTCatalogTable
object corresponding to the database table named tblname
owned by owner
. See "TTCatalogTable".
const TTCatalogTable & getTable(int tno)
Returns a constant reference to the TTCatalogTable
corresponding to table number tno
in the system. This method is intended to facilitate iteration through all of the tables in the system; the order of the tables in this array is arbitrary.
Note that the following relationship is asserted to hold:
0 <= tno
<= getNumTables()
const TTCatalogTable & getUserTable(int tno)
Returns a constant reference to the TTCatalogTable
corresponding to user table number tno
in the system. This method is intended to facilitate iteration through all of the user tables in the system; the order of the user tables in this array is arbitrary.
Note that the following relationship is asserted to hold:
0 <= tno
<= getNumUserTables()
int getTableIndex(const char * owner, const char * tblname) const
This method fetches the index in the TTCatalog
object for the specified owner.tblname
object. It returns -2 if the owner.tblname
does not exist. It returns -1 if the catalog did not call fetchCatalogData()
before calling TTCatalog::getTableIndex()
.
This example retrieves information about the TTUSER.MYDATA table from a TTCatalog
object. You can then call methods of TTCatalogTable
, described shortly, to get information about this table.
Example 4-7 Retrieving table information from a catalog
TTConnection conn; TTStatus stat; conn.Connect(...); TTCatalog cat (&conn); cat.fetchCatalogData(stat); int idx = cat.getTableIndex("TTUSER", "MYDATA"); if (idx < 0) { cerr << "Table TTUSER.MYDATA does not exist." << endl; return; } TTCatalogTable &table = cat.getTable(idx);
Used to store all metadata information about a table's columns and indexes.
Method | Description |
---|---|
getTableOwner() | Returns the owner of the table. |
getTableName() | Returns the name of the table. |
getNumColumns() | Returns the number of columns in the table. |
getNumIndexes() | Returns the number of indexes on the table. |
getColumn() | Returns a constant reference to the TTCatalogColumn corresponding to the ith column in the table. |
getIndex() | Returns a constant reference to the TTCatalogIndex corresponding to the ith index in the table. |
isSystemTable() | Returns TRUE if the table is a system table. |
isUserTable() | Returns TRUE if the table is a user table. |
const char * getTableOwner()
Returns the owner of the table.
const char * getTableName()
Returns the name of the table.
int getNumColumns()
Returns the number of columns in the table.
int getNumIndexes()
Returns the number of indexes on the table.
const TTCatalogColumn & getColumn(int i)
Returns a constant reference to the TTCatalogColumn
corresponding to column number i
in the table. This method is intended to facilitate iteration through all of the user tables in the system.
Note that the following relationship is asserted to hold:
0 <= i
<= getNumColumns()
const TTCatalogIndex & getIndex(int i)
Returns a constant reference to the TTCatalogIndex
corresponding to index number i
in the table. This method is intended to facilitate iteration through all of the user tables in the system; the order of a table's indexes in this array is arbitrary.
Note that the following relationship is asserted to hold:
0 <= i
<= getNumColumns()
bool isSystemTable()
Returns TRUE if the table is a system table (owned by SYS or TTREP). It returns FALSE otherwise.
bool isUserTable()
Returns TRUE if this is a user table. It returns FALSE otherwise. Note that the definition of a user table is one that is not a system table. Thus isUserTable()
returns the opposite of isSystemTable()
for any table.
The isSystemTable()
and isUserTable()
methods are useful for applications that iterate over all tables in a database after a call to TTCatalog::fetchCatalogData()
, so that you can filter or annotate tables to differentiate the system and user tables. See the TTClasses demo program catalog
for an example of how this can be done.
The TTCatalogColumn
class is used to store all metadata information about a single table column of the TTCatalogTable
object it is associated with.
Method | Description |
---|---|
getColumnName() | Return the name of the column. |
getDataType() | Returns an integer representing the ODBC SQL data type of the column. |
getTypeName() | Returns the database-dependent name that corresponds to the type returned by getDataType() . |
getNullable() | Returns SQL_NO_NULLS, SQL_NULLABLE, or SQL_NULLABLE_UNKNOWN. |
getPrecision() | Returns the precision of the column. |
getLength() | Returns the length of the column, in bytes. |
getScale() | Returns the scale of the column. |
getRadix() | Returns the radix of the column. |
const char * getColumnName()
Return the name of the column.
int getDataType()
Returns an integer representing the data type of the column. This is the standard ODBC SQL Type.
const char * getTypeName()
Returns the database-dependent name that corresponds to the type returned by getdataType()
.
int getNullable()
Returns SQL_NO_NULLS, SQL_NULLABLE, or SQL_NULLABLE_UNKNOWN.
int getPrecision()
Returns the precision of the column.
int getLength()
Returns the length of the column, in bytes.
int getScale()
Returns the scale of the column.
int getRadix()
Returns the radix of the column.
Used to store all information about an index of the TTCatalogTable
it is associated with.
Method | Description |
---|---|
getIndexName() | Returns the name of the index. |
getIndexOwner() | Returns the owner of the index. |
getTableName() | Returns the name of the table for which the index was created. |
getType() | Returns the type of the index. |
isUnique() | Returns whether the index is a unique index. |
getNumColumns() | Returns the number of columns in the index. |
getColumnName() | Returns the column name of the specified column in the index. |
getCollation() | Returns the collation of the specified column in the index. |
const char * getIndexName()
Returns the name of the index.
const char * getIndexOwner()
Returns the owner of the index.
const char * getTableName()
Returns the name of the table for which the index was created.
int getType()
Returns the type of the index. For TimesTen, the allowable values are PRIMARY_KEY, HASH_INDEX (the same as PRIMARY_KEY), and TTREE_INDEX. For other databases, allowable values are SQL_INDEX_HASHED and SQL_INDEX_CLUSTERED.
bool isUnique()
Returns whether the index is a unique index. TRUE means it is unique; FALSE means it is not unique.
int getNumColumns()
Returns the number of columns in the index.
const char * getColumnName(int i)
Returns the column name of column number i
in the index.
char getCollation (int i)
Returns the collation of column number i
in the index. Values returned are 'A' for ascending and 'D' for descending index order.
TTClasses provides a set of C++ classes that make it easy to write applications that use the TimesTen Transaction Log API (XLA).
XLA is a set of C callable functions that allow an application to monitor changes made to one or more tables in a TimesTen data store. Whenever another application changes a monitored tables, the application using XLA is informed of the changes. For more information about XLA, see "XLA and TimesTen Event Management" in the Oracle TimesTen In-Memory Database C Developer's Guide.
The XLA classes supports as many XLA columns as the maximum number of columns supported by TimesTen. For more information, see "System Limits" in the Oracle TimesTen In-Memory Database Reference.
Table 4-5 lists the TTClasses XLA classes and their descriptions.
Table 4-5 TTClasses XLA classes
Class | Description |
---|---|
Defines a persistent connection to a TimesTen data store. |
|
Fetches column values from a particular update record. |
|
Provides methods that enable and disable change tracking for a table. Methods are also provided to handle update notification records from XLA. |
|
Provides a list of TTXlaTableHandler objects. This class is used to route a particular change to the appropriate method for processing. Incoming update notification records are routed to the appropriate method of the appropriate TTXlaTableHandler object for processing. |
TTXlaPersistConnection
defines a persistent connection to a TimesTen data store.
Method | Description |
---|---|
Connect() | Connects with the specified bookmark. |
Connect() | Connects with the specified bookmark. It creates a bookmark if one does not exist. |
DeleteBookmarkAndDisconnect() | Deletes the bookmark and disconnects from the data store. |
Disconnect() | Closes an XLA connection to a TimesTen data store. |
ackUpdates() | Advances the bookmark to the next set of updates. |
getBookmarkIndex() | Stores the current place in the transaction log. |
setBookmarkIndex() | Returns to the saved transaction log index. |
fetchUpdatesWait() | Fetches updates to the transaction log within the specified wait period. |
virtual void Connect(const char* connStr, const char * bookmark, bool createBookmark, TTStatus&);
Each persistent XLA connection has a name (or bookmark
) associated with it, so that upon disconnect and reconnect, the same place in the transaction log can be found. The name for a connection's bookmark is specified in the bookmark
parameter.
Note:
Only one XLA connection can connect with a given bookmark name. An error will be returned if multiple connections try to connect to the same bookmark.Whether this is a new bookmark, or a previously created bookmark, is specified by the createBookmark
boolean parameter. If you specify that a bookmark is new (createBookmark==true
) and it already exists, an error will be returned. Similarly, if you specify that a bookmark already exists (createBookmark==false
) and it does not already exist, an error will be returned.
virtual void Connect(const char* connStr, const char * bookmark, TTStatus&);
This second connect method first tries to connect using the supplied bookmark, reusing it (implicit value of createBookmark==false
). If that bookmark does not exist, the method then tries to connect and create a new bookmark with the name bookmark
(implicit value of createBookmark==true
).
This method is provided as a convenience, to simplify XLA connection logic in case the developer does not wish to worry about whether the XLA bookmark exists.
void DeleteBookmarkAndDisconnect(TTStatus&)
This method deletes the bookmark that is currently associated with the connection, so that the data store no longer keeps records relevant to that bookmark. It then disconnects from the data store.
virtual void Disconnect(TTStatus&)
This method closes an XLA connection to a TimesTen data store. The XLA bookmark persists after you call this method. If you want to delete the bookmark and disconnect from the data store, then use DeleteBookmarkAndDisconnect()
instead (described immediately above).
void ackUpdates(TTStatus &)
This method is used to advance the bookmark to the next set of updates. After you have acknowledged a set of updates, the updates cannot be viewed again. See the descriptions of getBookMarkIndex()
and setBookMarkIndex()
, following shortly, for information about replaying a set of updates.
Applications should acknowledge updates when a batch of XLA records have been read and processed so that transaction log files do not fill up the disk where they are stored. Do not call ackUpdates()
too frequently, because it is a relatively expensive operation.
If an application uses XLA to read a batch of records and then a failure occurs, the records can be retrieved when the application reconnects using XLA.
void getBookmarkIndex(TTStatus &)
This method acquires the current bookmark location.
void setBookmarkIndex(TTStatus &)
This method restores the bookmark to the previously acquired bookmark location. Use this method to replay a batch of records multiple times.
Note that ackUpdates()
invalidates the stored transaction log placeholder. After ackUpdates()
, a call to setBookmarkIndex()
returns an error because it is no longer possible to go back to the previously acquired bookmark location.
void fetchUpdatesWait(ttXlaUpdateDesc_t*** arry, int maxrecs, int* recsP, int seconds, TTStatus&)
This method is used by an XLA application to fetch a set of records describing changes to a data store. A list of ttXlaUpdateDesc_t
structures is returned. If there are no XLA updates to be fetched, this method waits the specified number of seconds before returning.
The caller specifies the maximum number of records it is willing to receive. When the method returns, the caller receives the number of records actually returned, as well as an array of pointers which point to structures defining the changes.
The ttXlaUpdateDesc_t
structures that are returned by this method are defined in the XLA specification. No C++ object-oriented encapsulation of these methods is provided.
A persistent XLA application can create multiple TTXlaPersistConnection objects. Each TTXlaPersistConnection
object must be associated with its own bookmark, which is specified at connect time and must be maintained through the ackUpdates()
and deleteBookmark()
methods.
After a persistent XLA connection is made, the application should enter a loop in which the fetchUpdatesWait()
method is called repeatedly until application termination. This loop should fetch updates from XLA as rapidly as possible, to prevent the transaction log from overfilling disk. After processing a batch of updates, the application should call ackUpdates()
in order to acknowledge those updates and get ready for the next call to fetchUpdatesWait()
. A batch of updates can be replayed using the setBookmarkIndex()
and getBookmarkIndex()
methods. Also, if the persistent XLA application disconnects after fetchUpdatesWait()
, but before ackUpdates()
, the next connection (with the same bookmark name) which calls fetchUpdatesWait()
will see that same batch of updates.
Updates that occur while a TTXlaPersistConnection
object is disconnected to the data store are not lost, but are stored in the transaction log until another TTXlaPersistConnection
object connects with the same bookmark name.
The TTXlaRowViewer
class allows application developers to examine XLA change notification record structures to fetch old and new column values.
Before a row can be examined, the TTXlaRowViewer
object must be associated with a table (using the setTable()
method) and a row (using the setTuple()
method). The table is a TTXlaTable
object previously defined. The row is part of a ttXlaUpdateDesc_t
structure as returned by XLA using the TTXlaPersistConnection::fetchUpdateWait()
method.
Method | Description |
---|---|
setTable() | Associates TTXlaRowViewer with the specified table. |
setTuple() | Associates the TTXlaRowViewer object with the specified row image. |
isNull() | Indicates whether the specified column in a row image is NULL. |
"Get()" | Fetches the value of the specified column in a row image. |
void setTable(TTXlaTable*)
This associates this TTXlaRowViewer
with a particular table.
void setTuple(ttXlaUpdateDesc_t*, int whichTuple)
This method associates this TTXlaRowViewer
object with a particular row image.
The ttXlaUpdateDesc_t
structures that are returned by TTXlaPersistConnection::fetchUpdatesWait()
contain either zero, one, or two rows.
Structures that define a row that was inserted into a table contain the row image of the inserted row.
Structures that define a row that was deleted from a table contain the row image of the deleted row.
Structures that define a row that was updated in a table contain the images of the row before and after the update.
Structures that define other changes to the table or the data store contain no row images. For example, structures reporting that an index was dropped contain no row images.
The setTuple()
method takes two arguments:
A pointer to a particular ttXlaUpdateDesc_t
structure defining a database change.
An integer specifying which of row images in the update structure should be examined. Values for this parameter are:
INSERTED_TUP: Examine the newly inserted row
DELETED_TUP: Examine the deleted row
UPDATE_OLD_TUP: Examine the row before it was updated
UPDATE_NEW_TUP: Examine the row after it was updated
After the setTable()
and setTuple()
methods are called, the following methods can be used to fetch information about row images in the update records.
bool isNull(int whichCol)
Indicates whether a particular column in a row image is NULL (returns TRUE) or not (returns FALSE).
The whichCol
parameter is the column number for the column to be interrogated.
void Get(int col, ...)
Fetches the value of a particular column in a row image.
These methods are very similar to the TTCmd::getColumn()
methods.
The col
parameter is the column number for the column to be interrogated.
Table 4-6 shows the supported SQL data types and the appropriate versions of Get
to use for each parameter type. There are six variants for the NUMBER data type and two variants for the FLOAT data type. Design the application according to the kind of data that is stored. For example, data of type NUMBER(9,0) can be accessed by the Get(int, int*)
method without loss of data.
Note:
In this table, lengthlen
is in bytes.Table 4-6 TTXlaRowViewer::Get() variants for supported data types
XLA data type | Database data type | Get variant |
---|---|---|
TTXLA_CHAR_TT |
TT_CHAR |
|
TTXLA_NCHAR_TT |
TT_NCHAR |
|
TTXLA_VARCHAR_TT |
TT_VARCHAR |
|
TTXLA_NVARCHAR_TT |
TT_NVARCHAR |
|
TTXLA_TINYINT |
TT_TINYINT |
|
TTXLA_SMALLINT |
TT_SMALLINT |
|
TTXLA_INTEGER |
TT_INTEGER |
|
TTXLA_BIGINT |
TT_BIGINT |
|
TTXLA_BINARY_FLOAT |
BINARY_FLOAT |
|
TTXLA_BINARY_DOUBLE |
BINARY_DOUBLE |
|
TTXLA_DECIMAL_TT |
TT_DECIMAL |
|
TTXLA_TIME |
TT_TIME |
|
TTXLA_DATE_TT |
TT_DATE |
|
TTXLA_TIMESTAMP_TT |
TT_TIMESTAMP |
|
TTXLA_BINARY |
BINARY |
|
TTXLA_VARBINARY |
VARBINARY |
|
TTXLA_NUMBER |
NUMBER |
|
TTXLA_DATE |
DATE |
|
TTXLA_TIMESTAMP |
TIMESTAMP |
|
TTXLA_CHAR |
CHAR |
|
TTXLA_NCHAR |
NCHAR |
|
TTXLA_VARCHAR |
VARCHAR2 |
|
TTXLA_NVARCHAR |
NVARCHAR2 |
|
TTXLA_FLOAT |
FLOAT |
|
The TTXlaTableHandler
class is intended as a base class from which application developers write customized classes to process changes to a particular table.
The constructor associates the TTXlaTableHandler with a particular table and initializes the TTXlaTable
object contained within this object:
TTXlaTableHandler(TTXlaConnection& conn, const char* ownerP, const char* nameP)
(See "Internal classes" regarding TTXlaTable
.)
Member | Description |
---|---|
TTXlaTable tbl; |
The object associated with the table being handled. |
TTXlaRowViewer row; |
Used to view the row being inserted or deleted, or the old image of the row being changed. |
TTXlaRowViewer row2; |
Used to view the new image of the row being updated. |
Method | Description |
---|---|
EnableTracking() | Enables XLA update tracking for the underlying table. |
DisableTracking() | Disables XLA update tracking for the underlying table. |
HandleChange() | Dispatches a record from ttXlaUpdateDesc_t to the appropriate handling routine for processing. |
HandleDelete() | Invoked when the HandleChange() method is called to process a delete operation. |
HandleInsert() | Invoked when the HandleChange() method is called to process an insert operation. |
HandleUpdate() | Invoked when the HandleChange() method is called to process an update operation. |
generateSQL() | Returns the SQL associated with a given XLA record. |
virtual void EnableTracking(TTStatus&);
Enables XLA update tracking for the underlying table. Until this method is called, XLA will not return information about changes to this table.
virtual void DisableTracking(TTStatus&);
Disables XLA update tracking for the underlying table. After this method is called, XLA will not return information about changes to this table.
virtual void HandleChange(ttXlaUpdateDesc_t*, void* pData = 0);
Dispatches a ttXlaUpdateDesc_t
to the appropriate handling routine for processing. The update description is analyzed to determine if it is a delete, insert or update. The appropriate virtual method—HandleDelete()
, HandleInsert()
, or HandleUpdate()
—is then called.
See "Acknowledging XLA updates at transaction boundaries" for an example that uses the pData
parameter.
virtual void HandleDelete(ttXlaUpdateDesc_t*) = 0;
This method will be invoked whenever the HandleChange()
method is called to process a delete operation.
This method is not implemented in the TTXlaTableHandler
base class, but must be provided by any classes derived from it. Application developers should put their logic to handle deleted rows in this method.
The row that was deleted from the table is available through the RowViewer
named row
.
virtual void HandleInsert(ttXlaUpdateDesc_t*) = 0;
This method will be invoked whenever the HandleChange()
method is called to process a insert operation.
This method is not implemented in the TTXlaTableHandler
base class, but must be provided by any classes derived from it. Application developers should put their logic to handle inserted rows in this method.
The row that was inserted from the table is available through the RowViewer
named row
.
virtual void HandleUpdate(ttXlaUpdateDesc_t*) = 0;
This method will be invoked whenever the HandleChange()
method is called to process an update operation.
This method is not implemented in the TTXlaTableHandler
base class, but must be provided by any classes derived from it. Application developers should put their logic to handle updated rows in this method.
The previous version of the row that was updated from the table is available through the RowViewer
object named row
; the new version of the row is available through the RowViewer
object named row2
.
void generateSQL (ttXlaUpdateDesc_t*, char * buffer, SQLINTEGER maxLen, SQLINTEGER *actualLen, TTStatus &);
This method can be used to print out the SQL associated with a given XLA record. The SQL string is returned through the buffer
parameter, which the caller of this method has allocated space for and specified its length in the maxLen
parameter. The actualLen
parameter returns information about the actual length of the SQL string returned. Lengths are in bytes.
If maxLen
is less than the generated SQL string, a TTStatus
error will be returned, and the contents of buffer and actualLen
will be unmodified.
Application developers can derive one or more classes from TTXlaTableHandler
, and can put most of the application's logic in the HandleInsert()
, HandleDelete()
, and HandleUpdate()
methods of that class.
One strategy is to derive multiple classes from TTXlaTableHandler
, one for each table. Business logic to handle changes to customers might be implemented in a CustomerTableHandler
class, while business logic to handle changes to orders might be implemented in a OrderTableHandler
class.
Another strategy is to derive one or more generic classes from TTXlaTableHandler
to handle various scenarios. For example, a generic class derived from TTXlaTableHandler
could be used to publish changes using a publish/subscribe system.
The TTXlaTableList
class is used to dispatch update notification events to the appropriate TTXlaTableHandler
. A list of TableHandler
objects is maintained in the class. As update notifications are received from XLA, the appropriate Handle
methods of the appropriate TableHandler
is called to process each record.
For example, if an object of type CustomerTableHandler
is handling changes to table CUSTOMER, and an object of type OrderTableHandler
is handling changes to table ORDERS, the application should include both of these objects in a TTXlaTableList
. As XLA update notification records are fetched from XLA, they can be dispatched to the correct handler by simply calling TTXlaTableList::HandleChange()
.
The constructor has two forms:
TTXlaTableList(TTXlaConnection *, unsigned int i)
Where i
is the number of database objects to monitor.
Or:
TTXlaTableList(TTXlaConnection* cP);
Where cP
references the database connection to be used for XLA operations. This form of the constructor can monitor up to 150 database objects.
Method | Description |
---|---|
add() | Adds a TableHandler to the list. |
del() | Deletes a TableHandler from the list. |
HandleChange() | Processes a record obtained from ttXlaUpdateDesc_t . |
void add(TTXlaTableHandler* h);
Adds a TableHandler
to the list.
void del(TTXlaTableHandler* h);
Deletes a TableHandler
from the list.
void HandleChange(ttXlaUpdateDesc_t* p, TTStatus&);
When a ttXlaUpdateDesc_t
is received from XLA, it can be processed by calling this method. This method determines which table the record references and calls the HandleChange()
method of the appropriate TableHandler
.
These classes are provided in the C++ class library and are used internally in other classes. Their implementation may change.
TTCommand
: The base class of TTCmd, the TTCommand
class provides a low level C++ mapping for ODBC statements (SQLHSTMT) and ODBC function calls.
TTParameter
: TTCmd implements self-defining parameters through the TTParameter
class.
TTColumn
: TTCmd implements self-defining columns through the TTColumn
class.
TTXlaTable
: TTXlaTable
objects define information about tables which are being monitored for changes.
TTXlaColumn
: TTXlaRowViewer uses this function to define a single column in a table.