Kea 3.2.0-git
pgsql_connection.h
Go to the documentation of this file.
1// Copyright (C) 2016-2026 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6#ifndef PGSQL_CONNECTION_H
7#define PGSQL_CONNECTION_H
8
11
12#include <boost/scoped_ptr.hpp>
13
14#include <vector>
15#include <stdint.h>
16
17namespace isc {
18namespace db {
19
21const uint32_t PGSQL_SCHEMA_VERSION_MAJOR = 34;
22const uint32_t PGSQL_SCHEMA_VERSION_MINOR = 0;
23
24// Maximum number of parameters that can be used a statement
25// @todo This allows us to use an initializer list (since we can't
26// require C++11). It's unlikely we'd go past this many a single
27// statement.
29
37
44
46 const char* name;
47
49 const char* text;
50};
51
57const size_t OID_NONE = 0; // PostgreSQL infers proper type
58const size_t OID_BOOL = 16;
59const size_t OID_BYTEA = 17;
60const size_t OID_INT8 = 20; // 8 byte int
61const size_t OID_INT2 = 21; // 2 byte int
62const size_t OID_INT4 = 23; // 4 byte int
63const size_t OID_TEXT = 25;
64const size_t OID_VARCHAR = 1043;
65const size_t OID_TIMESTAMP = 1114;
67
79class PgSqlHolder : public boost::noncopyable {
80public:
81
86 PgSqlHolder() : pgconn_(NULL) {
87 }
88
93 if (pgconn_ != NULL) {
94 PQfinish(pgconn_);
95 }
96 }
97
101 void setConnection(PGconn* connection) {
102 if (pgconn_ != NULL) {
103 // Already set? Release the current connection first.
104 // Maybe this should be an error instead?
105 PQfinish(pgconn_);
106 }
107
108 pgconn_ = connection;
109 }
110
115 operator PGconn*() const {
116 return (pgconn_);
117 }
118
122 operator bool() const {
123 return (pgconn_);
124 }
125
126private:
127 PGconn* pgconn_;
128};
129
131class PgSqlConnection;
132
150class PgSqlTransaction : public boost::noncopyable {
151public:
152
162
170
177 void commit();
178
179private:
180
182 PgSqlConnection& conn_;
183
188 bool committed_;
189};
190
192typedef boost::scoped_ptr<PgSqlTransaction> ScopedPgSqlTransactionPtr;
193
202public:
204 static const char DUPLICATE_KEY[];
206 static const char NULL_KEY[];
207
209 typedef std::function<void(PgSqlResult&, int)> ConsumeResultRowFun;
210
212 static bool warned_about_tls;
213
221 PgSqlConnection(const ParameterMap& parameters,
223 DbCallback callback = DbCallback())
224 : DatabaseConnection(parameters, callback),
225 io_service_accessor_(io_accessor), io_service_(),
227 }
228
230 virtual ~PgSqlConnection();
231
238 static std::tuple<std::vector<std::string>, std::vector<std::string>>
239 toKeaAdminParameters(ParameterMap const& params);
240
255 static std::pair<uint32_t, uint32_t>
256 getVersion(const ParameterMap& parameters,
258 const DbCallback& cb = DbCallback(),
259 const std::string& timer_name = std::string(),
260 unsigned int id = 0);
261
274 static void
275 ensureSchemaVersion(const ParameterMap& parameters,
276 const DbCallback& cb = DbCallback(),
277 const std::string& timer_name = std::string());
278
285 static void
286 initializeSchema(const ParameterMap& parameters);
287
297 void prepareStatement(const PgSqlTaggedStatement& statement);
298
311 void prepareStatements(const PgSqlTaggedStatement* start_statement,
312 const PgSqlTaggedStatement* end_statement);
313
321 std::string getConnParameters();
322
323private:
324
339 std::string getConnParametersInternal(bool logging);
340
341public:
342
351 void openDatabase();
352
353private:
354
365 void openDatabaseInternal(bool logging);
366
367public:
368
387 void startTransaction();
388
392 bool isTransactionStarted() const;
393
404 void commit();
405
416 void rollback();
417
426 void createSavepoint(const std::string& name);
427
437 void rollbackToSavepoint(const std::string& name);
438
450 void executeSQL(const std::string& sql);
451
459 bool compareError(const PgSqlResult& r, const char* error_state);
460
480 void checkStatementError(const PgSqlResult& r,
481 PgSqlTaggedStatement& statement);
482
489 if (callback_) {
491 io_service_ = (*io_service_accessor_)();
492 io_service_accessor_.reset();
493 }
494
495 if (io_service_) {
496 io_service_->post(std::bind(callback_, reconnectCtl()));
497 }
498 }
499 }
500
519 const PsqlBindArray& in_bindings
520 = PsqlBindArray());
521
539 void selectQuery(PgSqlTaggedStatement& statement,
540 const PsqlBindArray& in_bindings,
541 ConsumeResultRowFun process_result_row);
542
555 void insertQuery(PgSqlTaggedStatement& statement,
556 const PsqlBindArray& in_bindings);
557
558
571 uint64_t updateDeleteQuery(PgSqlTaggedStatement& statement,
572 const PsqlBindArray& in_bindings);
573
579
584 operator PGconn*() const {
585 return (conn_);
586 }
587
591 operator bool() const {
592 return (conn_);
593 }
594
595private:
596
611 template<typename T>
612 void setIntParameterValue(const std::string& name, int64_t min, int64_t max, T& value);
613
614public:
615
624
627
635
638 static std::string KEA_ADMIN_;
639};
640
642typedef boost::shared_ptr<PgSqlConnection> PgSqlConnectionPtr;
643
644} // end of isc::db namespace
645} // end of isc namespace
646
647#endif // PGSQL_CONNECTION_H
Common database connection class.
util::ReconnectCtlPtr reconnectCtl()
The reconnect settings.
DatabaseConnection(const ParameterMap &parameters, DbCallback callback=DbCallback())
Constructor.
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
DbCallback callback_
The callback used to recover the connection.
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.
std::string getConnParameters()
Creates connection string from specified parameters.
IOServiceAccessorPtr io_service_accessor_
Accessor function which returns the IOService that can be used to recover the connection.
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.
static void ensureSchemaVersion(const ParameterMap &parameters, const DbCallback &cb=DbCallback(), const std::string &timer_name=std::string())
Retrieve schema version, validate it against the hardcoded version, and attempt to initialize the sch...
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 &parameters, const IOServiceAccessorPtr &ac=IOServiceAccessorPtr(), const DbCallback &cb=DbCallback(), const std::string &timer_name=std::string(), unsigned int id=0)
Get the schema version.
static std::string KEA_ADMIN_
Holds location to kea-admin.
PgSqlHolder conn_
PgSql connection handle.
void rollbackToSavepoint(const std::string &name)
Rollbacks to the given savepoint.
static std::tuple< std::vector< std::string >, std::vector< std::string > > toKeaAdminParameters(ParameterMap const &params)
Convert PostgreSQL library parameters to kea-admin parameters.
static void initializeSchema(const ParameterMap &parameters)
Initialize schema.
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 with logging.
PgSqlConnection(const ParameterMap &parameters, IOServiceAccessorPtr io_accessor=IOServiceAccessorPtr(), DbCallback callback=DbCallback())
Constructor.
isc::asiolink::IOServicePtr io_service_
IOService object, used for all ASIO operations.
Postgresql connection handle Holder.
void setConnection(PGconn *connection)
Sets the connection to the value given.
PgSqlHolder()
Constructor.
RAII wrapper for PostgreSQL Result sets.
PgSqlTransaction(PgSqlConnection &conn)
Constructor.
void commit()
Commits transaction.
const size_t OID_INT4
const size_t OID_INT2
boost::shared_ptr< PgSqlResult > PgSqlResultPtr
boost::shared_ptr< IOServiceAccessor > IOServiceAccessorPtr
Pointer to an instance of IOServiceAccessor.
const size_t PGSQL_MAX_PARAMETERS_IN_QUERY
const size_t OID_VARCHAR
const size_t OID_NONE
Constants for PostgreSQL data types These are defined by PostgreSQL in <catalog/pg_type....
const size_t OID_TIMESTAMP
const size_t OID_TEXT
const size_t OID_BOOL
const uint32_t PGSQL_SCHEMA_VERSION_MINOR
boost::shared_ptr< PgSqlConnection > PgSqlConnectionPtr
Defines a pointer to a PgSqlConnection.
const size_t OID_INT8
const size_t OID_BYTEA
std::function< bool(util::ReconnectCtlPtr db_reconnect_ctl)> DbCallback
Defines a callback prototype for propagating events upward.
const uint32_t PGSQL_SCHEMA_VERSION_MAJOR
Define the PostgreSQL backend version.
boost::scoped_ptr< PgSqlTransaction > ScopedPgSqlTransactionPtr
Defines a scoped pointer to a transaction.
Defines the logger used by the top-level component of kea-lfc.
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.