Kea 2.7.5
pgsql_connection.h
Go to the documentation of this file.
1// Copyright (C) 2016-2024 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 = 26;
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
199public:
201 static const char DUPLICATE_KEY[];
203 static const char NULL_KEY[];
204
206 typedef std::function<void(PgSqlResult&, int)> ConsumeResultRowFun;
207
209 static bool warned_about_tls;
210
218 PgSqlConnection(const ParameterMap& parameters,
220 DbCallback callback = DbCallback())
221 : DatabaseConnection(parameters, callback),
222 io_service_accessor_(io_accessor), io_service_(),
224 }
225
227 virtual ~PgSqlConnection();
228
235 static std::tuple<std::vector<std::string>, std::vector<std::string>>
236 toKeaAdminParameters(ParameterMap const& params);
237
251 static std::pair<uint32_t, uint32_t>
252 getVersion(const ParameterMap& parameters,
254 const DbCallback& cb = DbCallback(),
255 const std::string& timer_name = std::string());
256
269 static void
270 ensureSchemaVersion(const ParameterMap& parameters,
271 const DbCallback& cb = DbCallback(),
272 const std::string& timer_name = std::string());
273
280 static void
281 initializeSchema(const ParameterMap& parameters);
282
292 void prepareStatement(const PgSqlTaggedStatement& statement);
293
306 void prepareStatements(const PgSqlTaggedStatement* start_statement,
307 const PgSqlTaggedStatement* end_statement);
308
316 std::string getConnParameters();
317
318private:
319
334 std::string getConnParametersInternal(bool logging);
335
336public:
337
346 void openDatabase();
347
348private:
349
360 void openDatabaseInternal(bool logging);
361
362public:
363
382 void startTransaction();
383
387 bool isTransactionStarted() const;
388
399 void commit();
400
411 void rollback();
412
421 void createSavepoint(const std::string& name);
422
432 void rollbackToSavepoint(const std::string& name);
433
445 void executeSQL(const std::string& sql);
446
454 bool compareError(const PgSqlResult& r, const char* error_state);
455
475 void checkStatementError(const PgSqlResult& r,
476 PgSqlTaggedStatement& statement);
477
484 if (callback_) {
486 io_service_ = (*io_service_accessor_)();
487 io_service_accessor_.reset();
488 }
489
490 if (io_service_) {
491 io_service_->post(std::bind(callback_, reconnectCtl()));
492 }
493 }
494 }
495
514 const PsqlBindArray& in_bindings
515 = PsqlBindArray());
516
534 void selectQuery(PgSqlTaggedStatement& statement,
535 const PsqlBindArray& in_bindings,
536 ConsumeResultRowFun process_result_row);
537
550 void insertQuery(PgSqlTaggedStatement& statement,
551 const PsqlBindArray& in_bindings);
552
553
566 uint64_t updateDeleteQuery(PgSqlTaggedStatement& statement,
567 const PsqlBindArray& in_bindings);
568
574
579 operator PGconn*() const {
580 return (conn_);
581 }
582
586 operator bool() const {
587 return (conn_);
588 }
589
590private:
591
606 template<typename T>
607 void setIntParameterValue(const std::string& name, int64_t min, int64_t max, T& value);
608
609public:
610
619
622
630
633 static std::string KEA_ADMIN_;
634};
635
637typedef boost::shared_ptr<PgSqlConnection> PgSqlConnectionPtr;
638
639} // end of isc::db namespace
640} // end of isc namespace
641
642#endif // PGSQL_CONNECTION_H
Common database connection class.
util::ReconnectCtlPtr reconnectCtl()
The reconnect settings.
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.
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::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.
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())
Get the schema version.
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.
std::function< void(PgSqlResult &, int) ConsumeResultRowFun)
Function invoked to process fetched row.
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.
RAII object representing a PostgreSQL transaction.
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.
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.