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>
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) {
136std::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) {
185 string dbconnparameters;
186 string shost =
"localhost";
193 dbconnparameters +=
"host = '" + shost +
"'" ;
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();
232 dbconnparameters +=
" user = '" + suser +
"'";
240 dbconnparameters +=
" password = '" + spassword +
"'";
248 dbconnparameters +=
" dbname = '" + sname +
"'";
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);
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))) {
341 .
arg(sqlstate ? sqlstate :
"<sqlstate null>");
352 "fatal database error or connectivity lost");
358 <<
", reason: " << PQerrorMessage(
conn_));
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);
386 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
387 const char* error_message = PQerrorMessage(
conn_);
412 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
413 const char* error_message = PQerrorMessage(
conn_);
432 if (PQresultStatus(r) != PGRES_COMMAND_OK) {
433 const char* error_message = PQerrorMessage(
conn_);
445 std::string sql(
"SAVEPOINT " + name);
455 std::string sql(
"ROLLBACK TO SAVEPOINT " + name);
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)));
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 <<
">");
533 return (boost::lexical_cast<int>(PQcmdTuples(*result_set)));
int version()
returns Kea hooks version.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown if a function is called in a prohibited way.
A generic exception that is thrown when an unexpected error condition occurs.
std::string getParameter(const std::string &name) const
Returns value of a connection parameter.
void markUnusable()
Sets the unusable flag to true.
void checkUnusable()
Throws an exception if the connection is not usable.
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
Exception thrown when a specific connection has been rendered unusable either through loss of connect...
Exception thrown on failure to open database.
Exception thrown on failure to execute a database function.
Database duplicate entry error.
Exception thrown if name of database is not specified.
Key is NULL but was specified NOT NULL.
Common PgSql Connector Pool.
static bool warned_about_tls
Emit the TLS support warning only once.
void startTransaction()
Starts new transaction.
void rollback()
Rollbacks current transaction.
void createSavepoint(const std::string &name)
Creates a savepoint within the current transaction.
uint64_t updateDeleteQuery(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings)
Executes UPDATE or DELETE prepared statement and returns the number of affected rows.
int transaction_ref_count_
Reference counter for transactions.
void selectQuery(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings, ConsumeResultRowFun process_result_row)
Executes SELECT query using prepared statement.
bool compareError(const PgSqlResult &r, const char *error_state)
Checks a result set's SQL state against an error state.
static const char NULL_KEY[]
Define the PgSql error state for a null foreign key error.
std::function< void(PgSqlResult &, int)> ConsumeResultRowFun
Function invoked to process fetched row.
void prepareStatement(const PgSqlTaggedStatement &statement)
Prepare Single Statement.
static const char DUPLICATE_KEY[]
Define the PgSql error state for a duplicate key error.
PgSqlResultPtr executePreparedStatement(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings=PsqlBindArray())
Executes a prepared SQL statement.
bool isTransactionStarted() const
Checks if there is a transaction in progress.
static std::pair< uint32_t, uint32_t > getVersion(const ParameterMap ¶meters)
Get the schema version.
PgSqlHolder conn_
PgSql connection handle.
void rollbackToSavepoint(const std::string &name)
Rollbacks to the given savepoint.
void startRecoverDbConnection()
The recover connection.
void insertQuery(PgSqlTaggedStatement &statement, const PsqlBindArray &in_bindings)
Executes INSERT prepared statement.
void commit()
Commits current transaction.
void executeSQL(const std::string &sql)
Executes the an SQL statement.
virtual ~PgSqlConnection()
Destructor.
void checkStatementError(const PgSqlResult &r, PgSqlTaggedStatement &statement)
Checks result of the r object.
void prepareStatements(const PgSqlTaggedStatement *start_statement, const PgSqlTaggedStatement *end_statement)
Prepare statements.
void openDatabase()
Open Database.
static void getColumnValue(const PgSqlResult &r, const int row, const size_t col, std::string &value)
Fetches text column value as a string.
void setConnection(PGconn *connection)
Sets the connection to the value given.
RAII wrapper for PostgreSQL Result sets.
void colCheck(int col) const
Determines if a column index is valid.
void rowCheck(int row) const
Determines if a row index is valid.
void rowColCheck(int row, int col) const
Determines if both a row and column index are valid.
~PgSqlResult()
Destructor.
std::string getColumnLabel(const int col) const
Fetches the name of the column in a result set.
PgSqlResult(PGresult *result)
Constructor.
PgSqlTransaction(PgSqlConnection &conn)
Constructor.
void commit()
Commits transaction.
~PgSqlTransaction()
Destructor.
We want to reuse the database backend connection and exchange code for other uses,...
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
const int DB_DBG_TRACE_DETAIL
Database logging levels.
const int PGSQL_DEFAULT_CONNECTION_TIMEOUT
@ PGSQL_START_TRANSACTION
boost::shared_ptr< PgSqlResult > PgSqlResultPtr
const size_t OID_NONE
Constants for PostgreSQL data types These are defined by PostgreSQL in <catalog/pg_type....
Defines the logger used by the top-level component of kea-lfc.
#define PGSQL_STATECODE_LEN
DB_LOG & arg(T first, Args... args)
Pass parameters to replace logger placeholders.
Define a PostgreSQL statement.
int nbparams
Number of parameters for a given query.
const char * text
Text representation of the actual query.
const char * name
Short name of the query.
const Oid types[PGSQL_MAX_PARAMETERS_IN_QUERY]
OID types.
std::vector< const char * > values_
Vector of pointers to the data values.
std::vector< int > formats_
Vector of "format" for each value.
size_t size() const
Fetches the number of entries in the array.
std::vector< int > lengths_
Vector of data lengths for each value.