27 #include <gnc-locale-utils.h> 33 #include "gnc-dbisqlconnection.hpp" 37 #include "gnc-dbiproviderimpl.hpp" 39 static const unsigned int DBI_MAX_CONN_ATTEMPTS = 5;
40 const std::string lock_table =
"gnclock";
49 const char* to_sql()
const override;
58 GncDbiSqlStatement::to_sql()
const 65 const PairVec& col_values)
68 for (
auto colpair : col_values)
70 if (colpair != *col_values.begin())
72 if (colpair.second ==
"NULL")
73 m_sql += colpair.first +
" IS " + colpair.second;
75 m_sql += colpair.first +
" = " + colpair.second;
79 GncDbiSqlConnection::GncDbiSqlConnection (DbType type,
QofBackend* qbe,
81 m_qbe{qbe}, m_conn{conn},
82 m_provider{type == DbType::DBI_SQLITE ?
83 make_dbi_provider<DbType::DBI_SQLITE>() :
84 type == DbType::DBI_MYSQL ?
85 make_dbi_provider<DbType::DBI_MYSQL>() :
86 make_dbi_provider<DbType::DBI_PGSQL>()},
87 m_conn_ok{
true}, m_last_error{ERR_BACKEND_NO_ERR}, m_error_repeat{0},
88 m_retry{
false}, m_sql_savepoint{0}, m_readonly{
false}
93 throw std::runtime_error(
"Failed to lock database!");
94 if (!check_and_rollback_failed_save())
97 throw std::runtime_error(
"A failed safe-save was detected and rolling it back failed.");
102 GncDbiSqlConnection::lock_database (
bool break_lock)
108 auto tables = m_provider->get_table_list(m_conn, lock_table);
111 auto result = dbi_conn_queryf (m_conn,
112 "CREATE TABLE %s ( Hostname varchar(%d), PID int )",
117 dbi_result_free (result);
120 if (dbi_conn_error (m_conn, &errstr))
122 PERR (
"Error %s creating lock table", errstr);
129 char hostname[ GNC_HOST_NAME_MAX + 1 ];
130 auto result = dbi_conn_queryf (m_conn,
"SELECT * FROM %s",
132 if (result && dbi_result_get_numrows (result))
134 dbi_result_free (result);
143 result = dbi_conn_queryf (m_conn,
"DELETE FROM %s", lock_table.c_str());
147 m_qbe->
set_message(
"Failed to delete lock record");
151 dbi_result_free (result);
156 dbi_result_free (result);
160 memset (hostname, 0,
sizeof (hostname));
161 gethostname (hostname, GNC_HOST_NAME_MAX);
162 result = dbi_conn_queryf (m_conn,
163 "INSERT INTO %s VALUES ('%s', '%d')",
164 lock_table.c_str(), hostname, (int)GETPID ());
168 m_qbe->
set_message(
"Failed to create lock record");
172 dbi_result_free (result);
177 GncDbiSqlConnection::unlock_database ()
179 if (m_conn ==
nullptr)
return;
180 if (m_readonly)
return;
181 auto dbi_error{dbi_conn_error (m_conn,
nullptr)};
182 g_return_if_fail (dbi_error == DBI_ERROR_NONE || dbi_error == DBI_ERROR_BADIDX);
184 auto tables = m_provider->get_table_list (m_conn, lock_table);
187 PWARN (
"No lock table in database, so not unlocking it.");
193 char hostname[ GNC_HOST_NAME_MAX + 1 ];
195 memset (hostname, 0,
sizeof (hostname));
196 gethostname (hostname, GNC_HOST_NAME_MAX);
197 auto result = dbi_conn_queryf (m_conn,
198 "SELECT * FROM %s WHERE Hostname = '%s' " 199 "AND PID = '%d'", lock_table.c_str(),
202 if (result && dbi_result_get_numrows (result))
206 dbi_result_free (result);
209 result = dbi_conn_queryf (m_conn,
"DELETE FROM %s",
213 PERR (
"Failed to delete the lock entry");
220 dbi_result_free (result);
227 dbi_result_free (result);
229 PWARN (
"There was no lock entry in the Lock table");
232 PWARN (
"Unable to get a lock on LOCK, so failed to clear the lock entry.");
237 GncDbiSqlConnection::check_and_rollback_failed_save()
239 auto backup_tables = m_provider->get_table_list(m_conn,
"%back");
240 if (backup_tables.empty())
242 auto merge_tables = m_provider->get_table_list(m_conn,
"%_merge");
243 if (!merge_tables.empty())
245 PERR(
"Merge tables exist in the database indicating a previous" 246 "attempt to recover from a failed safe-save. Automatic" 247 "recovery is beyond GnuCash's ability, you must recover" 248 "by hand or restore from a good backup.");
254 GncDbiSqlConnection::~GncDbiSqlConnection()
259 dbi_conn_close(m_conn);
265 GncDbiSqlConnection::execute_select_statement (
const GncSqlStatementPtr& stmt)
270 DEBUG (
"SQL: %s\n", stmt->to_sql());
271 auto locale = gnc_push_locale (LC_NUMERIC,
"C");
275 result = dbi_conn_query (m_conn, stmt->to_sql());
278 if (result ==
nullptr)
280 PERR (
"Error executing SQL %s\n", stmt->to_sql());
282 m_qbe->set_error(m_last_error);
286 gnc_pop_locale (LC_NUMERIC, locale);
287 return std::make_unique<GncDbiSqlResult>(
this, result);
296 DEBUG (
"SQL: %s\n", stmt->to_sql());
300 result = dbi_conn_query (m_conn, stmt->to_sql());
303 if (result ==
nullptr && m_last_error)
305 PERR (
"Error executing SQL %s\n", stmt->to_sql());
307 m_qbe->set_error(m_last_error);
314 auto num_rows = (gint)dbi_result_get_numrows_affected (result);
315 auto status = dbi_result_free (result);
318 PERR (
"Error in dbi_result_free() result\n");
320 m_qbe->set_error(m_last_error);
328 GncDbiSqlConnection::create_statement_from_sql (
const std::string& sql)
338 return ! m_provider->get_table_list(m_conn, table_name).empty();
350 PERR (
"gnc_dbi_verify_conn() failed\n");
358 if (m_sql_savepoint == 0)
359 result = dbi_conn_queryf (m_conn,
"BEGIN");
362 std::ostringstream savepoint;
363 savepoint <<
"savepoint_" << m_sql_savepoint;
364 result = dbi_conn_queryf(m_conn,
"SAVEPOINT %s",
365 savepoint.str().c_str());
372 PERR (
"BEGIN transaction failed()\n");
376 if (dbi_result_free (result) < 0)
378 PERR (
"Error in dbi_result_free() result\n");
389 DEBUG (
"ROLLBACK\n");
390 if (m_sql_savepoint == 0)
return false;
392 if (m_sql_savepoint == 1)
393 result = dbi_conn_query (m_conn,
"ROLLBACK");
396 std::ostringstream savepoint;
397 savepoint <<
"savepoint_" << m_sql_savepoint - 1;
398 result = dbi_conn_queryf(m_conn,
"ROLLBACK TO SAVEPOINT %s",
399 savepoint.str().c_str());
403 PERR (
"Error in conn_rollback_transaction()\n");
408 if (dbi_result_free (result) < 0)
410 PERR (
"Error in dbi_result_free() result\n");
423 if (m_sql_savepoint == 0)
return false;
425 if (m_sql_savepoint == 1)
426 result = dbi_conn_queryf (m_conn,
"COMMIT");
429 std::ostringstream savepoint;
430 savepoint <<
"savepoint_" << m_sql_savepoint - 1;
431 result = dbi_conn_queryf(m_conn,
"RELEASE SAVEPOINT %s",
432 savepoint.str().c_str());
437 PERR (
"Error in conn_commit_transaction()\n");
442 if (dbi_result_free (result) < 0)
444 PERR (
"Error in dbi_result_free() result\n");
455 const ColVec& info_vec)
const noexcept
458 unsigned int col_num = 0;
460 ddl +=
"CREATE TABLE " + table_name +
"(";
461 for (
auto const& info : info_vec)
467 m_provider->append_col_def (ddl, info);
474 DEBUG (
"SQL: %s\n", ddl.c_str());
475 auto result = dbi_conn_query (m_conn, ddl.c_str());
476 auto status = dbi_result_free (result);
479 PERR (
"Error in dbi_result_free() result\n");
487 create_index_ddl (
const GncSqlConnection* conn,
const std::string& index_name,
488 const std::string& table_name,
const EntryVec& col_table)
491 ddl +=
"CREATE INDEX " + index_name +
" ON " + table_name +
"(";
492 for (
const auto& table_row : col_table)
494 if (table_row != *col_table.begin())
498 ddl += table_row->name();
506 const std::string& table_name,
507 const EntryVec& col_table)
const noexcept
509 auto ddl = create_index_ddl (
this, index_name, table_name, col_table);
512 DEBUG (
"SQL: %s\n", ddl.c_str());
513 auto result = dbi_conn_query (m_conn, ddl.c_str());
514 auto status = dbi_result_free (result);
517 PERR (
"Error in dbi_result_free() result\n");
526 const ColVec& info_vec)
529 auto ddl = add_columns_ddl(table_name, info_vec);
533 DEBUG (
"SQL: %s\n", ddl.c_str());
534 auto result = dbi_conn_query (m_conn, ddl.c_str());
535 auto status = dbi_result_free (result);
538 PERR(
"Error in dbi_result_free() result\n" );
546 GncDbiSqlConnection::quote_string (
const std::string& unquoted_str)
551 dbi_conn_quote_string_copy (m_conn, unquoted_str.c_str(),
553 if (quoted_str ==
nullptr)
554 return std::string{
""};
555 std::string retval{quoted_str};
577 (void)dbi_conn_connect (m_conn);
583 GncDbiSqlConnection::retry_connection(
const char* msg)
586 while (m_retry && m_error_repeat <= DBI_MAX_CONN_ATTEMPTS)
589 if (dbi_conn_connect(m_conn) == 0)
596 const guint backoff_msecs = 1;
597 Sleep (backoff_msecs * 2 << ++m_error_repeat);
599 const guint backoff_usecs = 1000;
600 usleep (backoff_usecs * 2 << ++m_error_repeat);
602 PINFO (
"DBI error: %s - Reconnecting...\n", msg);
605 PERR (
"DBI error: %s - Giving up after %d consecutive attempts.\n", msg,
606 DBI_MAX_CONN_ATTEMPTS);
612 GncDbiSqlConnection::rename_table(
const std::string& old_name,
613 const std::string& new_name)
615 std::string sql =
"ALTER TABLE " + old_name +
" RENAME TO " + new_name;
616 auto stmt = create_statement_from_sql(sql);
621 GncDbiSqlConnection::drop_table(
const std::string&
table)
623 std::string sql =
"DROP TABLE " +
table;
624 auto stmt = create_statement_from_sql(sql);
629 GncDbiSqlConnection::merge_tables(
const std::string&
table,
630 const std::string& other)
632 auto merge_table =
table +
"_merge";
633 std::string sql =
"CREATE TABLE " + merge_table +
" AS SELECT * FROM " +
634 table +
" UNION SELECT * FROM " + other;
635 auto stmt = create_statement_from_sql(sql);
638 sql = std::string(
"DELETE FROM ") +
table;
639 stmt = create_statement_from_sql(sql);
642 sql = std::string(
"INSERT INTO ") +
table +
643 " SELECT * FROM " + merge_table;
644 stmt = create_statement_from_sql(sql);
647 if (!drop_table(merge_table))
649 return drop_table(other);
680 auto backup_tables = m_provider->get_table_list(m_conn,
"%_back");
681 auto all_tables = m_provider->get_table_list(m_conn,
"");
683 auto new_end = std::remove(all_tables.begin(), all_tables.end(), lock_table);
684 all_tables.erase(new_end, all_tables.end());
686 data_tables.reserve(all_tables.size() - backup_tables.size());
687 std::set_difference(all_tables.begin(), all_tables.end(),
688 backup_tables.begin(), backup_tables.end(),
689 std::back_inserter(data_tables));
693 if (!backup_tables.empty())
695 PERR(
"Unable to backup database, an existing backup is present.");
699 for (
auto table : data_tables)
704 for (
auto table : backup_tables)
706 auto data_table =
table.substr(0,
table.find(
"_back"));
707 if (std::find(data_tables.begin(), data_tables.end(),
708 data_table) != data_tables.end())
711 rename_table(
table, data_table);
715 for (
auto table : backup_tables)
717 auto data_table =
table.substr(0,
table.find(
"_back"));
718 if (std::find(data_tables.begin(), data_tables.end(),
719 data_table) != data_tables.end())
720 drop_table(data_table);
721 rename_table(
table, data_table);
725 for (
auto table : backup_tables)
727 auto data_table =
table.substr(0,
table.find(
"_back"));
728 if (std::find(data_tables.begin(), data_tables.end(),
729 data_table) != data_tables.end())
731 if (!merge_tables(data_table,
table))
736 if (!rename_table(
table, data_table))
746 GncDbiSqlConnection::drop_indexes() noexcept
748 auto index_list = m_provider->get_index_list (m_conn);
749 for (
auto index : index_list)
752 m_provider->drop_index (m_conn, index);
753 if (DBI_ERROR_NONE != dbi_conn_error (m_conn, &errmsg))
755 PERR(
"Failed to drop indexes %s", errmsg);
763 GncDbiSqlConnection::add_columns_ddl(
const std::string& table_name,
764 const ColVec& info_vec)
const noexcept
768 ddl +=
"ALTER TABLE " + table_name;
769 for (
auto const& info : info_vec)
771 if (info != *info_vec.begin())
775 ddl +=
"ADD COLUMN ";
776 m_provider->append_col_def (ddl, info);
bool verify() noexcept override
Check if the dbi connection is valid.
void set_message(std::string &&)
Set a descriptive message that can be displayed to the user when there's an error.
#define G_LOG_DOMAIN
Functions providing the SX List as a plugin page.
#define PINFO(format, args...)
Print an informational note.
bool does_table_exist(const std::string &) const noexcept override
Returns true if successful.
const gchar * QofIdTypeConst
QofIdTypeConst declaration.
void qof_backend_set_error(QofBackend *qof_be, QofBackendError err)
Set the error on the specified QofBackend.
#define DEBUG(format, args...)
Print a debugging message.
in use by another user (ETXTBSY)
Open the session read-only, ignoring any existing lock and not creating one if the URI isn't locked...
#define PERR(format, args...)
Log a serious error.
Create a new store at the URI even if a store already exists there.
#define PWARN(format, args...)
Log a warning.
error in response from server
bool table_operation(TableOpType op) noexcept
Perform a specified SQL operation on every table in a database.
bool commit_transaction() noexcept override
Returns TRUE if successful, FALSE if error.
bool create_index(const std::string &, const std::string &, const EntryVec &) const noexcept override
Returns TRUE if successful, FALSE if error.
bool begin_transaction() noexcept override
Returns TRUE if successful, false if error.
SessionOpenMode
Mode for opening sessions.
bool add_columns_to_table(const std::string &, const ColVec &) const noexcept override
Returns TRUE if successful, FALSE if error.
Encapsulate the connection to the database.
bool create_table(const std::string &, const ColVec &) const noexcept override
Returns TRUE if successful, FALSE if error.
bool rollback_transaction() noexcept override
Returns TRUE if successful, FALSE if error.
int execute_nonselect_statement(const GncSqlStatementPtr &) noexcept override
Returns false if error.
void set_error(QofBackendError err)
Set the error value only if there isn't already an error already.