GnuCash  5.6-150-g038405b370+
gnc-backend-dbi.cpp
1 /********************************************************************
2  * gnc-backend-dbi.c: load and save data to SQL via libdbi *
3  * *
4  * This program is free software; you can redistribute it and/or *
5  * modify it under the terms of the GNU General Public License as *
6  * published by the Free Software Foundation; either version 2 of *
7  * the License, or (at your option) any later version. *
8  * *
9  * This program is distributed in the hope that it will be useful, *
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12  * GNU General Public License for more details. *
13  * *
14  * You should have received a copy of the GNU General Public License*
15  * along with this program; if not, contact: *
16  * *
17  * Free Software Foundation Voice: +1-617-542-5942 *
18  * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 *
19  * Boston, MA 02110-1301, USA gnu@gnu.org *
20 \********************************************************************/
28 #include <glib.h>
29 #include <glib/gstdio.h>
30 
31 #include "config.h"
32 
33 #include <platform.h>
34 #if PLATFORM(WINDOWS)
35 #include <winsock2.h>
36 #include <windows.h>
37 #endif
38 
39 #include <inttypes.h>
40 #include <errno.h>
41 #include "qof.h"
42 #include "qofquery-p.h"
43 #include "qofquerycore-p.h"
44 #include "Account.h"
45 #include "TransLog.h"
46 #include "gnc-engine.h"
47 #include "SX-book.h"
48 #include "Recurrence.h"
49 #include <gnc-features.h>
50 #include "gnc-uri-utils.h"
51 #include "gnc-filepath-utils.h"
52 #include <gnc-path.h>
53 #include "gnc-locale-utils.h"
54 
55 #include "gnc-prefs.h"
56 
57 #ifdef S_SPLINT_S
58 #include "splint-defs.h"
59 #endif
60 
61 #include <boost/regex.hpp>
62 #include <string>
63 #include <iomanip>
64 
65 #include <qofsession.hpp>
66 #include <gnc-backend-prov.hpp>
67 #include "gnc-backend-dbi.h"
68 #include "gnc-backend-dbi.hpp"
69 
70 #include <gnc-sql-object-backend.hpp>
71 #include "gnc-dbisqlresult.hpp"
72 #include "gnc-dbisqlconnection.hpp"
73 
74 #if LIBDBI_VERSION >= 900
75 #define HAVE_LIBDBI_R 1
76 static dbi_inst dbi_instance = nullptr;
77 #else
78 #define HAVE_LIBDBI_R 0
79 #define HAVE_LIBDBI_TO_LONGLONG 0
80 #endif
81 
82 #define TRANSACTION_NAME "trans"
83 
84 static QofLogModule log_module = G_LOG_DOMAIN;
85 
86 #define FILE_URI_TYPE "file"
87 #define FILE_URI_PREFIX (FILE_URI_TYPE "://")
88 #define SQLITE3_URI_TYPE "sqlite3"
89 #define SQLITE3_URI_PREFIX (SQLITE3_URI_TYPE "://")
90 #define PGSQL_DEFAULT_PORT 5432
91 
92 static void adjust_sql_options (dbi_conn connection);
93 template<DbType Type> bool save_may_clobber_data (dbi_conn conn,
94  const std::string& dbname);
95 
96 template <DbType Type>
98 {
99 public:
100  QofDbiBackendProvider (const char* name, const char* type) :
101  QofBackendProvider {name, type} {}
103  QofDbiBackendProvider operator=(QofDbiBackendProvider&) = delete;
105  QofDbiBackendProvider operator=(QofDbiBackendProvider&&) = delete;
106  ~QofDbiBackendProvider () = default;
108  {
109  return new GncDbiBackend<Type>(nullptr, nullptr);
110  }
111  bool type_check(const char* type) { return true; }
112 };
113 
114 /* ================================================================= */
115 /* ================================================================= */
117 {
118  UriStrings() = default;
119  UriStrings(const std::string& uri);
120  ~UriStrings() = default;
121  std::string basename() const noexcept;
122  const char* dbname() const noexcept;
123  std::string quote_dbname(DbType t) const noexcept;
124  std::string m_protocol;
125  std::string m_host;
126  std::string m_dbname;
127  std::string m_username;
128  std::string m_password;
129  std::string m_basename;
130  int m_portnum;
131 };
132 
133 UriStrings::UriStrings(const std::string& uri)
134 {
135  gchar *scheme, *host, *username, *password, *dbname;
136  int portnum;
137  gnc_uri_get_components(uri.c_str(), &scheme, &host, &portnum, &username,
138  &password, &dbname);
139  m_protocol = std::string{scheme};
140  m_host = std::string{host};
141  if (dbname)
142  m_dbname = std::string{dbname};
143  if (username)
144  m_username = std::string{username};
145  if (password)
146  m_password = std::string{password};
147  m_portnum = portnum;
148  g_free(scheme);
149  g_free(host);
150  g_free(username);
151  g_free(password);
152  g_free(dbname);
153 }
154 
155 std::string
156 UriStrings::basename() const noexcept
157 {
158  return m_protocol + "_" + m_host + "_" + m_username + "_" + m_dbname;
159 }
160 
161 const char*
162 UriStrings::dbname() const noexcept
163 {
164  return m_dbname.c_str();
165 }
166 
167 std::string
168 UriStrings::quote_dbname(DbType t) const noexcept
169 {
170  if (m_dbname.empty())
171  return "";
172  const char quote = (t == DbType::DBI_MYSQL ? '`' : '"');
173  std::string retval(1, quote);
174  retval += m_dbname + quote;
175  return retval;
176 }
177 
178 static void
179 set_options(dbi_conn conn, const PairVec& options)
180 {
181  for (const auto& option : options)
182  {
183  auto opt = option.first.c_str();
184  auto val = option.second.c_str();
185  auto result = dbi_conn_set_option(conn, opt, val);
186  if (result < 0)
187  {
188  const char *msg = nullptr;
189  dbi_conn_error(conn, &msg);
190  PERR("Error setting %s option to %s: %s", opt, val, msg);
191  throw std::runtime_error(msg);
192  }
193  }
194 }
195 
203 template <DbType Type> bool
205  const UriStrings& uri)
206 
207 {
208  PairVec options;
209  options.push_back(std::make_pair("host", uri.m_host));
210  options.push_back(std::make_pair("dbname", uri.m_dbname));
211  options.push_back(std::make_pair("username", uri.m_username));
212  options.push_back(std::make_pair("password", uri.m_password));
213  options.push_back(std::make_pair("encoding", "UTF-8"));
214  try
215  {
216  set_options(conn, options);
217  auto result = dbi_conn_set_option_numeric(conn, "port", uri.m_portnum);
218  if (result < 0)
219  {
220  const char *msg = nullptr;
221  auto err = dbi_conn_error(conn, &msg);
222  PERR("Error (%d) setting port option to %d: %s", err, uri.m_portnum, msg);
223  throw std::runtime_error(msg);
224  }
225  }
226  catch (std::runtime_error& err)
227  {
228  set_error (ERR_BACKEND_SERVER_ERR);
229  return false;
230  }
231 
232  return true;
233 }
234 
235 template <DbType Type> void error_handler(dbi_conn conn, void* data);
236 void error_handler(dbi_conn conn, void* data);
237 
238 template <DbType Type> dbi_conn
239 GncDbiBackend<Type>::conn_setup (PairVec& options, UriStrings& uri)
240 {
241  const char* dbstr = (Type == DbType::DBI_SQLITE ? "sqlite3" :
242  Type == DbType::DBI_MYSQL ? "mysql" : "pgsql");
243 #if HAVE_LIBDBI_R
244  dbi_conn conn = nullptr;
245  if (dbi_instance)
246  conn = dbi_conn_new_r (dbstr, dbi_instance);
247  else
248  PERR ("Attempt to connect with an uninitialized dbi_instance");
249 #else
250  auto conn = dbi_conn_new (dbstr);
251 #endif
252 
253  if (conn == nullptr)
254  {
255  PERR ("Unable to create %s dbi connection", dbstr);
256  set_error (ERR_BACKEND_BAD_URL);
257  return nullptr;
258  }
259 
260  dbi_conn_error_handler (conn, error_handler<Type>, this);
261  if (!uri.m_dbname.empty() &&
262  !set_standard_connection_options(conn, uri))
263  {
264  dbi_conn_close(conn);
265  return nullptr;
266  }
267  if(!options.empty())
268  {
269  try {
270  set_options(conn, options);
271  }
272  catch (std::runtime_error& err)
273  {
274  dbi_conn_close(conn);
275  set_error (ERR_BACKEND_SERVER_ERR);
276  return nullptr;
277  }
278  }
279 
280  return conn;
281 }
282 
283 template <DbType Type>bool
284 GncDbiBackend<Type>::create_database(dbi_conn conn, const char* db)
285 {
286  const char *dbname;
287  const char *dbcreate;
288  if (Type == DbType::DBI_MYSQL)
289  {
290  dbname = "mysql";
291  dbcreate = "CREATE DATABASE %s CHARACTER SET utf8";
292  }
293  else
294  {
295  dbname = "postgres";
296  dbcreate = "CREATE DATABASE %s WITH TEMPLATE template0 ENCODING 'UTF8'";
297  }
298  PairVec options;
299  options.push_back(std::make_pair("dbname", dbname));
300  try
301  {
302  set_options(conn, options);
303  }
304  catch (std::runtime_error& err)
305  {
306  set_error (ERR_BACKEND_SERVER_ERR);
307  return false;
308  }
309 
310  auto result = dbi_conn_connect (conn);
311  if (result < 0)
312  {
313  PERR ("Unable to connect to %s database", dbname);
314  set_error(ERR_BACKEND_SERVER_ERR);
315  return false;
316  }
317  if (Type == DbType::DBI_MYSQL)
318  adjust_sql_options(conn);
319  auto dresult = dbi_conn_queryf (conn, dbcreate, db);
320  if (dresult == nullptr)
321  {
322  PERR ("Unable to create database '%s'\n", db);
323  set_error (ERR_BACKEND_SERVER_ERR);
324  return false;
325  }
326  dbi_result_free (dresult);
327  if (Type == DbType::DBI_PGSQL)
328  {
329  const char *alterdb = "ALTER DATABASE %s SET "
330  "standard_conforming_strings TO on";
331  dbi_result_free (dbi_conn_queryf (conn, alterdb, db));
332  }
333  dbi_conn_close(conn);
334  conn = nullptr;
335  return true;
336 }
337 
338 template <> void
339 error_handler<DbType::DBI_SQLITE> (dbi_conn conn, void* user_data)
340 {
341  const char* msg;
343  static_cast<decltype(dbi_be)>(user_data);
344  int err_num = dbi_conn_error (conn, &msg);
345  /* BADIDX is raised if we attempt to seek outside of a result. We
346  * handle that possibility after checking the return value of the
347  * seek. Having this raise a critical error breaks looping by
348  * testing for the return value of the seek.
349  */
350  if (err_num == DBI_ERROR_BADIDX) return;
351  PERR ("DBI error: %s\n", msg);
352  if (dbi_be->connected())
353  dbi_be->set_dbi_error (ERR_BACKEND_MISC, 0, false);
354 }
355 
356 template <> void
358  const char* new_uri,
359  SessionOpenMode mode)
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  {
379  set_error (ERR_FILEIO_FILE_NOT_FOUND);
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  {
393  set_error (ERR_BACKEND_STORE_EXISTS);
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);
424  set_error (ERR_BACKEND_BAD_URL);
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 }
461 
462 
463 template <> void
464 error_handler<DbType::DBI_MYSQL> (dbi_conn conn, void* user_data)
465 {
467  static_cast<decltype(dbi_be)>(user_data);
468  const char* msg;
469 
470  auto err_num = dbi_conn_error (conn, &msg);
471  /* BADIDX is raised if we attempt to seek outside of a result. We
472  * handle that possibility after checking the return value of the
473  * seek. Having this raise a critical error breaks looping by
474  * testing for the return value of the seek.
475  */
476  if (err_num == DBI_ERROR_BADIDX) return;
477 
478  /* Note: the sql connection may not have been initialized yet
479  * so let's be careful with using it
480  */
481 
482  /* Database doesn't exist. When this error is triggered the
483  * GncDbiSqlConnection may not exist yet either, so don't use it here
484  */
485  if (err_num == 1049) // Database doesn't exist
486  {
487  PINFO ("DBI error: %s\n", msg);
488  dbi_be->set_exists(false);
489  return;
490  }
491 
492  /* All the other error handling code assumes the GncDbiSqlConnection
493  * has been initialized. So let's assert it exits here, otherwise
494  * simply return.
495  */
496  if (!dbi_be->connected())
497  {
498  PINFO ("DBI error: %s\n", msg);
499  PINFO ("Note: GncDbiSqlConnection not yet initialized. Skipping further error processing.");
500  return;
501  }
502 
503  /* Test for other errors */
504  if (err_num == 2006) // Server has gone away
505  {
506  PINFO ("DBI error: %s - Reconnecting...\n", msg);
507  dbi_be->set_dbi_error (ERR_BACKEND_CONN_LOST, 1, true);
508  dbi_be->retry_connection(msg);
509  }
510  else if (err_num == 2003) // Unable to connect
511  {
512  dbi_be->set_dbi_error (ERR_BACKEND_CANT_CONNECT, 1, true);
513  dbi_be->retry_connection (msg);
514  }
515  else if (err_num == 1007) //Database exists
516  {
517  dbi_be->set_exists(true);
518  return;
519  }
520 
521  else // Any other error
522  {
523  PERR ("DBI error: %s\n", msg);
524  dbi_be->set_dbi_error (ERR_BACKEND_MISC, 0, FALSE);
525  }
526 }
527 
528 #define SQL_OPTION_TO_REMOVE "NO_ZERO_DATE"
529 
530 /* Given an sql_options string returns a copy of the string adjusted as
531  * necessary. In particular if string the contains SQL_OPTION_TO_REMOVE it is
532  * removed along with comma separator.
533  */
534 std::string
535 adjust_sql_options_string(const std::string& str)
536 {
537 /* Regex that finds the SQL_OPTION_TO_REMOVE as the first, last, or middle of a
538  * comma-delimited list.
539  */
540  static const boost::regex reg{"(?:," SQL_OPTION_TO_REMOVE "$|\\b"
541  SQL_OPTION_TO_REMOVE "\\b,?)"};
542  return regex_replace(str, reg, std::string{""});
543 }
544 
545 /* checks mysql sql_options and adjusts if necessary */
546 static void
547 adjust_sql_options (dbi_conn connection)
548 {
549  dbi_result result = dbi_conn_query( connection, "SELECT @@sql_mode");
550  if (result == nullptr)
551  {
552  const char* errmsg;
553  int err = dbi_conn_error(connection, &errmsg);
554  PERR("Unable to read sql_mode %d : %s", err, errmsg);
555  return;
556  }
557  dbi_result_first_row(result);
558  std::string str{dbi_result_get_string_idx(result, 1)};
559  dbi_result_free(result);
560  if (str.empty())
561  {
562  const char* errmsg;
563  int err = dbi_conn_error(connection, &errmsg);
564  if (err)
565  PERR("Unable to get sql_mode %d : %s", err, errmsg);
566  else
567  PINFO("Sql_mode isn't set.");
568  return;
569  }
570  PINFO("Initial sql_mode: %s", str.c_str());
571  if(str.find(SQL_OPTION_TO_REMOVE) != std::string::npos)
572  str = adjust_sql_options_string(str);
573 
574  //https://bugs.gnucash.org/show_bug.cgi?id=798112
575  const char* backslash_option{"NO_BACKSLASH_ESCAPES"};
576 
577  if (str.find(backslash_option) == std::string::npos)
578  {
579  if (!str.empty())
580  str.append(",");
581  str.append(backslash_option);
582  }
583 
584  PINFO("Setting sql_mode to %s", str.c_str());
585  std::string set_str{"SET sql_mode='" + std::move(str) + "'"};
586  dbi_result set_result = dbi_conn_query(connection,
587  set_str.c_str());
588  if (set_result)
589  {
590  dbi_result_free(set_result);
591  }
592  else
593  {
594  const char* errmsg;
595  int err = dbi_conn_error(connection, &errmsg);
596  PERR("Unable to set sql_mode %d : %s", err, errmsg);
597  }
598 }
599 
600 template <DbType Type> bool
601 drop_database(dbi_conn conn, const UriStrings& uri)
602 {
603  const char *root_db;
604  if (Type == DbType::DBI_PGSQL)
605  {
606  root_db = "template1";
607  }
608  else if (Type == DbType::DBI_MYSQL)
609  {
610  root_db = "mysql";
611  }
612  else
613  {
614  PERR ("Unknown database type, can't proceed.");
615  LEAVE("Error");
616  return false;
617  }
618  if (dbi_conn_select_db (conn, root_db) == -1)
619  {
620  PERR ("Failed to switch out of %s, drop will fail.",
621  uri.quote_dbname(Type).c_str());
622  LEAVE ("Error");
623  return false;
624  }
625  auto result = dbi_conn_queryf (conn, "DROP DATABASE %s",
626  uri.quote_dbname(Type).c_str());
627  if (!result)
628  {
629  PERR ("Failed to drop database %s prior to recreating it."
630  "Proceeding would combine old and new data.",
631  uri.quote_dbname(Type).c_str());
632  LEAVE ("Error");
633  return false;
634  }
635  dbi_result_free (result);
636  return true;
637 }
638 
639 template <DbType Type> void
640 GncDbiBackend<Type>::session_begin (QofSession* session, const char* new_uri,
641  SessionOpenMode mode)
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  {
700  set_error (ERR_BACKEND_STORE_EXISTS);
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());
714  set_error (ERR_BACKEND_CANT_CONNECT);
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());
722  set_error(ERR_BACKEND_NO_SUCH_DB);
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());
743  set_error (ERR_BACKEND_SERVER_ERR);
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 }
779 
780 template<> void
781 error_handler<DbType::DBI_PGSQL> (dbi_conn conn, void* user_data)
782 {
784  static_cast<decltype(dbi_be)>(user_data);
785  const char* msg;
786 
787  auto err_num = dbi_conn_error (conn, &msg);
788  /* BADIDX is raised if we attempt to seek outside of a result. We
789  * handle that possibility after checking the return value of the
790  * seek. Having this raise a critical error breaks looping by
791  * testing for the return value of the seek.
792  */
793  if (err_num == DBI_ERROR_BADIDX) return;
794  if (g_str_has_prefix (msg, "FATAL: database") &&
795  g_str_has_suffix (msg, "does not exist\n"))
796  {
797  PINFO ("DBI error: %s\n", msg);
798  dbi_be->set_exists(false);
799  }
800  else if (g_strrstr (msg,
801  "server closed the connection unexpectedly")) // Connection lost
802  {
803  if (!dbi_be->connected())
804  {
805  PWARN ("DBI Error: Connection lost, connection pointer invalid");
806  return;
807  }
808  PINFO ("DBI error: %s - Reconnecting...\n", msg);
809  dbi_be->set_dbi_error (ERR_BACKEND_CONN_LOST, 1, true);
810  dbi_be->retry_connection(msg);
811  }
812  else if (g_str_has_prefix (msg, "connection pointer is NULL") ||
813  g_str_has_prefix (msg, "could not connect to server")) // No connection
814  {
815 
816  if (!dbi_be->connected())
817  qof_backend_set_error(reinterpret_cast<QofBackend*>(dbi_be),
819  else
820  {
821  dbi_be->set_dbi_error(ERR_BACKEND_CANT_CONNECT, 1, true);
822  dbi_be->retry_connection (msg);
823  }
824  }
825  else
826  {
827  PERR ("DBI error: %s\n", msg);
828  if (dbi_be->connected())
829  dbi_be->set_dbi_error (ERR_BACKEND_MISC, 0, false);
830  }
831 }
832 
833 /* ================================================================= */
834 
835 template <DbType Type> void
837 {
838  ENTER (" ");
839 
840  finalize_version_info ();
841  connect(nullptr);
842 
843  LEAVE (" ");
844 }
845 
846 template <DbType Type>
848 {
849  /* Stop transaction logging */
850  xaccLogSetBaseName (nullptr);
851 }
852 
853 /* ================================================================= */
854 
855 /* GNUCASH_RESAVE_VERSION indicates the earliest database version
856  * compatible with this version of Gnucash; the stored value is the
857  * earliest version of Gnucash conpatible with the database. If the
858  * GNUCASH_RESAVE_VERSION for this Gnucash is newer than the Gnucash
859  * version which created the database, a resave is offered. If the
860  * version of this Gnucash is older than the saved resave version,
861  * then the database will be loaded read-only. A resave will update
862  * both values to match this version of Gnucash.
863  */
864 template <DbType Type> void
865 GncDbiBackend<Type>::load (QofBook* book, QofBackendLoadType loadType)
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
875  init_version_info ();
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. */
890  set_error(ERR_SQL_DB_TOO_OLD);
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  */
898  set_error(ERR_SQL_DB_TOO_NEW);
899  }
900 
901 
902  LEAVE ("");
903 }
904 
905 /* ================================================================= */
906 /* This is used too early to call GncDbiProvider::get_table_list(). */
907 template <DbType T> bool
908 save_may_clobber_data (dbi_conn conn, const std::string& dbname)
909 {
910 
911  /* Data may be clobbered iff the number of tables != 0 */
912  auto result = dbi_conn_get_table_list (conn, dbname.c_str(), nullptr);
913  bool retval = false;
914  if (result)
915  {
916  retval = dbi_result_get_numrows (result) > 0;
917  dbi_result_free (result);
918  }
919  return retval;
920 }
921 
922 template <> bool
923 save_may_clobber_data <DbType::DBI_PGSQL>(dbi_conn conn,
924  const std::string& dbname)
925 {
926 
927  /* Data may be clobbered iff the number of tables != 0 */
928  const char* query = "SELECT relname FROM pg_class WHERE relname !~ '^(pg|sql)_' AND relkind = 'r' ORDER BY relname";
929  auto result = dbi_conn_query (conn, query);
930  bool retval = false;
931  if (result)
932  {
933  retval = dbi_result_get_numrows (result) > 0;
934  dbi_result_free (result);
935  }
936  return retval;
937 }
938 
939 
948 template <DbType Type> void
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 }
986 /* MySQL commits the transaction and all savepoints after the first CREATE
987  * TABLE, crashing when we try to RELEASE SAVEPOINT because the savepoint
988  * doesn't exist after the commit. We must run without a wrapping transaction in
989  * that case.
990  */
991 template <> void
993 {
994  auto conn = dynamic_cast<GncDbiSqlConnection*>(m_conn);
995 
996  g_return_if_fail (conn != nullptr);
997  g_return_if_fail (book != nullptr);
998 
999  ENTER ("book=%p, primary=%p", book, m_book);
1000  if (!conn->table_operation (TableOpType::backup))
1001  {
1002  set_error(ERR_BACKEND_SERVER_ERR);
1003  conn->table_operation (TableOpType::rollback);
1004  LEAVE ("Failed to rename tables");
1005  return;
1006  }
1007  if (!conn->drop_indexes())
1008  {
1009  conn->table_operation (TableOpType::rollback);
1010  set_error (ERR_BACKEND_SERVER_ERR);
1011  set_message("Failed to drop indexes");
1012  LEAVE ("Failed to drop indexes");
1013  return;
1014  }
1015 
1016  sync(m_book);
1017  if (check_error())
1018  {
1019  conn->table_operation (TableOpType::rollback);
1020  LEAVE ("Failed to create new database tables");
1021  return;
1022  }
1023  conn->table_operation (TableOpType::drop_backup);
1024  LEAVE ("book=%p", m_book);
1025 }
1026 /* ================================================================= */
1027 
1028 /*
1029  * Checks to see whether the file is an sqlite file or not
1030  *
1031  */
1032 template<> bool
1034 {
1035  FILE* f;
1036  gchar buf[51]{};
1037  G_GNUC_UNUSED size_t chars_read;
1038  gint status;
1039  gchar* filename;
1040 
1041  // BAD if the path is null
1042  g_return_val_if_fail (uri != nullptr, FALSE);
1043 
1044  filename = gnc_uri_get_path (uri);
1045  f = g_fopen (filename, "r");
1046  g_free (filename);
1047 
1048  // OK if the file doesn't exist - new file
1049  if (f == nullptr)
1050  {
1051  PINFO ("doesn't exist (errno=%d) -> DBI", errno);
1052  return TRUE;
1053  }
1054 
1055  // OK if file has the correct header
1056  chars_read = fread (buf, sizeof (buf) - 1, 1, f);
1057  status = fclose (f);
1058  if (status < 0)
1059  {
1060  PERR ("Error in fclose(): %d\n", errno);
1061  }
1062  if (g_str_has_prefix (buf, "SQLite format 3"))
1063  {
1064  PINFO ("has SQLite format string -> DBI");
1065  return TRUE;
1066  }
1067  PINFO ("exists, does not have SQLite format string -> not DBI");
1068 
1069  // Otherwise, BAD
1070  return FALSE;
1071 }
1072 
1073 void
1075 {
1076  const char* driver_dir;
1077  int num_drivers;
1078  gboolean have_sqlite3_driver = FALSE;
1079  gboolean have_mysql_driver = FALSE;
1080  gboolean have_pgsql_driver = FALSE;
1081 
1082  /* Initialize libdbi and see which drivers are available. Only register qof backends which
1083  have drivers available. */
1084  driver_dir = g_getenv ("GNC_DBD_DIR");
1085  if (driver_dir == nullptr)
1086  {
1087  PINFO ("GNC_DBD_DIR not set: using libdbi built-in default\n");
1088  }
1089 
1090  /* dbi_initialize returns -1 in case of errors */
1091 #if HAVE_LIBDBI_R
1092  if (dbi_instance)
1093  return;
1094  num_drivers = dbi_initialize_r (driver_dir, &dbi_instance);
1095 #else
1096  num_drivers = dbi_initialize (driver_dir);
1097 #endif
1098  if (num_drivers <= 0)
1099  {
1100 #if HAVE_LIBDBI_R
1101  if (dbi_instance)
1102  {
1103  dbi_shutdown_r (dbi_instance);
1104  dbi_instance = nullptr;
1105  }
1106 #endif
1107  gchar *libdir = gnc_path_get_libdir ();
1108  gchar *dir = g_build_filename (libdir, "dbd", nullptr);
1109  g_free (libdir);
1110 #if HAVE_LIBDBI_R
1111  num_drivers = dbi_initialize_r (dir, &dbi_instance);
1112 #else
1113  num_drivers = dbi_initialize (dir);
1114 #endif
1115  g_free (dir);
1116  }
1117  if (num_drivers <= 0)
1118  {
1119  PWARN ("No DBD drivers found\n");
1120  }
1121  else
1122  {
1123  dbi_driver driver = nullptr;
1124  PINFO ("%d DBD drivers found\n", num_drivers);
1125 
1126  do
1127  {
1128 #if HAVE_LIBDBI_R
1129  driver = dbi_driver_list_r (driver, dbi_instance);
1130 #else
1131  driver = dbi_driver_list (driver);
1132 #endif
1133 
1134  if (driver != nullptr)
1135  {
1136  const gchar* name = dbi_driver_get_name (driver);
1137 
1138  PINFO ("Driver: %s\n", name);
1139  if (strcmp (name, "sqlite3") == 0)
1140  {
1141  have_sqlite3_driver = TRUE;
1142  }
1143  else if (strcmp (name, "mysql") == 0)
1144  {
1145  have_mysql_driver = TRUE;
1146  }
1147  else if (strcmp (name, "pgsql") == 0)
1148  {
1149  have_pgsql_driver = TRUE;
1150  }
1151  }
1152  }
1153  while (driver != nullptr);
1154  }
1155 
1156  if (have_sqlite3_driver)
1157  {
1158  const char* name = "GnuCash Libdbi (SQLITE3) Backend";
1159  auto prov = QofBackendProvider_ptr(new QofDbiBackendProvider<DbType::DBI_SQLITE>{name, FILE_URI_TYPE});
1160  qof_backend_register_provider(std::move(prov));
1161  prov = QofBackendProvider_ptr(new QofDbiBackendProvider<DbType::DBI_SQLITE>{name, SQLITE3_URI_TYPE});
1162  qof_backend_register_provider(std::move(prov));
1163  }
1164 
1165  if (have_mysql_driver)
1166  {
1167  const char *name = "GnuCash Libdbi (MYSQL) Backend";
1168  auto prov = QofBackendProvider_ptr(new QofDbiBackendProvider<DbType::DBI_MYSQL>{name, "mysql"});
1169  qof_backend_register_provider(std::move(prov));
1170  }
1171 
1172  if (have_pgsql_driver)
1173  {
1174  const char* name = "GnuCash Libdbi (POSTGRESQL) Backend";
1175  auto prov = QofBackendProvider_ptr(new QofDbiBackendProvider<DbType::DBI_PGSQL>{name, "postgres"});
1176  qof_backend_register_provider(std::move(prov));
1177  }
1178 
1179  /* If needed, set log level to DEBUG so that SQl statements will be put into
1180  the gnucash.trace file. */
1181  /* qof_log_set_level( log_module, QOF_LOG_DEBUG ); */
1182 }
1183 
1184 #ifndef GNC_NO_LOADABLE_MODULES
1185 G_MODULE_EXPORT void
1187 {
1189 }
1190 
1191 G_MODULE_EXPORT void
1192 qof_backend_module_finalize (void)
1193 {
1195 }
1196 #endif /* GNC_NO_LOADABLE_MODULES */
1197 
1198 void
1200 {
1201 #if HAVE_LIBDBI_R
1202  if (dbi_instance)
1203  {
1204  dbi_shutdown_r (dbi_instance);
1205  dbi_instance = nullptr;
1206  }
1207 #else
1208  dbi_shutdown ();
1209 #endif
1210 }
1211 
1212 /* --------------------------------------------------------- */
1213 
1214 static void
1215 log_failed_field(dbi_result result, const char* fieldname)
1216 {
1217  auto idx = dbi_result_get_field_idx(result, fieldname);
1218  if (dbi_result_field_is_null_idx(result, idx))
1219  PERR("Result field %s is NULL", fieldname);
1220  else
1221  {
1222  auto type = dbi_result_get_field_type_idx(result, idx);
1223  auto attribs = dbi_result_get_field_attribs_idx(result, idx);
1224  PERR("Result field %s has type %d and attribs %d",
1225  fieldname, type, attribs);
1226  }
1227 }
1228 
1238 static GncDbiTestResult
1239 dbi_library_test (dbi_conn conn)
1240 {
1241  int64_t testlonglong = -9223372036854775807LL, resultlonglong = 0;
1242  uint64_t testulonglong = 9223372036854775807LLU, resultulonglong = 0;
1243  double testdouble = 1.7976921348623157E+307, resultdouble = 0.0;
1244  dbi_result result;
1245  GncDbiTestResult retval = GNC_DBI_PASS;
1246 
1247  result = dbi_conn_query (conn, "CREATE TEMPORARY TABLE numtest "
1248  "( test_int BIGINT, test_unsigned BIGINT,"
1249  " test_double FLOAT8 )");
1250  if (result == nullptr)
1251  {
1252  PWARN ("Test_DBI_Library: Create table failed");
1253  return GNC_DBI_FAIL_SETUP;
1254  }
1255  dbi_result_free (result);
1256  std::stringstream querystr;
1257  querystr << "INSERT INTO numtest VALUES (" << testlonglong <<
1258  ", " << testulonglong << ", " << std::setprecision(12) <<
1259  testdouble << ")";
1260  auto query = querystr.str();
1261  result = dbi_conn_query (conn, query.c_str());
1262  if (result == nullptr)
1263  {
1264  PWARN ("Test_DBI_Library: Failed to insert test row into table");
1265  return GNC_DBI_FAIL_SETUP;
1266  }
1267  dbi_result_free (result);
1268  auto locale = gnc_push_locale (LC_NUMERIC, "C");
1269  result = dbi_conn_query (conn, "SELECT * FROM numtest");
1270  if (result == nullptr || !dbi_result_get_numrows(result))
1271  {
1272  const char* errmsg;
1273  dbi_conn_error (conn, &errmsg);
1274  PWARN ("Test_DBI_Library: Failed to retrieve test row into table: %s",
1275  errmsg);
1276  dbi_result_free (result);
1277  dbi_result_free (dbi_conn_query (conn, "DROP TABLE numtest"));
1278  gnc_pop_locale (LC_NUMERIC, locale);
1279  return GNC_DBI_FAIL_SETUP;
1280  }
1281  while (dbi_result_next_row (result))
1282  {
1283  resultlonglong = dbi_result_get_longlong (result, "test_int");
1284  if (!resultlonglong)
1285  log_failed_field(result, "test_int");
1286  resultulonglong = dbi_result_get_ulonglong (result, "test_unsigned");
1287  if (!resultulonglong)
1288  log_failed_field(result, "test_unsigned");
1289  resultdouble = dbi_result_get_double (result, "test_double");
1290  if (!resultdouble)
1291  log_failed_field(result, "test_double");
1292  }
1293  dbi_result_free (result);
1294  dbi_result_free (dbi_conn_query (conn, "DROP TABLE numtest"));
1295  gnc_pop_locale (LC_NUMERIC, locale);
1296  if (testlonglong != resultlonglong)
1297  {
1298  PWARN ("Test_DBI_Library: LongLong Failed %" PRId64 " != % " PRId64,
1299  testlonglong, resultlonglong);
1300  retval = GNC_DBI_FAIL_TEST;
1301  }
1302  if (testulonglong != resultulonglong)
1303  {
1304  PWARN ("Test_DBI_Library: Unsigned longlong Failed %" PRIu64 " != %"
1305  PRIu64, testulonglong, resultulonglong);
1306  retval = GNC_DBI_FAIL_TEST;
1307  }
1308  /* A bug in libdbi stores only 7 digits of precision */
1309  if (testdouble >= resultdouble + 0.000001e307 ||
1310  testdouble <= resultdouble - 0.000001e307)
1311  {
1312  PWARN ("Test_DBI_Library: Double Failed %17e != %17e",
1313  testdouble, resultdouble);
1314  retval = GNC_DBI_FAIL_TEST;
1315  }
1316  return retval;
1317 }
1318 
1319 template <DbType Type> bool
1321 {
1322  auto result = dbi_library_test (conn);
1323  switch (result)
1324  {
1325  case GNC_DBI_PASS:
1326  break;
1327 
1328  case GNC_DBI_FAIL_SETUP:
1329  set_error(ERR_SQL_DBI_UNTESTABLE);
1330  set_message ("DBI library large number test incomplete");
1331  break;
1332 
1333  case GNC_DBI_FAIL_TEST:
1334  set_error (ERR_SQL_BAD_DBI);
1335  set_message ("DBI library fails large number test");
1336  break;
1337  }
1338  return result == GNC_DBI_PASS;
1339 }
1340 
1341 /* ========================== END OF FILE ===================== */
Lost connection to server.
Definition: qofbackend.h:65
QofBackend * create_backend(void)
Return a new, fully initialized backend.
load and save data to SQL via libdbi
void set_dbi_error(QofBackendError error, unsigned int repeat, bool retry) noexcept
FIXME: Just a pass-through to m_conn:
not found / no such file
Definition: qofbackend.h:92
#define G_LOG_DOMAIN
Functions providing the SX List as a plugin page.
#define PINFO(format, args...)
Print an informational note.
Definition: qoflog.h:256
void qof_backend_register_provider(QofBackendProvider_ptr &&prov)
Let the system know about a new provider of backends.
Definition: qofsession.cpp:91
void qof_backend_set_error(QofBackend *qof_be, QofBackendError err)
Set the error on the specified QofBackend.
void gnc_features_set_used(QofBook *book, const gchar *feature)
Indicate that the current book uses the given feature.
bool type_check(const char *type)
Distinguish two providers with same access method.
database is old and needs upgrading
Definition: qofbackend.h:113
gchar * gnc_uri_get_path(const gchar *uri)
Extracts the path part from a uri.
G_MODULE_EXPORT void qof_backend_module_init(void)
This is the standardized initialization function of a qof_backend GModule, but compiling this can be ...
Can&#39;t parse url.
Definition: qofbackend.h:62
Create a new store at the URI.
Definition: qofsession.h:126
void gnc_uri_get_components(const gchar *uri, gchar **scheme, gchar **hostname, gint32 *port, gchar **username, gchar **password, gchar **path)
Converts a uri in separate components.
void load(QofBook *, QofBackendLoadType) override
Load the contents of an SQL database into a book.
#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
void gnc_module_finalize_backend_dbi(void)
Shutdown function which can be used when this module is statically linked into the application...
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
void safe_sync(QofBook *) override
Safely resave a database by renaming all of its tables, recreating everything, and then dropping the ...
database is newer, we can&#39;t write to it
Definition: qofbackend.h:114
Account handling public routines.
void load(QofBook *, QofBackendLoadType) override
Load the minimal set of application data needed for the application to be operable at initial startup...
void gnc_module_init_backend_dbi(void)
Initialization function which can be used when this module is statically linked into the application...
Anchor Scheduled Transaction info in a book.
undetermined error
Definition: qofbackend.h:79
LibDBI has numeric errors.
Definition: qofbackend.h:116
All type declarations for the whole Gnucash engine.
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
Generic api to store and retrieve preferences.
Encapsulate a libdbi dbi_conn connection.
API for the transaction logger.
QofBook reference.
Definition: qofbook-p.hpp:46
SessionOpenMode
Mode for opening sessions.
Definition: qofsession.h:120
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
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
Utility functions for convert uri in separate components and back.
could not complete test for LibDBI bug
Definition: qofbackend.h:117
void session_begin(QofSession *, const char *, SessionOpenMode) override
Open the file or connect to the server.
File path resolution utility functions.
Open will fail if the URI doesn&#39;t exist or is locked.
Definition: qofsession.h:124
Utility functions for file access.