GnuCash de0bfde+
Loading...
Searching...
No Matches
gnc-dbisqlconnection.cpp
1/********************************************************************
2 * gnc-dbisqlconnection.cpp: Encapsulate libdbi dbi_conn *
3 * *
4 * Copyright 2016 John Ralls <jralls@ceridwen.us> *
5 * *
6 * This program is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU General Public License as *
8 * published by the Free Software Foundation; either version 2 of *
9 * the License, or (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License*
17 * along with this program; if not, contact: *
18 * *
19 * Free Software Foundation Voice: +1-617-542-5942 *
20 * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 *
21 * Boston, MA 02110-1301, USA gnu@gnu.org *
22\********************************************************************/
23
24#include <guid.hpp>
25#include <config.h>
26#include <platform.h>
27#include <gnc-locale-utils.h>
28
29#include <string>
30#include <regex>
31#include <sstream>
32
33#include "gnc-dbisqlconnection.hpp"
34
35static QofLogModule log_module = G_LOG_DOMAIN;
36// gnc-dbiproviderimpl.hpp has templates that need log_module defined.
37#include "gnc-dbiproviderimpl.hpp"
38
39static const unsigned int DBI_MAX_CONN_ATTEMPTS = 5;
40const std::string lock_table = "gnclock";
41
42/* --------------------------------------------------------- */
43class GncDbiSqlStatement : public GncSqlStatement
44{
45public:
46 GncDbiSqlStatement(const std::string& sql) :
47 m_sql {sql} {}
48 ~GncDbiSqlStatement() {}
49 const char* to_sql() const override;
50 void add_where_cond(QofIdTypeConst, const PairVec&) override;
51
52private:
53 std::string m_sql;
54};
55
56
57const char*
58GncDbiSqlStatement::to_sql() const
59{
60 return m_sql.c_str();
61}
62
63void
64GncDbiSqlStatement::add_where_cond(QofIdTypeConst type_name,
65 const PairVec& col_values)
66{
67 m_sql += " WHERE ";
68 for (auto colpair : col_values)
69 {
70 if (colpair != *col_values.begin())
71 m_sql += " AND ";
72 if (colpair.second == "NULL")
73 m_sql += colpair.first + " IS " + colpair.second;
74 else
75 m_sql += colpair.first + " = " + colpair.second;
76 }
77}
78
79GncDbiSqlConnection::GncDbiSqlConnection (DbType type, QofBackend* qbe,
80 dbi_conn conn, SessionOpenMode mode) :
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}
100
101bool
102GncDbiSqlConnection::lock_database (bool break_lock)
103{
104 const char *errstr;
105 /* Protect everything with a single transaction to prevent races */
106 if (!begin_transaction())
107 return false;
108 auto tables = m_provider->get_table_list(m_conn, lock_table);
109 if (tables.empty())
110 {
111 auto result = dbi_conn_queryf (m_conn,
112 "CREATE TABLE %s ( Hostname varchar(%d), PID int )",
113 lock_table.c_str(),
114 GNC_HOST_NAME_MAX);
115 if (result)
116 {
117 dbi_result_free (result);
118 result = nullptr;
119 }
120 if (dbi_conn_error (m_conn, &errstr))
121 {
122 PERR ("Error %s creating lock table", errstr);
124 return false;
125 }
126 }
127
128 /* Check for an existing entry; delete it if break_lock is true, otherwise fail */
129 char hostname[ GNC_HOST_NAME_MAX + 1 ];
130 auto result = dbi_conn_queryf (m_conn, "SELECT * FROM %s",
131 lock_table.c_str());
132 if (result && dbi_result_get_numrows (result))
133 {
134 dbi_result_free (result);
135 result = nullptr;
136 if (!break_lock)
137 {
139 /* FIXME: After enhancing the qof_backend_error mechanism, report in the dialog what is the hostname of the machine holding the lock. */
141 return false;
142 }
143 result = dbi_conn_queryf (m_conn, "DELETE FROM %s", lock_table.c_str());
144 if (!result)
145 {
147 m_qbe->set_message("Failed to delete lock record");
149 return false;
150 }
151 dbi_result_free (result);
152 result = nullptr;
153 }
154 else if (result)
155 {
156 dbi_result_free (result);
157 result = nullptr;
158 }
159 /* Add an entry and commit the transaction */
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 ());
165 if (!result)
166 {
168 m_qbe->set_message("Failed to create lock record");
170 return false;
171 }
172 dbi_result_free (result);
173 return commit_transaction();
174}
175
176void
177GncDbiSqlConnection::unlock_database ()
178{
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);
183
184 auto tables = m_provider->get_table_list (m_conn, lock_table);
185 if (tables.empty())
186 {
187 PWARN ("No lock table in database, so not unlocking it.");
188 return;
189 }
190 if (begin_transaction())
191 {
192 /* Delete the entry if it's our hostname and PID */
193 char hostname[ GNC_HOST_NAME_MAX + 1 ];
194
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(),
200 hostname,
201 (int)GETPID ());
202 if (result && dbi_result_get_numrows (result))
203 {
204 if (result)
205 {
206 dbi_result_free (result);
207 result = nullptr;
208 }
209 result = dbi_conn_queryf (m_conn, "DELETE FROM %s",
210 lock_table.c_str());
211 if (!result)
212 {
213 PERR ("Failed to delete the lock entry");
214 m_qbe->set_error (ERR_BACKEND_SERVER_ERR);
216 return;
217 }
218 else
219 {
220 dbi_result_free (result);
221 result = nullptr;
222 }
224 return;
225 }
226 if (result)
227 dbi_result_free (result);
229 PWARN ("There was no lock entry in the Lock table");
230 return;
231 }
232 PWARN ("Unable to get a lock on LOCK, so failed to clear the lock entry.");
233 m_qbe->set_error (ERR_BACKEND_SERVER_ERR);
234}
235
236bool
237GncDbiSqlConnection::check_and_rollback_failed_save()
238{
239 auto backup_tables = m_provider->get_table_list(m_conn, "%back");
240 if (backup_tables.empty())
241 return true;
242 auto merge_tables = m_provider->get_table_list(m_conn, "%_merge");
243 if (!merge_tables.empty())
244 {
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.");
249 return false;
250 }
251 return table_operation(recover);
252}
253
254GncDbiSqlConnection::~GncDbiSqlConnection()
255{
256 if (m_conn)
257 {
258 unlock_database();
259 dbi_conn_close(m_conn);
260 m_conn = nullptr;
261 }
262}
263
264GncSqlResultPtr
265GncDbiSqlConnection::execute_select_statement (const GncSqlStatementPtr& stmt)
266 noexcept
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}
289
290int
292 noexcept
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}
326
327GncSqlStatementPtr
328GncDbiSqlConnection::create_statement_from_sql (const std::string& sql)
329 const noexcept
330{
331 return std::unique_ptr<GncSqlStatement>{new GncDbiSqlStatement (sql)};
332}
333
334bool
335GncDbiSqlConnection::does_table_exist (const std::string& table_name)
336 const noexcept
337{
338 return ! m_provider->get_table_list(m_conn, table_name).empty();
339}
340
341bool
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}
385
386bool
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}
418
419bool
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}
451
452
453bool
454GncDbiSqlConnection::create_table (const std::string& table_name,
455 const ColVec& info_vec) const noexcept
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}
485
486static std::string
487create_index_ddl (const GncSqlConnection* conn, const std::string& index_name,
488 const std::string& table_name, const EntryVec& col_table)
489{
490 std::string ddl;
491 ddl += "CREATE INDEX " + index_name + " ON " + table_name + "(";
492 for (const auto& table_row : col_table)
493 {
494 if (table_row != *col_table.begin())
495 {
496 ddl += ", ";
497 }
498 ddl += table_row->name();
499 }
500 ddl += ")";
501 return ddl;
502}
503
504bool
505GncDbiSqlConnection::create_index(const std::string& index_name,
506 const std::string& table_name,
507 const EntryVec& col_table) const noexcept
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}
523
524bool
525GncDbiSqlConnection::add_columns_to_table(const std::string& table_name,
526 const ColVec& info_vec)
527 const noexcept
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}
544
545std::string
546GncDbiSqlConnection::quote_string (const std::string& unquoted_str)
547 const noexcept
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}
559
560
564bool
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}
581
582bool
583GncDbiSqlConnection::retry_connection(const char* msg)
584 noexcept
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}
610
611bool
612GncDbiSqlConnection::rename_table(const std::string& old_name,
613 const std::string& new_name)
614{
615 std::string sql = "ALTER TABLE " + old_name + " RENAME TO " + new_name;
616 auto stmt = create_statement_from_sql(sql);
617 return execute_nonselect_statement(stmt) >= 0;
618}
619
620bool
621GncDbiSqlConnection::drop_table(const std::string& table)
622{
623 std::string sql = "DROP TABLE " + table;
624 auto stmt = create_statement_from_sql(sql);
625 return execute_nonselect_statement(stmt) >= 0;
626}
627
628bool
629GncDbiSqlConnection::merge_tables(const std::string& table,
630 const std::string& other)
631{
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);
636 if (execute_nonselect_statement(stmt) < 0)
637 return false;
638 sql = std::string("DELETE FROM ") + table;
639 stmt = create_statement_from_sql(sql);
640 if (execute_nonselect_statement(stmt) < 0)
641 return false;
642 sql = std::string("INSERT INTO ") + table +
643 " SELECT * FROM " + merge_table;
644 stmt = create_statement_from_sql(sql);
645 if (execute_nonselect_statement(stmt) < 0)
646 return false;
647 if (!drop_table(merge_table))
648 return false;
649 return drop_table(other);
650}
651
676
677bool
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}
744
745bool
746GncDbiSqlConnection::drop_indexes() noexcept
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}
761
762std::string
763GncDbiSqlConnection::add_columns_ddl(const std::string& table_name,
764 const ColVec& info_vec) const noexcept
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}
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 add_columns_to_table(const std::string &, const ColVec &) const noexcept override
Returns TRUE if successful, FALSE if error.
int execute_nonselect_statement(const GncSqlStatementPtr &) noexcept override
Returns 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 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 verify() noexcept override
Check if the dbi connection is valid.
bool rollback_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.
Encapsulate the connection to the database.
SQL statement provider.
void qof_backend_set_error(QofBackend *qof_be, QofBackendError err)
Set the error on the specified QofBackend.
SessionOpenMode
Mode for opening sessions.
Definition qofsession.h:121
@ ERR_BACKEND_LOCKED
in use by another user (ETXTBSY)
Definition qofbackend.h:66
@ ERR_BACKEND_SERVER_ERR
error in response from server
Definition qofbackend.h:71
@ ERR_BACKEND_DATA_CORRUPT
data in db is corrupt
Definition qofbackend.h:70
@ 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
const gchar * QofIdTypeConst
QofIdTypeConst declaration.
Definition qofid.h:82
#define PINFO(format, args...)
Print an informational note.
Definition qoflog.h:256
#define DEBUG(format, args...)
Print a debugging message.
Definition qoflog.h:264
#define PERR(format, args...)
Log a serious error.
Definition qoflog.h:244
#define PWARN(format, args...)
Log a warning.
Definition qoflog.h:250