GnuCash de0bfde+
Loading...
Searching...
No Matches
GncDbiSqlConnection Class Reference

Encapsulate a libdbi dbi_conn connection. More...

#include <gnc-dbisqlconnection.hpp>

Inheritance diagram for GncDbiSqlConnection:
GncSqlConnection

Public Member Functions

 GncDbiSqlConnection (DbType type, QofBackend *qbe, dbi_conn conn, SessionOpenMode mode)
GncSqlResultPtr execute_select_statement (const GncSqlStatementPtr &) noexcept override
int execute_nonselect_statement (const GncSqlStatementPtr &) noexcept override
 Returns false if error.
GncSqlStatementPtr create_statement_from_sql (const std::string &) const noexcept override
bool does_table_exist (const std::string &) const noexcept override
 Returns true if successful.
bool begin_transaction () noexcept override
 Returns TRUE if successful, false if error.
bool rollback_transaction () noexcept override
 Returns TRUE if successful, FALSE if error.
bool commit_transaction () noexcept override
 Returns TRUE if successful, FALSE if error.
bool create_table (const std::string &, const ColVec &) const 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 add_columns_to_table (const std::string &, const ColVec &) const noexcept override
 Returns TRUE if successful, FALSE if error.
std::string quote_string (const std::string &) const noexcept override
int dberror () const noexcept override
 Get the connection error value.
QofBackend * qbe () const noexcept
dbi_conn conn () const noexcept
void set_error (QofBackendError error, unsigned int repeat, bool retry) noexcept override
void init_error () noexcept
bool verify () noexcept override
 Check if the dbi connection is valid.
bool retry_connection (const char *msg) noexcept override
bool table_operation (TableOpType op) noexcept
 Perform a specified SQL operation on every table in a database.
std::string add_columns_ddl (const std::string &table_name, const ColVec &info_vec) const noexcept
bool drop_indexes () noexcept
Public Member Functions inherited from GncSqlConnection
virtual ~GncSqlConnection ()=default
 Returns NULL if error.

Detailed Description

Encapsulate a libdbi dbi_conn connection.

Definition at line 41 of file gnc-dbisqlconnection.hpp.

Constructor & Destructor Documentation

◆ GncDbiSqlConnection()

GncDbiSqlConnection::GncDbiSqlConnection ( DbType type,
QofBackend * qbe,
dbi_conn conn,
SessionOpenMode mode )

Definition at line 79 of file gnc-dbisqlconnection.cpp.

80 :
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}
89{
90 if (mode == SESSION_READ_ONLY)
91 m_readonly = true;
92 else if (!lock_database(mode == SESSION_BREAK_LOCK))
93 throw std::runtime_error("Failed to lock database!");
94 if (!check_and_rollback_failed_save())
95 {
96 unlock_database();
97 throw std::runtime_error("A failed safe-save was detected and rolling it back failed.");
98 }
99}
@ SESSION_READ_ONLY
Create a new store at the URI even if a store already exists there.
Definition qofsession.h:128
@ SESSION_BREAK_LOCK
Open the session read-only, ignoring any existing lock and not creating one if the URI isn't locked.
Definition qofsession.h:130

◆ ~GncDbiSqlConnection()

GncDbiSqlConnection::~GncDbiSqlConnection ( )
override

Definition at line 254 of file gnc-dbisqlconnection.cpp.

255{
256 if (m_conn)
257 {
258 unlock_database();
259 dbi_conn_close(m_conn);
260 m_conn = nullptr;
261 }
262}

Member Function Documentation

◆ add_columns_ddl()

std::string GncDbiSqlConnection::add_columns_ddl ( const std::string & table_name,
const ColVec & info_vec ) const
noexcept

Definition at line 763 of file gnc-dbisqlconnection.cpp.

765{
766 std::string ddl;
767
768 ddl += "ALTER TABLE " + table_name;
769 for (auto const& info : info_vec)
770 {
771 if (info != *info_vec.begin())
772 {
773 ddl += ", ";
774 }
775 ddl += "ADD COLUMN ";
776 m_provider->append_col_def (ddl, info);
777 }
778 return ddl;
779}

◆ add_columns_to_table()

bool GncDbiSqlConnection::add_columns_to_table ( const std::string & ,
const ColVec &  ) const
overridevirtualnoexcept

Returns TRUE if successful, FALSE if error.

Implements GncSqlConnection.

Definition at line 525 of file gnc-dbisqlconnection.cpp.

528{
529 auto ddl = add_columns_ddl(table_name, info_vec);
530 if (ddl.empty())
531 return false;
532
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);
536 if (status < 0)
537 {
538 PERR( "Error in dbi_result_free() result\n" );
540 }
541
542 return true;
543}
void qof_backend_set_error(QofBackend *qof_be, QofBackendError err)
Set the error on the specified QofBackend.
@ ERR_BACKEND_SERVER_ERR
error in response from server
Definition qofbackend.h:71
#define DEBUG(format, args...)
Print a debugging message.
Definition qoflog.h:264
#define PERR(format, args...)
Log a serious error.
Definition qoflog.h:244

◆ begin_transaction()

bool GncDbiSqlConnection::begin_transaction ( )
overridevirtualnoexcept

Returns TRUE if successful, false if error.

Implements GncSqlConnection.

Definition at line 342 of file gnc-dbisqlconnection.cpp.

343{
344 dbi_result result;
345
346 DEBUG ("BEGIN\n");
347
348 if (!verify ())
349 {
350 PERR ("gnc_dbi_verify_conn() failed\n");
352 return false;
353 }
354
355 do
356 {
357 init_error ();
358 if (m_sql_savepoint == 0)
359 result = dbi_conn_queryf (m_conn, "BEGIN");
360 else
361 {
362 std::ostringstream savepoint;
363 savepoint << "savepoint_" << m_sql_savepoint;
364 result = dbi_conn_queryf(m_conn, "SAVEPOINT %s",
365 savepoint.str().c_str());
366 }
367 }
368 while (m_retry);
369
370 if (!result)
371 {
372 PERR ("BEGIN transaction failed()\n");
374 return false;
375 }
376 if (dbi_result_free (result) < 0)
377 {
378 PERR ("Error in dbi_result_free() result\n");
380 return false;
381 }
382 ++m_sql_savepoint;
383 return true;
384}
bool verify() noexcept override
Check if the dbi connection is valid.

◆ commit_transaction()

bool GncDbiSqlConnection::commit_transaction ( )
overridevirtualnoexcept

Returns TRUE if successful, FALSE if error.

Implements GncSqlConnection.

Definition at line 420 of file gnc-dbisqlconnection.cpp.

421{
422 DEBUG ("COMMIT\n");
423 if (m_sql_savepoint == 0) return false;
424 dbi_result result;
425 if (m_sql_savepoint == 1)
426 result = dbi_conn_queryf (m_conn, "COMMIT");
427 else
428 {
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());
433 }
434
435 if (!result)
436 {
437 PERR ("Error in conn_commit_transaction()\n");
439 return false;
440 }
441
442 if (dbi_result_free (result) < 0)
443 {
444 PERR ("Error in dbi_result_free() result\n");
446 return false;
447 }
448 --m_sql_savepoint;
449 return true;
450}

◆ conn()

dbi_conn GncDbiSqlConnection::conn ( ) const
inlinenoexcept

Definition at line 66 of file gnc-dbisqlconnection.hpp.

66{ return m_conn; }

◆ create_index()

bool GncDbiSqlConnection::create_index ( const std::string & ,
const std::string & ,
const EntryVec &  ) const
overridevirtualnoexcept

Returns TRUE if successful, FALSE if error.

Implements GncSqlConnection.

Definition at line 505 of file gnc-dbisqlconnection.cpp.

508{
509 auto ddl = create_index_ddl (this, index_name, table_name, col_table);
510 if (ddl.empty())
511 return false;
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);
515 if (status < 0)
516 {
517 PERR ("Error in dbi_result_free() result\n");
519 }
520
521 return true;
522}

◆ create_statement_from_sql()

GncSqlStatementPtr GncDbiSqlConnection::create_statement_from_sql ( const std::string & sql) const
overridevirtualnoexcept

Implements GncSqlConnection.

Definition at line 328 of file gnc-dbisqlconnection.cpp.

330{
331 return std::unique_ptr<GncSqlStatement>{new GncDbiSqlStatement (sql)};
332}

◆ create_table()

bool GncDbiSqlConnection::create_table ( const std::string & ,
const ColVec &  ) const
overridevirtualnoexcept

Returns TRUE if successful, FALSE if error.

Implements GncSqlConnection.

Definition at line 454 of file gnc-dbisqlconnection.cpp.

456{
457 std::string ddl;
458 unsigned int col_num = 0;
459
460 ddl += "CREATE TABLE " + table_name + "(";
461 for (auto const& info : info_vec)
462 {
463 if (col_num++ != 0)
464 {
465 ddl += ", ";
466 }
467 m_provider->append_col_def (ddl, info);
468 }
469 ddl += ")";
470
471 if (ddl.empty())
472 return false;
473
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);
477 if (status < 0)
478 {
479 PERR ("Error in dbi_result_free() result\n");
481 }
482
483 return true;
484}

◆ dberror()

int GncDbiSqlConnection::dberror ( ) const
inlineoverridevirtualnoexcept

Get the connection error value.

If not 0 will normally be meaningless outside of implementation code.

Implements GncSqlConnection.

Definition at line 63 of file gnc-dbisqlconnection.hpp.

63 {
64 return dbi_conn_error(m_conn, nullptr); }

◆ does_table_exist()

bool GncDbiSqlConnection::does_table_exist ( const std::string & ) const
overridevirtualnoexcept

Returns true if successful.

Implements GncSqlConnection.

Definition at line 335 of file gnc-dbisqlconnection.cpp.

337{
338 return ! m_provider->get_table_list(m_conn, table_name).empty();
339}

◆ drop_indexes()

bool GncDbiSqlConnection::drop_indexes ( )
noexcept

Definition at line 746 of file gnc-dbisqlconnection.cpp.

747{
748 auto index_list = m_provider->get_index_list (m_conn);
749 for (auto index : index_list)
750 {
751 const char* errmsg;
752 m_provider->drop_index (m_conn, index);
753 if (DBI_ERROR_NONE != dbi_conn_error (m_conn, &errmsg))
754 {
755 PERR("Failed to drop indexes %s", errmsg);
756 return false;
757 }
758 }
759 return true;
760}

◆ execute_nonselect_statement()

int GncDbiSqlConnection::execute_nonselect_statement ( const GncSqlStatementPtr & )
overridevirtualnoexcept

Returns false if error.

Implements GncSqlConnection.

Definition at line 291 of file gnc-dbisqlconnection.cpp.

293{
294 dbi_result result;
295
296 DEBUG ("SQL: %s\n", stmt->to_sql());
297 do
298 {
299 init_error ();
300 result = dbi_conn_query (m_conn, stmt->to_sql());
301 }
302 while (m_retry);
303 if (result == nullptr && m_last_error)
304 {
305 PERR ("Error executing SQL %s\n", stmt->to_sql());
306 if(m_last_error)
307 m_qbe->set_error(m_last_error);
308 else
309 m_qbe->set_error(ERR_BACKEND_SERVER_ERR);
310 return -1;
311 }
312 if (!result)
313 return 0;
314 auto num_rows = (gint)dbi_result_get_numrows_affected (result);
315 auto status = dbi_result_free (result);
316 if (status < 0)
317 {
318 PERR ("Error in dbi_result_free() result\n");
319 if(m_last_error)
320 m_qbe->set_error(m_last_error);
321 else
322 m_qbe->set_error(ERR_BACKEND_SERVER_ERR);
323 }
324 return num_rows;
325}

◆ execute_select_statement()

GncSqlResultPtr GncDbiSqlConnection::execute_select_statement ( const GncSqlStatementPtr & stmt)
overridevirtualnoexcept

Implements GncSqlConnection.

Definition at line 265 of file gnc-dbisqlconnection.cpp.

267{
268 dbi_result result;
269
270 DEBUG ("SQL: %s\n", stmt->to_sql());
271 auto locale = gnc_push_locale (LC_NUMERIC, "C");
272 do
273 {
274 init_error ();
275 result = dbi_conn_query (m_conn, stmt->to_sql());
276 }
277 while (m_retry);
278 if (result == nullptr)
279 {
280 PERR ("Error executing SQL %s\n", stmt->to_sql());
281 if(m_last_error)
282 m_qbe->set_error(m_last_error);
283 else
284 m_qbe->set_error(ERR_BACKEND_SERVER_ERR);
285 }
286 gnc_pop_locale (LC_NUMERIC, locale);
287 return std::make_unique<GncDbiSqlResult>(this, result);
288}

◆ init_error()

void GncDbiSqlConnection::init_error ( )
inlinenoexcept

Definition at line 74 of file gnc-dbisqlconnection.hpp.

75 {
76 set_error(ERR_BACKEND_NO_ERR, 0, false);
77 }

◆ qbe()

QofBackend * GncDbiSqlConnection::qbe ( ) const
inlinenoexcept

Definition at line 65 of file gnc-dbisqlconnection.hpp.

65{ return m_qbe; }

◆ quote_string()

std::string GncDbiSqlConnection::quote_string ( const std::string & unquoted_str) const
overridevirtualnoexcept

Implements GncSqlConnection.

Definition at line 546 of file gnc-dbisqlconnection.cpp.

548{
549 char* quoted_str;
550
551 dbi_conn_quote_string_copy (m_conn, unquoted_str.c_str(),
552 &quoted_str);
553 if (quoted_str == nullptr)
554 return std::string{""};
555 std::string retval{quoted_str};
556 free(quoted_str);
557 return retval;
558}

◆ retry_connection()

bool GncDbiSqlConnection::retry_connection ( const char * msg)
overridevirtualnoexcept

Implements GncSqlConnection.

Definition at line 583 of file gnc-dbisqlconnection.cpp.

585{
586 while (m_retry && m_error_repeat <= DBI_MAX_CONN_ATTEMPTS)
587 {
588 m_conn_ok = false;
589 if (dbi_conn_connect(m_conn) == 0)
590 {
591 init_error();
592 m_conn_ok = true;
593 return true;
594 }
595#ifdef G_OS_WIN32
596 const guint backoff_msecs = 1;
597 Sleep (backoff_msecs * 2 << ++m_error_repeat);
598#else
599 const guint backoff_usecs = 1000;
600 usleep (backoff_usecs * 2 << ++m_error_repeat);
601#endif
602 PINFO ("DBI error: %s - Reconnecting...\n", msg);
603
604 }
605 PERR ("DBI error: %s - Giving up after %d consecutive attempts.\n", msg,
606 DBI_MAX_CONN_ATTEMPTS);
607 m_conn_ok = false;
608 return false;
609}
#define PINFO(format, args...)
Print an informational note.
Definition qoflog.h:256

◆ rollback_transaction()

bool GncDbiSqlConnection::rollback_transaction ( )
overridevirtualnoexcept

Returns TRUE if successful, FALSE if error.

Implements GncSqlConnection.

Definition at line 387 of file gnc-dbisqlconnection.cpp.

388{
389 DEBUG ("ROLLBACK\n");
390 if (m_sql_savepoint == 0) return false;
391 dbi_result result;
392 if (m_sql_savepoint == 1)
393 result = dbi_conn_query (m_conn, "ROLLBACK");
394 else
395 {
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());
400 }
401 if (!result)
402 {
403 PERR ("Error in conn_rollback_transaction()\n");
405 return false;
406 }
407
408 if (dbi_result_free (result) < 0)
409 {
410 PERR ("Error in dbi_result_free() result\n");
412 return false;
413 }
414
415 --m_sql_savepoint;
416 return true;
417}

◆ set_error()

void GncDbiSqlConnection::set_error ( QofBackendError error,
unsigned int repeat,
bool retry )
inlineoverridevirtualnoexcept

Implements GncSqlConnection.

Definition at line 67 of file gnc-dbisqlconnection.hpp.

69 {
70 m_last_error = error;
71 m_error_repeat = repeat;
72 m_retry = retry;
73 }

◆ table_operation()

bool GncDbiSqlConnection::table_operation ( TableOpType op)
noexcept

Perform a specified SQL operation on every table in a database.

Possible operations are:

  • drop: to DROP all tables from the database
  • empty: to DELETE all records from each table in the database.
  • backup: Rename every table from "name" to "name_back"
  • drop_backup: DROP the backup tables.
  • rollback: DROP the new table "name" and rename "name_back" to "name", restoring the database to its previous state.

The intent of the last two is to be able to move an existing table aside, query its contents with a transformation (in 2.4.x this is already done as the contents are loaded completely when a Qof session is started), save them to a new table according to a new database format, and finally drop the backup table; if there's an error during the process, rollback allows returning the table to its original state.

Parameters
sql_connThe sql connection (via dbi) to which the transactions will be sent
table_namessStrVec of tables to operate on.
opThe operation to perform.
Returns
Success (TRUE) or failure.

Definition at line 678 of file gnc-dbisqlconnection.cpp.

679{
680 auto backup_tables = m_provider->get_table_list(m_conn, "%_back");
681 auto all_tables = m_provider->get_table_list(m_conn, "");
682 /* No operations on the lock table */
683 auto new_end = std::remove(all_tables.begin(), all_tables.end(), lock_table);
684 all_tables.erase(new_end, all_tables.end());
685 StrVec data_tables;
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));
690 switch(op)
691 {
692 case backup:
693 if (!backup_tables.empty())
694 {
695 PERR("Unable to backup database, an existing backup is present.");
697 return false;
698 }
699 for (auto table : data_tables)
700 if (!rename_table(table, table +"_back"))
701 return false; /* Error, trigger rollback. */
702 break;
703 case drop_backup:
704 for (auto table : backup_tables)
705 {
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())
709 drop_table(table); /* Other table exists, OK. */
710 else /* No data table, restore the backup */
711 rename_table(table, data_table);
712 }
713 break;
714 case rollback:
715 for (auto table : backup_tables)
716 {
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); /* Other table exists, OK. */
721 rename_table(table, data_table);
722 }
723 break;
724 case recover:
725 for (auto table : backup_tables)
726 {
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())
730 {
731 if (!merge_tables(data_table, table))
732 return false;
733 }
734 else
735 {
736 if (!rename_table(table, data_table))
737 return false;
738 }
739 }
740 break;
741 }
742 return true;
743}
@ ERR_BACKEND_DATA_CORRUPT
data in db is corrupt
Definition qofbackend.h:70

◆ verify()

bool GncDbiSqlConnection::verify ( )
overridevirtualnoexcept

Check if the dbi connection is valid.

If not attempt to re-establish it Returns TRUE if there is a valid connection in the end or FALSE otherwise

Implements GncSqlConnection.

Definition at line 565 of file gnc-dbisqlconnection.cpp.

566{
567 if (m_conn_ok)
568 return true;
569
570 /* We attempt to connect only once here. The error function will
571 * automatically re-attempt up until DBI_MAX_CONN_ATTEMPTS time to connect
572 * if this call fails. After all these attempts, conn_ok will indicate if
573 * there is a valid connection or not.
574 */
575 init_error ();
576 m_conn_ok = true;
577 (void)dbi_conn_connect (m_conn);
578
579 return m_conn_ok;
580}

The documentation for this class was generated from the following files: