![]() |
Kea
2.3.5-git
|
Common PgSql Connector Pool. More...
#include <pgsql_connection.h>
Public Types | |
typedef std::function< void(PgSqlResult &, int)> | ConsumeResultRowFun |
Function invoked to process fetched row. More... | |
![]() | |
typedef std::map< std::string, std::string > | ParameterMap |
Database configuration parameter map. More... | |
Public Member Functions | |
PgSqlConnection (const ParameterMap ¶meters, IOServiceAccessorPtr io_accessor=IOServiceAccessorPtr(), DbCallback callback=DbCallback()) | |
Constructor. More... | |
virtual | ~PgSqlConnection () |
Destructor. More... | |
void | checkStatementError (const PgSqlResult &r, PgSqlTaggedStatement &statement) |
Checks result of the r object. More... | |
void | commit () |
Commits current transaction. More... | |
bool | compareError (const PgSqlResult &r, const char *error_state) |
Checks a result set's SQL state against an error state. More... | |
void | createSavepoint (const std::string &name) |
Creates a savepoint within the current transaction. More... | |
PgSqlResultPtr | executePreparedStatement (PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings=PsqlBindArray()) |
Executes a prepared SQL statement. More... | |
void | executeSQL (const std::string &sql) |
Executes the an SQL statement. More... | |
std::string | getConnParameters () |
Creates connection string from specified parameters. More... | |
void | insertQuery (PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings) |
Executes INSERT prepared statement. More... | |
bool | isTransactionStarted () const |
Checks if there is a transaction in progress. More... | |
void | openDatabase () |
Open Database. More... | |
operator bool () const | |
Boolean Operator. More... | |
operator PGconn * () const | |
Conversion Operator. More... | |
void | prepareStatement (const PgSqlTaggedStatement &statement) |
Prepare Single Statement. More... | |
void | prepareStatements (const PgSqlTaggedStatement *start_statement, const PgSqlTaggedStatement *end_statement) |
Prepare statements. More... | |
void | rollback () |
Rollbacks current transaction. More... | |
void | rollbackToSavepoint (const std::string &name) |
Rollbacks to the given savepoint. More... | |
void | selectQuery (PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings, ConsumeResultRowFun process_result_row) |
Executes SELECT query using prepared statement. More... | |
void | startRecoverDbConnection () |
The recover connection. More... | |
void | startTransaction () |
Starts new transaction. More... | |
uint64_t | updateDeleteQuery (PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings) |
Executes UPDATE or DELETE prepared statement and returns the number of affected rows. More... | |
![]() | |
DatabaseConnection (const ParameterMap ¶meters, DbCallback callback=DbCallback()) | |
Constructor. More... | |
virtual | ~DatabaseConnection () |
Destructor. More... | |
void | checkUnusable () |
Throws an exception if the connection is not usable. More... | |
bool | configuredReadOnly () const |
Convenience method checking if database should be opened with read only access. More... | |
std::string | getParameter (const std::string &name) const |
Returns value of a connection parameter. More... | |
bool | isUnusable () |
Flag which indicates if connection is unusable. More... | |
virtual void | makeReconnectCtl (const std::string &timer_name) |
Instantiates a ReconnectCtl based on the connection's reconnect parameters. More... | |
util::ReconnectCtlPtr | reconnectCtl () |
The reconnect settings. More... | |
Static Public Member Functions | |
static std::pair< uint32_t, uint32_t > | getVersion (const ParameterMap ¶meters) |
Get the schema version. More... | |
![]() | |
static bool | invokeDbFailedCallback (const util::ReconnectCtlPtr &db_reconnect_ctl) |
Invokes the connection's restore failed connectivity callback. More... | |
static bool | invokeDbLostCallback (const util::ReconnectCtlPtr &db_reconnect_ctl) |
Invokes the connection's lost connectivity callback. More... | |
static bool | invokeDbRecoveredCallback (const util::ReconnectCtlPtr &db_reconnect_ctl) |
Invokes the connection's restored connectivity callback. More... | |
static ParameterMap | parse (const std::string &dbaccess) |
Parse database access string. More... | |
static std::string | redactedAccessString (const ParameterMap ¶meters) |
Redact database access string. More... | |
static isc::data::ElementPtr | toElement (const ParameterMap ¶ms) |
Unparse a parameter map. More... | |
static isc::data::ElementPtr | toElementDbAccessString (const std::string &dbaccess) |
Unparse an access string. More... | |
Public Attributes | |
PgSqlHolder | conn_ |
PgSql connection handle. More... | |
isc::asiolink::IOServicePtr | io_service_ |
IOService object, used for all ASIO operations. More... | |
IOServiceAccessorPtr | io_service_accessor_ |
Accessor function which returns the IOService that can be used to recover the connection. More... | |
int | transaction_ref_count_ |
Reference counter for transactions. More... | |
Static Public Attributes | |
static const char | DUPLICATE_KEY [] = ERRCODE_UNIQUE_VIOLATION |
Define the PgSql error state for a duplicate key error. More... | |
static const char | NULL_KEY [] = ERRCODE_NOT_NULL_VIOLATION |
Define the PgSql error state for a null foreign key error. More... | |
static bool | warned_about_tls = false |
Emit the TLS support warning only once. More... | |
![]() | |
static DbCallback | db_failed_callback_ = 0 |
Optional callback function to invoke if an opened connection recovery failed. More... | |
static DbCallback | db_lost_callback_ = 0 |
Optional callback function to invoke if an opened connection is lost. More... | |
static DbCallback | db_recovered_callback_ = 0 |
Optional callback function to invoke if an opened connection recovery succeeded. More... | |
static const time_t | MAX_DB_TIME = 2147483647 |
Defines maximum value for time that can be reliably stored. More... | |
Additional Inherited Members | |
![]() | |
void | markUnusable () |
Sets the unusable flag to true. More... | |
![]() | |
DbCallback | callback_ |
The callback used to recover the connection. More... | |
Common PgSql Connector Pool.
This class provides common operations for PgSql database connection used by both PgSqlLeaseMgr and PgSqlHostDataSource. It manages connecting to the database and preparing compiled statements. Its fields are public, because they are used (both set and retrieved) in classes that use instances of PgSqlConnection.
Definition at line 198 of file pgsql_connection.h.
typedef std::function<void(PgSqlResult&, int)> isc::db::PgSqlConnection::ConsumeResultRowFun |
Function invoked to process fetched row.
Definition at line 206 of file pgsql_connection.h.
|
inline |
Constructor.
Initialize PgSqlConnection object with parameters needed for connection.
parameters | Specify the connection details. |
io_accessor | The IOService accessor function. |
callback | The connection recovery callback. |
Definition at line 218 of file pgsql_connection.h.
References isc::db::PgSqlTaggedStatement::name.
|
virtual |
Destructor.
Definition at line 122 of file pgsql_connection.cc.
References isc::db::DB_LOG< log_type >::arg(), and isc::db::PGSQL_DEALLOC_ERROR.
void isc::db::PgSqlConnection::checkStatementError | ( | const PgSqlResult & | r, |
PgSqlTaggedStatement & | statement | ||
) |
Checks result of the r object.
This function is used to determine whether or not the SQL statement execution succeeded, and in the event of failures, decide whether or not the failures are recoverable.
If the error is recoverable, the function will throw a DbOperationError. If the error is deemed unrecoverable, such as a loss of connectivity with the server, the function will call startRecoverDbConnection() which will start the connection recovery.
If the invocation returns true, this indicates the calling layer will attempt recovery, and the function throws a DbOperationError to allow the caller to error handle the failed db access attempt.
r | result of the last PostgreSQL operation |
statement | - tagged statement that was executed |
isc::db::DbOperationError | Detailed PostgreSQL failure |
Definition at line 294 of file pgsql_connection.cc.
References isc::db::DB_LOG< log_type >::arg(), isc_throw, isc::db::PgSqlTaggedStatement::name, and isc::db::PGSQL_FATAL_ERROR.
void isc::db::PgSqlConnection::commit | ( | ) |
Commits current transaction.
Commits all pending database operations. On databases that don't support transactions, this is a no-op.
When this method is called for a nested transaction it decrements the transaction reference counter incremented during the call to startTransaction
.
DbOperationError | If the commit failed. |
Definition at line 370 of file pgsql_connection.cc.
References isc::db::DB_DBG_TRACE_DETAIL, isc_throw, and isc::db::PGSQL_COMMIT.
Referenced by isc::db::PgSqlTransaction::commit().
bool isc::db::PgSqlConnection::compareError | ( | const PgSqlResult & | r, |
const char * | error_state | ||
) |
Checks a result set's SQL state against an error state.
r | result set to check |
error_state | error state to compare against |
Definition at line 286 of file pgsql_connection.cc.
References PGSQL_STATECODE_LEN.
void isc::db::PgSqlConnection::createSavepoint | ( | const std::string & | name | ) |
Creates a savepoint within the current transaction.
Creates a named savepoint within the current transaction.
name | name of the savepoint to create. |
InvalidOperation | if called outside a transaction. |
DbOperationError | If the savepoint cannot be created. |
Definition at line 410 of file pgsql_connection.cc.
References isc::db::DB_LOG< log_type >::arg(), isc::db::DB_DBG_TRACE_DETAIL, isc_throw, and isc::db::PGSQL_CREATE_SAVEPOINT.
PgSqlResultPtr isc::db::PgSqlConnection::executePreparedStatement | ( | PgSqlTaggedStatement & | statement, |
const PsqlBindArray & | in_bindings = PsqlBindArray() |
||
) |
Executes a prepared SQL statement.
It executes the given prepared SQL statement, after checking for usability and input parameter sanity. After the statement is executed checkStatementError()
is invoked to ensure we detect connectivity issues properly. Upon successful execution, the the result set is returned. It may be used for any form of prepared SQL statement (e.g query, insert, update, delete...), with or without input parameters.
statement | PgSqlTaggedStatement describing the prepared statement to execute. |
in_bindings | array of input parameter bindings. If the SQL statement requires no input arguments, this parameter should either be omitted or an empty PsqlBindArray should be supplied. |
InvalidOperation | if the number of parameters expected by the statement does not match the size of the input bind array. |
Definition at line 441 of file pgsql_connection.cc.
References isc::db::PsqlBindArray::formats_, isc_throw, isc::db::PsqlBindArray::lengths_, isc::db::PgSqlTaggedStatement::name, isc::db::PgSqlTaggedStatement::nbparams, isc::db::PsqlBindArray::size(), isc::db::PgSqlTaggedStatement::text, and isc::db::PsqlBindArray::values_.
void isc::db::PgSqlConnection::executeSQL | ( | const std::string & | sql | ) |
Executes the an SQL statement.
It executes the given SQL text after first checking the connection for usability. After the statement is executed checkStatementError()
is invoked to ensure we detect connectivity issues properly. It is intended to be used to execute utility statements such as commit, rollback et al, which have no parameters, return no results, and are not pre-compiled.
sql | SQL statement to execute. |
Definition at line 431 of file pgsql_connection.cc.
References isc::db::OID_NONE.
std::string isc::db::PgSqlConnection::getConnParameters | ( | ) |
Creates connection string from specified parameters.
This function is called frin the openDatabase
and from the unit tests.
openDatabase
. NoDatabaseName | Mandatory database name not given |
DbInvalidTimeout | when the database timeout is wrong. |
Definition at line 184 of file pgsql_connection.cc.
References isc_throw, isc::db::PGSQL_DEFAULT_CONNECTION_TIMEOUT, and isc::Exception::what().
|
static |
Get the schema version.
parameters | A data structure relating keywords and values concerned with the database. |
isc::db::DbOperationError | An operation on the open database has failed. |
Definition at line 137 of file pgsql_connection.cc.
References conn_, isc::db::PgSqlExchange::getColumnValue(), isc_throw, openDatabase(), and version().
Referenced by isc::dhcp::PgSqlLeaseMgr::getVersion(), and isc::dhcp::PgSqlHostDataSourceImpl::getVersion().
void isc::db::PgSqlConnection::insertQuery | ( | PgSqlTaggedStatement & | statement, |
const PsqlBindArray & | in_bindings | ||
) |
Executes INSERT prepared statement.
The statement
must refer to an existing prepared statement associated with the connection. The in_bindings
size must match the number of placeholders in the prepared statement.
This method executes prepared statement using provided bindings to insert data into the database.
statement | reference to the precompiled tagged statement to execute |
in_bindings | input bindings holding values to substitue placeholders in the query. |
Definition at line 492 of file pgsql_connection.cc.
bool isc::db::PgSqlConnection::isTransactionStarted | ( | ) | const |
Checks if there is a transaction in progress.
Definition at line 365 of file pgsql_connection.cc.
void isc::db::PgSqlConnection::openDatabase | ( | ) |
Open Database.
Opens the database using the information supplied in the parameters passed to the constructor.
NoDatabaseName | Mandatory database name not given |
DbOpenError | Error opening the database |
Definition at line 264 of file pgsql_connection.cc.
References isc_throw.
Referenced by getVersion().
|
inline |
Boolean Operator.
Allows testing the PgConnection for initialized connection
Definition at line 509 of file pgsql_connection.h.
|
inline |
Conversion Operator.
Allows the PgConnection object to be passed as the context argument to PQxxxx functions.
Definition at line 502 of file pgsql_connection.h.
void isc::db::PgSqlConnection::prepareStatement | ( | const PgSqlTaggedStatement & | statement | ) |
Prepare Single Statement.
Creates a prepared statement from the text given and adds it to the statements_ vector at the given index.
statement | SQL statement to be prepared. |
isc::db::DbOperationError | An operation on the open database has failed. |
Definition at line 161 of file pgsql_connection.cc.
References isc_throw, isc::db::PgSqlTaggedStatement::name, isc::db::PgSqlTaggedStatement::nbparams, isc::db::PgSqlTaggedStatement::text, and isc::db::PgSqlTaggedStatement::types.
void isc::db::PgSqlConnection::prepareStatements | ( | const PgSqlTaggedStatement * | start_statement, |
const PgSqlTaggedStatement * | end_statement | ||
) |
Prepare statements.
Creates the prepared statements for all of the SQL statements used by the PostgreSQL backend.
start_statement | Pointer to the first statement in range of the statements to be compiled. |
end_statement | Pointer to the statement marking end of the range of statements to be compiled. This last statement is not compiled. |
isc::db::DbOperationError | An operation on the open database has failed. |
Definition at line 174 of file pgsql_connection.cc.
void isc::db::PgSqlConnection::rollback | ( | ) |
Rollbacks current transaction.
Rolls back all pending database operations. On databases that don't support transactions, this is a no-op.
When this method is called for a nested transaction it decrements the transaction reference counter incremented during the call to startTransaction
.
DbOperationError | If the rollback failed. |
Definition at line 390 of file pgsql_connection.cc.
References isc::db::DB_DBG_TRACE_DETAIL, isc_throw, and isc::db::PGSQL_ROLLBACK.
Referenced by isc::db::PgSqlTransaction::~PgSqlTransaction().
void isc::db::PgSqlConnection::rollbackToSavepoint | ( | const std::string & | name | ) |
Rollbacks to the given savepoint.
Rolls back all pending database operations made after the named savepoint.
name | name of the savepoint to which to rollback. |
InvalidOperation | if called outside a transaction. |
DbOperationError | if the rollback failed. |
Definition at line 421 of file pgsql_connection.cc.
References isc_throw.
void isc::db::PgSqlConnection::selectQuery | ( | PgSqlTaggedStatement & | statement, |
const PsqlBindArray & | in_bindings, | ||
ConsumeResultRowFun | process_result_row | ||
) |
Executes SELECT query using prepared statement.
The statement parameter refers to an existing prepared statement associated with the connection. The in_bindings
size must match the number of placeholders in the prepared statement.
This method executes prepared statement using provided input bindings and calls process_result_row
function for each returned row. The process_result_row
function is implemented by the caller and should gather and store each returned row in an external data structure prior.
statement | reference to the precompiled tagged statement to execute |
in_bindings | input bindings holding values to substitue placeholders in the query. |
process_result_row | Pointer to the function to be invoked for each retrieved row. This function consumes the retrieved data from the result set. |
Definition at line 471 of file pgsql_connection.cc.
References isc_throw, isc::db::PgSqlTaggedStatement::text, and isc::Exception::what().
|
inline |
The recover connection.
This function starts the recover process of the connection.
Definition at line 406 of file pgsql_connection.h.
void isc::db::PgSqlConnection::startTransaction | ( | ) |
Starts new transaction.
This function begins a new transaction by sending the START TRANSACTION statement to the database. The transaction should be explicitly committed by calling commit()
or rolled back by calling rollback()
.
PostgreSQL does not support nested transactions directly. Issuing a START TRANSACTION while already in a transaction will cause a warning to be emitted but otherwise does not alter the state of the current transaction. In other words, the transaction will still end upon the next COMMIT or ROLLBACK statement.
Therefore, this function checks if a transaction has already started and does not start a new transaction. However, it increments a transaction reference counter which is later decremented when commit()
or rollback()
is called. When this mechanism is used properly, it guarantees that nested transactions are not attempted, thus avoiding unexpected commits or rollbacks of the pending transaction.
Definition at line 348 of file pgsql_connection.cc.
References isc::db::DB_DBG_TRACE_DETAIL, isc_throw, and isc::db::PGSQL_START_TRANSACTION.
Referenced by isc::db::PgSqlTransaction::PgSqlTransaction().
uint64_t isc::db::PgSqlConnection::updateDeleteQuery | ( | PgSqlTaggedStatement & | statement, |
const PsqlBindArray & | in_bindings | ||
) |
Executes UPDATE or DELETE prepared statement and returns the number of affected rows.
The statement
must refer to an existing prepared statement associated with the connection. The in_bindings
size must match the number of placeholders in the prepared statement.
statement | reference to the precompiled tagged statement to execute |
in_bindings | Input bindings holding values to substitute placeholders in the query. |
Definition at line 499 of file pgsql_connection.cc.
References isc_throw.
PgSqlHolder isc::db::PgSqlConnection::conn_ |
PgSql connection handle.
This field is public, because it is used heavily from PgSqlLeaseMgr and from PgSqlHostDataSource.
Definition at line 496 of file pgsql_connection.h.
Referenced by getVersion().
|
static |
Define the PgSql error state for a duplicate key error.
Definition at line 201 of file pgsql_connection.h.
Referenced by isc::dhcp::PgSqlHostDataSourceImpl::addStatement(), and isc::dhcp::PgSqlLeaseMgr::getDBVersion().
isc::asiolink::IOServicePtr isc::db::PgSqlConnection::io_service_ |
IOService object, used for all ASIO operations.
Definition at line 544 of file pgsql_connection.h.
IOServiceAccessorPtr isc::db::PgSqlConnection::io_service_accessor_ |
Accessor function which returns the IOService that can be used to recover the connection.
This accessor is used to lazy retrieve the IOService when the connection is lost. It is useful to retrieve it at a later time to support hook libraries which create managers on load and set IOService later on by using the dhcp4_srv_configured and dhcp6_srv_configured hooks.
Definition at line 541 of file pgsql_connection.h.
|
static |
Define the PgSql error state for a null foreign key error.
Definition at line 203 of file pgsql_connection.h.
int isc::db::PgSqlConnection::transaction_ref_count_ |
Reference counter for transactions.
It precludes starting and committing nested transactions. PostgreSQL logs but ignores START TRANSACTIONs (or BEGINs) issued from within an ongoing transaction. We do not want to start new transactions when one is already in progress.
Definition at line 552 of file pgsql_connection.h.
|
static |
Emit the TLS support warning only once.
Definition at line 209 of file pgsql_connection.h.
Referenced by isc::dhcp::PgSqlHostDataSourceImpl::PgSqlHostDataSourceImpl(), and isc::dhcp::PgSqlLeaseMgr::PgSqlLeaseMgr().