7#ifndef MYSQL_CONNECTION_H
8#define MYSQL_CONNECTION_H
17#include <boost/scoped_ptr.hpp>
19#include <mysqld_error.h>
63 (void) mysql_stmt_free_result(statement_);
67 MYSQL_STMT* statement_;
88template <
typename Fun,
typename... Args>
91 for (
unsigned count = 0; count < 5; ++count) {
92 status = fun(args...);
93 if (status != ER_LOCK_DEADLOCK) {
141 if (mysql_ == NULL) {
150 if (mysql_ != NULL) {
159 operator MYSQL*()
const {
172class MySqlConnection;
264 static std::vector<std::string>
280 static std::pair<uint32_t, uint32_t>
284 const std::string& timer_name = std::string());
301 const std::string& timer_name = std::string());
353 template<
typename StatementIndex>
355 if (statements_[index]->mysql == 0) {
357 "MySQL pointer for the prepared statement is NULL as a result of connectivity loss");
359 return (statements_[index]);
429 uint32_t valid_lifetime, time_t& cltt);
479 template<
typename StatementIndex>
486 std::vector<MYSQL_BIND> in_bind_vec;
488 in_bind_vec.push_back(in_binding->getMySqlBinding());
492 if (!in_bind_vec.empty()) {
495 in_bind_vec.empty() ? 0 : &in_bind_vec[0]);
496 checkError(status, index,
"unable to bind parameters for select");
500 std::vector<MYSQL_BIND> out_bind_vec;
502 out_bind_vec.push_back(out_binding->getMySqlBinding());
504 if (!out_bind_vec.empty()) {
505 status = mysql_stmt_bind_result(
getStatement(index), &out_bind_vec[0]);
506 checkError(status, index,
"unable to bind result parameters for select");
511 checkError(status, index,
"unable to execute");
514 checkError(status, index,
"unable to set up for storing all results");
518 while ((status = mysql_stmt_fetch(
getStatement(index))) ==
523 process_result(out_bindings);
525 }
catch (
const std::exception& ex) {
536 checkError(status, index,
"unable to fetch results");
538 }
else if (status == MYSQL_DATA_TRUNCATED) {
541 <<
" returned truncated data");
559 template<
typename StatementIndex>
563 std::vector<MYSQL_BIND> in_bind_vec;
565 in_bind_vec.push_back(in_binding->getMySqlBinding());
570 in_bind_vec.empty() ? 0 : &in_bind_vec[0]);
571 checkError(status, index,
"unable to bind parameters");
578 if (mysql_errno(
mysql_) == ER_DUP_ENTRY) {
582 if (mysql_errno(
mysql_) == ER_BAD_NULL_ERROR) {
585 checkError(status, index,
"unable to execute");
603 template<
typename StatementIndex>
607 std::vector<MYSQL_BIND> in_bind_vec;
609 in_bind_vec.push_back(in_binding->getMySqlBinding());
614 in_bind_vec.empty() ? 0 : &in_bind_vec[0]);
615 checkError(status, index,
"unable to bind parameters");
622 if ((mysql_errno(
mysql_) == ER_DUP_ENTRY)
623#ifdef ER_FOREIGN_DUPLICATE_KEY
624 || (mysql_errno(
mysql_) == ER_FOREIGN_DUPLICATE_KEY)
626#ifdef ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO
627 || (mysql_errno(
mysql_) == ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO)
629#ifdef ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO
630 || (mysql_errno(
mysql_) == ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO)
635 checkError(status, index,
"unable to execute");
639 return (
static_cast<uint64_t
>(mysql_stmt_affected_rows(
getStatement(index))));
694 template<
typename StatementIndex>
695 void checkError(
const int status,
const StatementIndex& index,
698 switch(mysql_errno(
mysql_)) {
705 case CR_SERVER_GONE_ERROR:
707 case CR_OUT_OF_MEMORY:
708 case CR_CONNECTION_ERROR: {
724 "fatal database error or connectivity lost");
731 << mysql_error(
mysql_) <<
" (error code "
732 << mysql_errno(
mysql_) <<
")");
766 const char* cipher = mysql_get_ssl_cipher(
mysql_);
767 return (cipher ? std::string(cipher) :
"");
787 void setIntParameterValue(
const std::string& name, int64_t min, int64_t max, T& value);
793 std::vector<MYSQL_STMT*> statements_;
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
Common database connection class.
util::ReconnectCtlPtr reconnectCtl()
The reconnect settings.
void markUnusable()
Sets the unusable flag to true.
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
void checkUnusable()
Throws an exception if the connection is not usable.
DbCallback callback_
The callback used to recover the connection.
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.
Common MySQL Connector Pool.
isc::asiolink::IOServicePtr io_service_
IOService object, used for all ASIO operations.
static std::string KEA_ADMIN_
Holds location to kea-admin.
std::function< void(MySqlBindingCollection &)> ConsumeResultFun
Function invoked to process fetched row.
MySqlHolder mysql_
MySQL connection handle.
void prepareStatement(uint32_t index, const char *text)
Prepare Single Statement.
bool isTransactionStarted() const
Checks if there is a transaction in progress.
std::vector< std::string > text_statements_
Raw text of statements.
void insertQuery(const StatementIndex &index, const MySqlBindingCollection &in_bindings)
Executes INSERT prepared statement.
bool tls_
TLS flag (true when TLS was required, false otherwise).
static void convertToDatabaseTime(const time_t input_time, MYSQL_TIME &output_time)
Convert time_t value to database time.
static std::pair< uint32_t, uint32_t > getVersion(const ParameterMap ¶meters, const IOServiceAccessorPtr &ac=IOServiceAccessorPtr(), const DbCallback &cb=DbCallback(), const std::string &timer_name=std::string())
Get the schema version.
IOServiceAccessorPtr io_service_accessor_
Accessor function which returns the IOService that can be used to recover the connection.
static void convertFromDatabaseTime(const MYSQL_TIME &expire, uint32_t valid_lifetime, time_t &cltt)
Convert Database Time to Lease Times.
void commit()
Commits current transaction.
MySqlConnection(const ParameterMap ¶meters, IOServiceAccessorPtr io_accessor=IOServiceAccessorPtr(), DbCallback callback=DbCallback())
Constructor.
void startRecoverDbConnection()
The recover connection.
static void initializeSchema(const ParameterMap ¶meters)
Initialize schema.
uint64_t updateDeleteQuery(const StatementIndex &index, const MySqlBindingCollection &in_bindings)
Executes UPDATE or DELETE prepared statement and returns the number of affected rows.
static std::vector< std::string > toKeaAdminParameters(ParameterMap const ¶ms)
Convert MySQL library parameters to kea-admin parameters.
void openDatabase()
Open Database.
std::string getTlsCipher()
Get the TLS cipher.
void prepareStatements(const TaggedStatement *start_statement, const TaggedStatement *end_statement)
Prepare statements.
int transaction_ref_count_
Reference counter for transactions.
void startTransaction()
Starts new transaction.
virtual ~MySqlConnection()
Destructor.
void checkError(const int status, const StatementIndex &index, const char *what)
Check Error and Throw Exception.
bool getTls() const
Get the TLS flag.
MYSQL_STMT * getStatement(StatementIndex index) const
Returns a prepared statement by an index.
void selectQuery(const StatementIndex &index, const MySqlBindingCollection &in_bindings, MySqlBindingCollection &out_bindings, ConsumeResultFun process_result)
Executes SELECT query using prepared statement.
void rollback()
Rollbacks current transaction.
static void ensureSchemaVersion(const ParameterMap ¶meters, 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...
Fetch and Release MySQL Results.
~MySqlFreeResult()
Destructor.
MySqlFreeResult(MYSQL_STMT *statement)
Constructor.
MySqlHolder()
Constructor.
~MySqlHolder()
Destructor.
RAII object representing MySQL transaction.
~MySqlTransaction()
Destructor.
void commit()
Commits transaction.
MySqlTransaction(MySqlConnection &conn)
Constructor.
Key is NULL but was specified NOT NULL.
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.
boost::shared_ptr< IOService > IOServicePtr
Defines a smart pointer to an IOService instance.
boost::shared_ptr< MySqlBinding > MySqlBindingPtr
Shared pointer to the Binding class.
boost::shared_ptr< IOServiceAccessor > IOServiceAccessorPtr
Pointer to an instance of IOServiceAccessor.
const int MLM_MYSQL_FETCH_FAILURE
MySQL fetch failure code.
int MysqlQuery(MYSQL *mysql, const char *stmt)
Execute a literal statement.
std::vector< MySqlBindingPtr > MySqlBindingCollection
Collection of bindings.
const int MLM_MYSQL_FETCH_SUCCESS
check for bool size
int retryOnDeadlock(Fun &fun, Args... args)
Retry on InnoDB deadlock.
std::function< bool(util::ReconnectCtlPtr db_reconnect_ctl)> DbCallback
Defines a callback prototype for propagating events upward.
int MysqlExecuteStatement(MYSQL_STMT *stmt)
Execute a prepared statement.
Defines the logger used by the top-level component of kea-lfc.
DB_LOG & arg(T first, Args... args)
Pass parameters to replace logger placeholders.
MySQL Selection Statements.