24 #define MAKE_SQLSTATE(ch1,ch2,ch3,ch4,ch5) {ch1,ch2,ch3,ch4,ch5} 26 #define PGSQL_STATECODE_LEN 5 27 #include <utils/errcodes.h> 41 const char PgSqlConnection::DUPLICATE_KEY[] = ERRCODE_UNIQUE_VIOLATION;
42 const char PgSqlConnection::NULL_KEY[] = ERRCODE_NOT_NULL_VIOLATION;
44 bool PgSqlConnection::warned_about_tls =
false;
46 PgSqlResult::PgSqlResult(PGresult *result)
47 : result_(result), rows_(0), cols_(0) {
56 rows_ = PQntuples(result);
57 cols_ = PQnfields(result);
63 if (row < 0 || row >= rows_) {
65 <<
", out of range: 0.." << rows_);
77 if (col < 0 || col >= cols_) {
79 <<
", out of range: 0.." << cols_);
91 const char* label = NULL;
94 label = PQfname(result_, col);
96 std::ostringstream os;
97 os <<
"Unknown column:" << col;
105 : conn_(conn), committed_(false) {
125 if (PQstatus(conn_) == CONNECTION_OK) {
127 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
130 .
arg(PQerrorMessage(conn_));
136 std::pair<uint32_t, uint32_t>
144 const char* version_sql =
"SELECT version, minor FROM schema_version;";
146 if (PQresultStatus(r) != PGRES_TUPLES_OK) {
148 << version_sql <<
", reason: " << PQerrorMessage(conn.
conn_));
157 return (make_pair(version, minor));
165 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
167 <<
" name: " << statement.
name 168 <<
", reason: " << PQerrorMessage(conn_)
169 <<
", text: " << statement.
text);
178 tagged_statement != end_statement; ++tagged_statement) {
179 prepareStatement(*tagged_statement);
185 string dbconnparameters;
186 string shost =
"localhost";
188 shost = getParameter(
"host");
193 dbconnparameters +=
"host = '" + shost +
"'" ;
197 sport = getParameter(
"port");
203 if (sport.size() > 0) {
204 unsigned int port = 0;
208 port = boost::lexical_cast<
unsigned int>(sport);
217 if (port > numeric_limits<uint16_t>::max()) {
223 std::ostringstream oss;
225 dbconnparameters +=
" port = " + oss.str();
231 suser = getParameter(
"user");
232 dbconnparameters +=
" user = '" + suser +
"'";
239 spassword = getParameter(
"password");
240 dbconnparameters +=
" password = '" + spassword +
"'";
247 sname = getParameter(
"name");
248 dbconnparameters +=
" dbname = '" + sname +
"'";
257 stimeout = getParameter(
"connect-timeout");
263 if (stimeout.size() > 0) {
267 connect_timeout = boost::lexical_cast<
unsigned int>(stimeout);
284 if ((connect_timeout == 0) ||
285 (connect_timeout > numeric_limits<int>::max())) {
287 stimeout <<
") must be an integer greater than 0");
291 std::ostringstream oss;
292 oss << connect_timeout;
293 dbconnparameters +=
" connect_timeout = " + oss.str();
297 PGconn* new_conn = PQconnectdb(dbconnparameters.c_str());
302 if (PQstatus(new_conn) != CONNECTION_OK) {
305 std::string error_message = PQerrorMessage(new_conn);
311 conn_.setConnection(new_conn);
316 const char* sqlstate = PQresultErrorField(r, PG_DIAG_SQLSTATE);
318 return ((sqlstate != NULL) &&
325 int s = PQresultStatus(r);
326 if (s != PGRES_COMMAND_OK && s != PGRES_TUPLES_OK) {
331 const char* sqlstate = PQresultErrorField(r, PG_DIAG_SQLSTATE);
332 if ((sqlstate == NULL) ||
333 ((memcmp(sqlstate,
"08", 2) == 0) ||
334 (memcmp(sqlstate,
"53", 2) == 0) ||
335 (memcmp(sqlstate,
"54", 2) == 0) ||
336 (memcmp(sqlstate,
"57", 2) == 0) ||
337 (memcmp(sqlstate,
"58", 2) == 0))) {
340 .
arg(PQerrorMessage(conn_))
341 .
arg(sqlstate ? sqlstate :
"<sqlstate null>");
347 startRecoverDbConnection();
352 "fatal database error or connectivity lost");
356 if (compareError(r, PgSqlConnection::DUPLICATE_KEY)) {
358 <<
", reason: " << PQerrorMessage(conn_));
362 if (compareError(r, PgSqlConnection::NULL_KEY)) {
364 <<
", reason: " << PQerrorMessage(conn_));
368 const char* error_message = PQerrorMessage(conn_);
370 << statement.
name <<
", status: " << s
371 <<
"sqlstate:[ " << (sqlstate ? sqlstate :
"<null>")
372 <<
" ], reason: " << error_message);
379 if (++transaction_ref_count_ > 1) {
386 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
387 const char* error_message = PQerrorMessage(conn_);
395 return (transaction_ref_count_ > 0);
400 if (transaction_ref_count_ <= 0) {
405 if (--transaction_ref_count_ > 0) {
412 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
413 const char* error_message = PQerrorMessage(conn_);
420 if (transaction_ref_count_ <= 0) {
425 if (--transaction_ref_count_ > 0) {
432 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
433 const char* error_message = PQerrorMessage(conn_);
440 if (transaction_ref_count_ <= 0) {
445 std::string sql(
"SAVEPOINT " + name);
451 if (transaction_ref_count_ <= 0) {
455 std::string sql(
"ROLLBACK TO SAVEPOINT " + name);
466 checkStatementError(r, statement);
476 <<
" expected: " << statement.
nbparams 477 <<
" parameters, given: " << in_bindings.
size()
478 <<
", statement: " << statement.
name 479 <<
", SQL: " << statement.
text);
482 const char*
const* values = 0;
483 const int* lengths = 0;
484 const int* formats = 0;
486 values =
static_cast<const char* const*
>(&in_bindings.
values_[0]);
487 lengths =
static_cast<const int *
>(&in_bindings.
lengths_[0]);
488 formats =
static_cast<const int *
>(&in_bindings.
formats_[0]);
493 values, lengths, formats, 0)));
495 checkStatementError(*result_set, statement);
504 PgSqlResultPtr result_set = executePreparedStatement(statement, in_bindings);
508 int rows = result_set->getRows();
509 for (
int row = 0; row < rows; ++row) {
511 process_result_row(*result_set, row);
512 }
catch (
const std::exception& ex) {
515 statement.
text <<
">");
524 PgSqlResultPtr result_set = executePreparedStatement(statement, in_bindings);
531 PgSqlResultPtr result_set = executePreparedStatement(statement, in_bindings);
533 return (boost::lexical_cast<int>(PQcmdTuples(*result_set)));
We want to reuse the database backend connection and exchange code for other uses, in particular for hook libraries.
RAII wrapper for PostgreSQL Result sets.
~PgSqlTransaction()
Destructor.
const Oid types[PGSQL_MAX_PARAMETERS_IN_QUERY]
OID types.
void startTransaction()
Starts new transaction.
void rollbackToSavepoint(const std::string &name)
Rollbacks to the given savepoint.
void commit()
Commits transaction.
const int PGSQL_DEFAULT_CONNECTION_TIMEOUT
std::vector< int > formats_
Vector of "format" for each value.
boost::shared_ptr< PgSqlResult > PgSqlResultPtr
std::vector< int > lengths_
Vector of data lengths for each value.
bool compareError(const PgSqlResult &r, const char *error_state)
Checks a result set's SQL state against an error state.
void insertQuery(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings)
Executes INSERT prepared statement.
void selectQuery(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings, ConsumeResultRowFun process_result_row)
Executes SELECT query using prepared statement.
void rowCheck(int row) const
Determines if a row index is valid.
std::string getColumnLabel(const int col) const
Fetches the name of the column in a result set.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
Exception thrown on failure to open database.
void executeSQL(const std::string &sql)
Executes the an SQL statement.
void commit()
Commits current transaction.
std::vector< const char * > values_
Vector of pointers to the data values.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
void prepareStatements(const PgSqlTaggedStatement *start_statement, const PgSqlTaggedStatement *end_statement)
Prepare statements.
Exception thrown if name of database is not specified.
void createSavepoint(const std::string &name)
Creates a savepoint within the current transaction.
void checkStatementError(const PgSqlResult &r, PgSqlTaggedStatement &statement)
Checks result of the r object.
A generic exception that is thrown when an unexpected error condition occurs.
bool isTransactionStarted() const
Checks if there is a transaction in progress.
void rollback()
Rollbacks current transaction.
PgSqlTransaction(PgSqlConnection &conn)
Constructor.
int version()
returns Kea hooks version.
static void getColumnValue(const PgSqlResult &r, const int row, const size_t col, std::string &value)
Fetches text column value as a string.
Common PgSql Connector Pool.
virtual ~PgSqlConnection()
Destructor.
void prepareStatement(const PgSqlTaggedStatement &statement)
Prepare Single Statement.
const int DB_DBG_TRACE_DETAIL
Database logging levels.
Defines the logger used by the top-level component of kea-lfc.
Define a PostgreSQL statement.
size_t size() const
Fetches the number of entries in the array.
uint64_t updateDeleteQuery(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings)
Executes UPDATE or DELETE prepared statement and returns the number of affected rows.
DB_LOG & arg(T first, Args... args)
Pass parameters to replace logger placeholders.
#define PGSQL_STATECODE_LEN
void rowColCheck(int row, int col) const
Determines if both a row and column index are valid.
A generic exception that is thrown if a function is called in a prohibited way.
const char * text
Text representation of the actual query.
void colCheck(int col) const
Determines if a column index is valid.
~PgSqlResult()
Destructor.
PgSqlResultPtr executePreparedStatement(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings=PsqlBindArray())
Executes a prepared SQL statement.
Exception thrown when a specific connection has been rendered unusable either through loss of connect...
void openDatabase()
Open Database.
const char * name
Short name of the query.
static std::pair< uint32_t, uint32_t > getVersion(const ParameterMap ¶meters)
Get the schema version.
const size_t OID_NONE
Constants for PostgreSQL data types These are defined by PostgreSQL in <catalog/pg_type.h>, but including this file is extraordinarily convoluted, so we'll use these to fill-in.
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
PgSqlHolder conn_
PgSql connection handle.
std::function< void(PgSqlResult &, int)> ConsumeResultRowFun
Function invoked to process fetched row.
Exception thrown on failure to execute a database function.
Key is NULL but was specified NOT NULL.
int nbparams
Number of parameters for a given query.
Database duplicate entry error.