GnuCash  5.6-150-g038405b370+
Public Member Functions
GncDbiBackend< Type > Class Template Reference
Inheritance diagram for GncDbiBackend< Type >:
GncSqlBackend QofBackend

Public Member Functions

 GncDbiBackend (GncSqlConnection *conn, QofBook *book)
 
void session_begin (QofSession *, const char *, SessionOpenMode) override
 Open the file or connect to the server. More...
 
void session_end () override
 
void load (QofBook *, QofBackendLoadType) override
 Load the minimal set of application data needed for the application to be operable at initial startup. More...
 
void safe_sync (QofBook *) override
 Safely resave a database by renaming all of its tables, recreating everything, and then dropping the backup tables only if there were no errors. More...
 
bool connected () const noexcept
 
void set_dbi_error (QofBackendError error, unsigned int repeat, bool retry) noexcept
 FIXME: Just a pass-through to m_conn:
 
void retry_connection (const char *msg) const noexcept
 
bool exists ()
 
void set_exists (bool exists)
 
template<>
void session_begin (QofSession *session, const char *new_uri, SessionOpenMode mode)
 Open the file or connect to the server. More...
 
template<>
void safe_sync (QofBook *book)
 Perform a sync in a way that prevents data loss on a DBI backend.
 
- Public Member Functions inherited from GncSqlBackend
 GncSqlBackend (GncSqlConnection *conn, QofBook *book)
 
void load (QofBook *, QofBackendLoadType) override
 Load the contents of an SQL database into a book. More...
 
void sync (QofBook *) override
 Save the contents of a book to an SQL database. More...
 
void begin (QofInstance *) override
 An object is about to be edited. More...
 
void commit (QofInstance *) override
 Object editing is complete and the object should be saved. More...
 
void rollback (QofInstance *) override
 Object editing has been cancelled. More...
 
void connect (GncSqlConnection *conn) noexcept
 Connect the backend to a GncSqlConnection. More...
 
void init_version_info () noexcept
 Initializes DB table version information. More...
 
bool reset_version_info () noexcept
 Resets the version table information by removing all version table info. More...
 
void finalize_version_info () noexcept
 Finalizes DB table version information. More...
 
GncSqlStatementPtr create_statement_from_sql (const std::string &str) const noexcept
 
GncSqlResultPtr execute_select_statement (const GncSqlStatementPtr &stmt) const noexcept
 Executes an SQL SELECT statement and returns the result rows. More...
 
int execute_nonselect_statement (const GncSqlStatementPtr &stmt) const noexcept
 
std::string quote_string (const std::string &) const noexcept
 
bool create_table (const std::string &table_name, const EntryVec &col_table) const noexcept
 Creates a table in the database. More...
 
bool create_table (const std::string &table_name, int table_version, const EntryVec &col_table) noexcept
 Creates a table in the database and sets its version. More...
 
void create_tables () noexcept
 Create/update all tables in the database.
 
bool create_index (const std::string &index_name, const std::string &table_name, const EntryVec &col_table) const noexcept
 Creates an index in the database. More...
 
bool add_columns_to_table (const std::string &table_name, const EntryVec &col_table) const noexcept
 Adds one or more columns to an existing table. More...
 
void upgrade_table (const std::string &table_name, const EntryVec &col_table) noexcept
 Upgrades a table to a new structure. More...
 
uint_t get_table_version (const std::string &table_name) const noexcept
 Returns the version number for a DB table. More...
 
bool set_table_version (const std::string &table_name, uint_t version) noexcept
 Registers the version for a table. More...
 
void commodity_for_postload_processing (gnc_commodity *)
 Register a commodity to be committed after loading is complete. More...
 
GncSqlObjectBackendPtr get_object_backend (const std::string &type) const noexcept
 Get the GncSqlObjectBackend for the indicated type. More...
 
bool object_in_db (const char *table_name, QofIdTypeConst obj_name, const gpointer pObject, const EntryVec &table) const noexcept
 Checks whether an object is in the database or not. More...
 
bool do_db_operation (E_DB_OPERATION op, const char *table_name, QofIdTypeConst obj_name, gpointer pObject, const EntryVec &table) const noexcept
 Performs an operation on the database. More...
 
bool save_commodity (gnc_commodity *comm) noexcept
 Ensure that a commodity referenced in another object is in fact saved in the database. More...
 
QofBook * book () const noexcept
 
void set_loading (bool loading) noexcept
 
bool pristine () const noexcept
 
void update_progress (double pct) const noexcept
 
void finish_progress () const noexcept
 
- Public Member Functions inherited from QofBackend
 QofBackend (const QofBackend &)=delete
 
 QofBackend (const QofBackend &&)=delete
 
virtual void export_coa (QofBook *)
 Extract the chart of accounts from the current database and create a new database with it. More...
 
void set_error (QofBackendError err)
 Set the error value only if there isn't already an error already.
 
QofBackendError get_error ()
 Retrieve the currently-stored error and clear it.
 
bool check_error ()
 Report if there is an error.
 
void set_message (std::string &&)
 Set a descriptive message that can be displayed to the user when there's an error.
 
const std::string && get_message ()
 Retrieve and clear the stored error message.
 
void set_percentage (QofBePercentageFunc pctfn)
 Store and retrieve a backend-specific function for determining the progress in completing a long operation, for use with a progress meter.
 
QofBePercentageFunc get_percentage ()
 
const std::string & get_uri ()
 Retrieve the backend's storage URI.
 

Additional Inherited Members

- Static Public Member Functions inherited from QofBackend
static bool register_backend (const char *, const char *)
 Class methods for dynamically loading the several backends and for freeing them at shutdown.
 
static void release_backends ()
 
- Protected Attributes inherited from GncSqlBackend
GncSqlConnection * m_conn = nullptr
 SQL connection.
 
QofBook * m_book = nullptr
 The primary, main open book.
 
bool m_loading
 We are performing an initial load.
 
bool m_in_query
 We are processing a query.
 
bool m_is_pristine_db
 Are we saving to a new pristine db?
 
const char * m_time_format = nullptr
 Server-specific date-time string format.
 
VersionVec m_versions
 Version number for each table.
 
- Protected Attributes inherited from QofBackend
QofBePercentageFunc m_percentage
 
std::string m_fullpath
 Each backend resolves a fully-qualified file path. More...
 

Detailed Description

template<DbType Type>
class GncDbiBackend< Type >

Definition at line 88 of file gnc-backend-dbi.hpp.

Member Function Documentation

◆ load()

template<DbType Type>
void GncDbiBackend< Type >::load ( QofBook *  ,
QofBackendLoadType   
)
overridevirtual

Load the minimal set of application data needed for the application to be operable at initial startup.

It is assumed that the application will perform a 'run_query()' to obtain any additional data that it needs. For file-based backends, it is acceptable for the backend to return all data at load time; for SQL-based backends, it is acceptable for the backend to return no data.

Thus, for example, the old GnuCash postgres backend returned the account tree, all currencies, and the pricedb, as these were needed at startup. It did not have to return any transactions whatsoever, as these were obtained at a later stage when a user opened a register, resulting in a query being sent to the backend. The current DBI backend on the other hand loads the entire database into memory.

(Its OK to send over entities at this point, but one should be careful of the network load; also, its possible that whatever is sent is not what the user wanted anyway, which is why its better to wait for the query).

Implements QofBackend.

Definition at line 865 of file gnc-backend-dbi.cpp.

866 {
867  g_return_if_fail (book != nullptr);
868 
869  ENTER ("dbi_be=%p, book=%p", this, book);
870 
871  if (loadType == LOAD_TYPE_INITIAL_LOAD)
872  {
873 
874  // Set up table version information
876  assert (m_book == nullptr);
877  create_tables();
878  }
879 
880  GncSqlBackend::load(book, loadType);
881 
882  if (Type == DbType::DBI_SQLITE)
883  gnc_features_set_used(book, GNC_FEATURE_SQLITE3_ISO_DATES);
884 
885  if (GNUCASH_RESAVE_VERSION > get_table_version("Gnucash"))
886  {
887  /* The database was loaded with an older database schema or
888  * data semantics. In order to ensure consistency, the whole
889  * thing needs to be saved anew. */
891  }
892  else if (GNUCASH_RESAVE_VERSION < get_table_version("Gnucash-Resave"))
893  {
894  /* Worse, the database was created with a newer version. We
895  * can't safely write to this database, so the user will have
896  * to do a "save as" to make one that we can write to.
897  */
899  }
900 
901 
902  LEAVE ("");
903 }
void gnc_features_set_used(QofBook *book, const gchar *feature)
Indicate that the current book uses the given feature.
database is old and needs upgrading
Definition: qofbackend.h:113
void create_tables() noexcept
Create/update all tables in the database.
void load(QofBook *, QofBackendLoadType) override
Load the contents of an SQL database into a book.
#define ENTER(format, args...)
Print a function entry debugging message.
Definition: qoflog.h:272
database is newer, we can&#39;t write to it
Definition: qofbackend.h:114
QofBook * m_book
The primary, main open book.
void init_version_info() noexcept
Initializes DB table version information.
#define LEAVE(format, args...)
Print a function exit debugging message.
Definition: qoflog.h:282
uint_t get_table_version(const std::string &table_name) const noexcept
Returns the version number for a DB table.
void set_error(QofBackendError err)
Set the error value only if there isn&#39;t already an error already.
Definition: qof-backend.cpp:56

◆ safe_sync()

template<DbType Type>
void GncDbiBackend< Type >::safe_sync ( QofBook *  book)
overridevirtual

Safely resave a database by renaming all of its tables, recreating everything, and then dropping the backup tables only if there were no errors.

If there are errors, drop the new tables and restore the originals.

Parameters
bookQofBook to be saved in the database.

Implements QofBackend.

Definition at line 949 of file gnc-backend-dbi.cpp.

950 {
951  auto conn = dynamic_cast<GncDbiSqlConnection*>(m_conn);
952 
953  g_return_if_fail (conn != nullptr);
954  g_return_if_fail (book != nullptr);
955 
956  ENTER ("book=%p, primary=%p", book, m_book);
957  if (!conn->begin_transaction())
958  {
959  LEAVE("Failed to obtain a transaction.");
960  return;
961  }
962  if (!conn->table_operation (TableOpType::backup))
963  {
964  conn->rollback_transaction();
965  LEAVE ("Failed to rename tables");
966  return;
967  }
968  if (!conn->drop_indexes())
969  {
970  conn->rollback_transaction();
971  LEAVE ("Failed to drop indexes");
972  return;
973  }
974 
975  sync(m_book);
976  if (check_error())
977  {
978  conn->rollback_transaction();
979  LEAVE ("Failed to create new database tables");
980  return;
981  }
982  conn->commit_transaction();
983  conn->table_operation (TableOpType::drop_backup);
984  LEAVE ("book=%p", m_book);
985 }
GncSqlConnection * m_conn
SQL connection.
#define ENTER(format, args...)
Print a function entry debugging message.
Definition: qoflog.h:272
void sync(QofBook *) override
Save the contents of a book to an SQL database.
QofBook * m_book
The primary, main open book.
Encapsulate a libdbi dbi_conn connection.
#define LEAVE(format, args...)
Print a function exit debugging message.
Definition: qoflog.h:282
bool check_error()
Report if there is an error.
Definition: qof-backend.cpp:73

◆ session_begin() [1/2]

template<DbType Type>
void GncDbiBackend< Type >::session_begin ( QofSession *  session,
const char *  new_uri,
SessionOpenMode  mode 
)
overridevirtual

Open the file or connect to the server.

Parameters
sessionThe QofSession that will control the backend.
new_uriThe location of the data store that the backend will use.
modeThe session open mode. See qof_session_begin().

Implements QofBackend.

Definition at line 640 of file gnc-backend-dbi.cpp.

642 {
643  PairVec options;
644 
645  g_return_if_fail (session != nullptr);
646  g_return_if_fail (new_uri != nullptr);
647 
648  ENTER (" ");
649 
650  /* Split the book-id
651  * Format is protocol://username:password@hostname:port/dbname
652  where username, password and port are optional) */
653  UriStrings uri(new_uri);
654 
655  if (Type == DbType::DBI_PGSQL)
656  {
657  if (uri.m_portnum == 0)
658  uri.m_portnum = PGSQL_DEFAULT_PORT;
659  /* Postgres's SQL interface coerces identifiers to lower case, but the
660  * C interface is case-sensitive. This results in a mixed-case dbname
661  * being created (with a lower case name) but then dbi can't connect to
662  * it. To work around this, coerce the name to lowercase first. */
663  auto lcname = g_utf8_strdown (uri.dbname(), -1);
664  uri.m_dbname = std::string{lcname};
665  g_free(lcname);
666  }
667  connect(nullptr);
668 
669  bool create{mode == SESSION_NEW_STORE || mode == SESSION_NEW_OVERWRITE};
670  auto conn = conn_setup(options, uri);
671  if (conn == nullptr)
672  {
673  LEAVE("Error");
674  return;
675  }
676 
677  m_exists = true; //May be unset in the error handler.
678  auto result = dbi_conn_connect (conn);
679  if (result == 0)
680  {
681  if (Type == DbType::DBI_MYSQL)
682  adjust_sql_options (conn);
683  if (mode != SESSION_READ_ONLY && !conn_test_dbi_library(conn))
684  {
685  dbi_conn_close(conn);
686  LEAVE("Error");
687  return;
688  }
689  bool create = (mode == SESSION_NEW_STORE ||
690  mode == SESSION_NEW_OVERWRITE);
691  if (create && save_may_clobber_data<Type>(conn, uri.quote_dbname(Type)))
692  {
693  if (mode == SESSION_NEW_OVERWRITE)
694  {
695  if (!drop_database<Type>(conn, uri))
696  return;
697  }
698  else
699  {
701  PWARN ("Database already exists, Might clobber it.");
702  dbi_conn_close(conn);
703  LEAVE("Error");
704  return;
705  }
706  /* Drop successful. */
707  m_exists = false;
708  }
709 
710  }
711  else if (m_exists)
712  {
713  PERR ("Unable to connect to database '%s'\n", uri.dbname());
715  dbi_conn_close(conn);
716  LEAVE("Error");
717  return;
718  }
719  else if (!create)
720  {
721  PERR ("Database '%s' does not exist\n", uri.dbname());
723  std::string msg{"Database "};
724  set_message(msg + uri.dbname() + " not found");
725  LEAVE("Error");
726  return;
727  }
728 
729  if (create)
730  {
731  if (!m_exists &&
732  !create_database(conn, uri.quote_dbname(Type).c_str()))
733  {
734  dbi_conn_close(conn);
735  LEAVE("Error");
736  return;
737  }
738  conn = conn_setup(options, uri);
739  result = dbi_conn_connect (conn);
740  if (result < 0)
741  {
742  PERR ("Unable to create database '%s'\n", uri.dbname());
744  dbi_conn_close(conn);
745  LEAVE("Error");
746  return;
747  }
748  if (Type == DbType::DBI_MYSQL)
749  adjust_sql_options (conn);
750  if (!conn_test_dbi_library(conn))
751  {
752  if (Type == DbType::DBI_PGSQL)
753  dbi_conn_select_db (conn, "template1");
754  dbi_result_free (dbi_conn_queryf (conn, "DROP DATABASE %s",
755  uri.quote_dbname(Type).c_str()));
756  dbi_conn_close(conn);
757  return;
758  }
759  }
760 
761  connect(nullptr);
762  try
763  {
764  connect(new GncDbiSqlConnection(Type, this, conn, mode));
765  }
766  catch (std::runtime_error& err)
767  {
768  return;
769  }
770  /* We should now have a proper session set up.
771  * Let's start logging */
772  auto translog_path = gnc_build_translog_path (uri.basename().c_str());
773  xaccLogSetBaseName (translog_path);
774  PINFO ("logpath=%s", translog_path ? translog_path : "(null)");
775  g_free (translog_path);
776 
777  LEAVE (" ");
778 }
void set_message(std::string &&)
Set a descriptive message that can be displayed to the user when there&#39;s an error.
Definition: qof-backend.cpp:79
#define PINFO(format, args...)
Print an informational note.
Definition: qoflog.h:256
Create a new store at the URI.
Definition: qofsession.h:126
#define PERR(format, args...)
Log a serious error.
Definition: qoflog.h:244
#define ENTER(format, args...)
Print a function entry debugging message.
Definition: qoflog.h:272
Create a new store at the URI even if a store already exists there.
Definition: qofsession.h:128
#define PWARN(format, args...)
Log a warning.
Definition: qoflog.h:250
error in response from server
Definition: qofbackend.h:71
gchar * gnc_build_translog_path(const gchar *filename)
Make a path to filename in the translog subdirectory of the user&#39;s configuration directory.
the named database doesn&#39;t exist
Definition: qofbackend.h:63
Encapsulate a libdbi dbi_conn connection.
File exists, data would be destroyed.
Definition: qofbackend.h:67
void xaccLogSetBaseName(const char *basepath)
The xaccLogSetBaseName() method sets the base filepath and the root part of the journal file name...
Definition: TransLog.cpp:120
void connect(GncSqlConnection *conn) noexcept
Connect the backend to a GncSqlConnection.
bad dbname/login/passwd or network failure
Definition: qofbackend.h:64
#define LEAVE(format, args...)
Print a function exit debugging message.
Definition: qoflog.h:282
void set_error(QofBackendError err)
Set the error value only if there isn&#39;t already an error already.
Definition: qof-backend.cpp:56
Open will fail if the URI doesn&#39;t exist or is locked.
Definition: qofsession.h:124

◆ session_begin() [2/2]

template<>
void GncDbiBackend< DbType::DBI_SQLITE >::session_begin ( QofSession *  session,
const char *  new_uri,
SessionOpenMode  mode 
)
virtual

Open the file or connect to the server.

Parameters
sessionThe QofSession that will control the backend.
new_uriThe location of the data store that the backend will use.
modeThe session open mode. See qof_session_begin().

Implements QofBackend.

Definition at line 357 of file gnc-backend-dbi.cpp.

360 {
361  gboolean file_exists;
362  PairVec options;
363 
364  g_return_if_fail (session != nullptr);
365  g_return_if_fail (new_uri != nullptr);
366 
367  ENTER (" ");
368 
369  /* Remove uri type if present */
370  auto path = gnc_uri_get_path (new_uri);
371  std::string filepath{path};
372  g_free(path);
373  GFileTest ftest = static_cast<decltype (ftest)> (
374  G_FILE_TEST_IS_REGULAR | G_FILE_TEST_EXISTS) ;
375  file_exists = g_file_test (filepath.c_str(), ftest);
376  bool create{mode == SESSION_NEW_STORE || mode == SESSION_NEW_OVERWRITE};
377  if (!create && !file_exists)
378  {
380  std::string msg{"Sqlite3 file "};
381  set_message (msg + filepath + " not found");
382  PWARN ("Sqlite3 file %s not found", filepath.c_str());
383  LEAVE("Error");
384  return;
385  }
386 
387  if (create && file_exists)
388  {
389  if (mode == SESSION_NEW_OVERWRITE)
390  g_unlink (filepath.c_str());
391  else
392  {
394  auto msg = "Might clobber, mode not SESSION_NEW_OVERWRITE";
395  PWARN ("%s", msg);
396  LEAVE("Error");
397  return;
398  }
399  }
400 
401  connect(nullptr);
402  /* dbi-sqlite3 documentation says that sqlite3 doesn't take a "host" option */
403  options.push_back(std::make_pair("host", "localhost"));
404  auto dirname = g_path_get_dirname (filepath.c_str());
405  auto basename = g_path_get_basename (filepath.c_str());
406  options.push_back(std::make_pair("dbname", basename));
407  options.push_back(std::make_pair("sqlite3_dbdir", dirname));
408  if (basename != nullptr) g_free (basename);
409  if (dirname != nullptr) g_free (dirname);
410  UriStrings uri;
411  auto conn = conn_setup(options, uri);
412  if (conn == nullptr)
413  {
414  LEAVE("Error");
415  return;
416  }
417 
418  auto result = dbi_conn_connect (conn);
419 
420  if (result < 0)
421  {
422  dbi_conn_close(conn);
423  PERR ("Unable to connect to %s: %d\n", new_uri, result);
425  LEAVE("Error");
426  return;
427  }
428 
429  if (mode != SESSION_READ_ONLY && !conn_test_dbi_library(conn))
430  {
431  if (create && !file_exists)
432  {
433  /* File didn't exist before, but it does now, and we don't want to
434  * leave it lying around.
435  */
436  dbi_conn_close (conn);
437  conn = nullptr;
438  g_unlink (filepath.c_str());
439  }
440  dbi_conn_close(conn);
441  LEAVE("Bad DBI Library");
442  return;
443  }
444 
445  try
446  {
447  connect(new GncDbiSqlConnection(DbType::DBI_SQLITE,
448  this, conn, mode));
449  }
450  catch (std::runtime_error& err)
451  {
452  return;
453  }
454 
455  /* We should now have a proper session set up.
456  * Let's start logging */
457  xaccLogSetBaseName (filepath.c_str());
458  PINFO ("logpath=%s", filepath.c_str() ? filepath.c_str() : "(null)");
459  LEAVE ("");
460 }
not found / no such file
Definition: qofbackend.h:92
void set_message(std::string &&)
Set a descriptive message that can be displayed to the user when there&#39;s an error.
Definition: qof-backend.cpp:79
#define PINFO(format, args...)
Print an informational note.
Definition: qoflog.h:256
gchar * gnc_uri_get_path(const gchar *uri)
Extracts the path part from a uri.
Can&#39;t parse url.
Definition: qofbackend.h:62
Create a new store at the URI.
Definition: qofsession.h:126
#define PERR(format, args...)
Log a serious error.
Definition: qoflog.h:244
#define ENTER(format, args...)
Print a function entry debugging message.
Definition: qoflog.h:272
Create a new store at the URI even if a store already exists there.
Definition: qofsession.h:128
#define PWARN(format, args...)
Log a warning.
Definition: qoflog.h:250
Encapsulate a libdbi dbi_conn connection.
File exists, data would be destroyed.
Definition: qofbackend.h:67
void xaccLogSetBaseName(const char *basepath)
The xaccLogSetBaseName() method sets the base filepath and the root part of the journal file name...
Definition: TransLog.cpp:120
void connect(GncSqlConnection *conn) noexcept
Connect the backend to a GncSqlConnection.
#define LEAVE(format, args...)
Print a function exit debugging message.
Definition: qoflog.h:282
void set_error(QofBackendError err)
Set the error value only if there isn&#39;t already an error already.
Definition: qof-backend.cpp:56
Open will fail if the URI doesn&#39;t exist or is locked.
Definition: qofsession.h:124

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