Kea  2.5.2
pgsql_connection.h
Go to the documentation of this file.
1 // Copyright (C) 2016-2023 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 
9 #include <asiolink/io_service.h>
10 #include <pgsql/pgsql_exchange.h>
11 
12 #include <boost/scoped_ptr.hpp>
13 
14 #include <vector>
15 #include <stdint.h>
16 
17 namespace isc {
18 namespace db {
19 
21 const uint32_t PGSQL_SCHEMA_VERSION_MAJOR = 19;
22 const 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.
28 const size_t PGSQL_MAX_PARAMETERS_IN_QUERY = 128;
29 
36  int nbparams;
37 
44 
46  const char* name;
47 
49  const char* text;
50 };
51 
57 const size_t OID_NONE = 0; // PostgreSQL infers proper type
58 const size_t OID_BOOL = 16;
59 const size_t OID_BYTEA = 17;
60 const size_t OID_INT8 = 20; // 8 byte int
61 const size_t OID_INT2 = 21; // 2 byte int
62 const size_t OID_INT4 = 23; // 4 byte int
63 const size_t OID_TEXT = 25;
64 const size_t OID_VARCHAR = 1043;
65 const size_t OID_TIMESTAMP = 1114;
67 
79 class PgSqlHolder : public boost::noncopyable {
80 public:
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 
126 private:
127  PGconn* pgconn_;
128 };
129 
131 class PgSqlConnection;
132 
150 class PgSqlTransaction : public boost::noncopyable {
151 public:
152 
162 
170 
177  void commit();
178 
179 private:
180 
182  PgSqlConnection& conn_;
183 
188  bool committed_;
189 };
190 
199 public:
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 
239  static std::pair<uint32_t, uint32_t>
240  getVersion(const ParameterMap& parameters);
241 
251  void prepareStatement(const PgSqlTaggedStatement& statement);
252 
265  void prepareStatements(const PgSqlTaggedStatement* start_statement,
266  const PgSqlTaggedStatement* end_statement);
267 
275  std::string getConnParameters();
276 
277 private:
278 
293  std::string getConnParametersInternal(bool logging);
294 
295 public:
296 
305  void openDatabase();
306 
307 private:
308 
319  void openDatabaseInternal(bool logging);
320 
321 public:
322 
341  void startTransaction();
342 
346  bool isTransactionStarted() const;
347 
358  void commit();
359 
370  void rollback();
371 
380  void createSavepoint(const std::string& name);
381 
391  void rollbackToSavepoint(const std::string& name);
392 
404  void executeSQL(const std::string& sql);
405 
413  bool compareError(const PgSqlResult& r, const char* error_state);
414 
434  void checkStatementError(const PgSqlResult& r,
435  PgSqlTaggedStatement& statement);
436 
443  if (callback_) {
445  io_service_ = (*io_service_accessor_)();
446  io_service_accessor_.reset();
447  }
448 
449  if (io_service_) {
450  io_service_->post(std::bind(callback_, reconnectCtl()));
451  }
452  }
453  }
454 
473  const PsqlBindArray& in_bindings
474  = PsqlBindArray());
475 
493  void selectQuery(PgSqlTaggedStatement& statement,
494  const PsqlBindArray& in_bindings,
495  ConsumeResultRowFun process_result_row);
496 
509  void insertQuery(PgSqlTaggedStatement& statement,
510  const PsqlBindArray& in_bindings);
511 
512 
525  uint64_t updateDeleteQuery(PgSqlTaggedStatement& statement,
526  const PsqlBindArray& in_bindings);
527 
533 
538  operator PGconn*() const {
539  return (conn_);
540  }
541 
545  operator bool() const {
546  return (conn_);
547  }
548 
549 private:
550 
565  template<typename T>
566  void setIntParameterValue(const std::string& name, int64_t min, int64_t max, T& value);
567 
568 public:
569 
578 
581 
589 };
590 
592 typedef boost::shared_ptr<PgSqlConnection> PgSqlConnectionPtr;
593 
594 } // end of isc::db namespace
595 } // end of isc namespace
596 
597 #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.
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 &parameters)
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 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.
~PgSqlHolder()
Destructor.
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.