Bitcoin Core  24.1.0
P2P Digital Currency
sqlite.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <wallet/sqlite.h>
6 
7 #include <chainparams.h>
8 #include <crypto/common.h>
9 #include <logging.h>
10 #include <sync.h>
11 #include <util/strencodings.h>
12 #include <util/system.h>
13 #include <util/translation.h>
14 #include <wallet/db.h>
15 
16 #include <sqlite3.h>
17 #include <stdint.h>
18 
19 #include <optional>
20 #include <utility>
21 #include <vector>
22 
23 namespace wallet {
24 static constexpr int32_t WALLET_SCHEMA_VERSION = 0;
25 
27 static int g_sqlite_count GUARDED_BY(g_sqlite_mutex) = 0;
28 
29 static void ErrorLogCallback(void* arg, int code, const char* msg)
30 {
31  // From sqlite3_config() documentation for the SQLITE_CONFIG_LOG option:
32  // "The void pointer that is the second argument to SQLITE_CONFIG_LOG is passed through as
33  // the first parameter to the application-defined logger function whenever that function is
34  // invoked."
35  // Assert that this is the case:
36  assert(arg == nullptr);
37  LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg);
38 }
39 
40 static bool BindBlobToStatement(sqlite3_stmt* stmt,
41  int index,
43  const std::string& description)
44 {
45  int res = sqlite3_bind_blob(stmt, index, blob.data(), blob.size(), SQLITE_STATIC);
46  if (res != SQLITE_OK) {
47  LogPrintf("Unable to bind %s to statement: %s\n", description, sqlite3_errstr(res));
48  sqlite3_clear_bindings(stmt);
49  sqlite3_reset(stmt);
50  return false;
51  }
52 
53  return true;
54 }
55 
56 static std::optional<int> ReadPragmaInteger(sqlite3* db, const std::string& key, const std::string& description, bilingual_str& error)
57 {
58  std::string stmt_text = strprintf("PRAGMA %s", key);
59  sqlite3_stmt* pragma_read_stmt{nullptr};
60  int ret = sqlite3_prepare_v2(db, stmt_text.c_str(), -1, &pragma_read_stmt, nullptr);
61  if (ret != SQLITE_OK) {
62  sqlite3_finalize(pragma_read_stmt);
63  error = Untranslated(strprintf("SQLiteDatabase: Failed to prepare the statement to fetch %s: %s", description, sqlite3_errstr(ret)));
64  return std::nullopt;
65  }
66  ret = sqlite3_step(pragma_read_stmt);
67  if (ret != SQLITE_ROW) {
68  sqlite3_finalize(pragma_read_stmt);
69  error = Untranslated(strprintf("SQLiteDatabase: Failed to fetch %s: %s", description, sqlite3_errstr(ret)));
70  return std::nullopt;
71  }
72  int result = sqlite3_column_int(pragma_read_stmt, 0);
73  sqlite3_finalize(pragma_read_stmt);
74  return result;
75 }
76 
77 static void SetPragma(sqlite3* db, const std::string& key, const std::string& value, const std::string& err_msg)
78 {
79  std::string stmt_text = strprintf("PRAGMA %s = %s", key, value);
80  int ret = sqlite3_exec(db, stmt_text.c_str(), nullptr, nullptr, nullptr);
81  if (ret != SQLITE_OK) {
82  throw std::runtime_error(strprintf("SQLiteDatabase: %s: %s\n", err_msg, sqlite3_errstr(ret)));
83  }
84 }
85 
86 SQLiteDatabase::SQLiteDatabase(const fs::path& dir_path, const fs::path& file_path, const DatabaseOptions& options, bool mock)
87  : WalletDatabase(), m_mock(mock), m_dir_path(fs::PathToString(dir_path)), m_file_path(fs::PathToString(file_path)), m_use_unsafe_sync(options.use_unsafe_sync)
88 {
89  {
91  LogPrintf("Using SQLite Version %s\n", SQLiteDatabaseVersion());
92  LogPrintf("Using wallet %s\n", m_dir_path);
93 
94  if (++g_sqlite_count == 1) {
95  // Setup logging
96  int ret = sqlite3_config(SQLITE_CONFIG_LOG, ErrorLogCallback, nullptr);
97  if (ret != SQLITE_OK) {
98  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup error log: %s\n", sqlite3_errstr(ret)));
99  }
100  // Force serialized threading mode
101  ret = sqlite3_config(SQLITE_CONFIG_SERIALIZED);
102  if (ret != SQLITE_OK) {
103  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to configure serialized threading mode: %s\n", sqlite3_errstr(ret)));
104  }
105  }
106  int ret = sqlite3_initialize(); // This is a no-op if sqlite3 is already initialized
107  if (ret != SQLITE_OK) {
108  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to initialize SQLite: %s\n", sqlite3_errstr(ret)));
109  }
110  }
111 
112  try {
113  Open();
114  } catch (const std::runtime_error&) {
115  // If open fails, cleanup this object and rethrow the exception
116  Cleanup();
117  throw;
118  }
119 }
120 
122 {
123  const std::vector<std::pair<sqlite3_stmt**, const char*>> statements{
124  {&m_read_stmt, "SELECT value FROM main WHERE key = ?"},
125  {&m_insert_stmt, "INSERT INTO main VALUES(?, ?)"},
126  {&m_overwrite_stmt, "INSERT or REPLACE into main values(?, ?)"},
127  {&m_delete_stmt, "DELETE FROM main WHERE key = ?"},
128  {&m_cursor_stmt, "SELECT key, value FROM main"},
129  };
130 
131  for (const auto& [stmt_prepared, stmt_text] : statements) {
132  if (*stmt_prepared == nullptr) {
133  int res = sqlite3_prepare_v2(m_database.m_db, stmt_text, -1, stmt_prepared, nullptr);
134  if (res != SQLITE_OK) {
135  throw std::runtime_error(strprintf(
136  "SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res)));
137  }
138  }
139  }
140 }
141 
143 {
144  Cleanup();
145 }
146 
147 void SQLiteDatabase::Cleanup() noexcept
148 {
149  Close();
150 
152  if (--g_sqlite_count == 0) {
153  int ret = sqlite3_shutdown();
154  if (ret != SQLITE_OK) {
155  LogPrintf("SQLiteDatabase: Failed to shutdown SQLite: %s\n", sqlite3_errstr(ret));
156  }
157  }
158 }
159 
161 {
162  assert(m_db);
163 
164  // Check the application ID matches our network magic
165  auto read_result = ReadPragmaInteger(m_db, "application_id", "the application id", error);
166  if (!read_result.has_value()) return false;
167  uint32_t app_id = static_cast<uint32_t>(read_result.value());
168  uint32_t net_magic = ReadBE32(Params().MessageStart());
169  if (app_id != net_magic) {
170  error = strprintf(_("SQLiteDatabase: Unexpected application id. Expected %u, got %u"), net_magic, app_id);
171  return false;
172  }
173 
174  // Check our schema version
175  read_result = ReadPragmaInteger(m_db, "user_version", "sqlite wallet schema version", error);
176  if (!read_result.has_value()) return false;
177  int32_t user_ver = read_result.value();
178  if (user_ver != WALLET_SCHEMA_VERSION) {
179  error = strprintf(_("SQLiteDatabase: Unknown sqlite wallet schema version %d. Only version %d is supported"), user_ver, WALLET_SCHEMA_VERSION);
180  return false;
181  }
182 
183  sqlite3_stmt* stmt{nullptr};
184  int ret = sqlite3_prepare_v2(m_db, "PRAGMA integrity_check", -1, &stmt, nullptr);
185  if (ret != SQLITE_OK) {
186  sqlite3_finalize(stmt);
187  error = strprintf(_("SQLiteDatabase: Failed to prepare statement to verify database: %s"), sqlite3_errstr(ret));
188  return false;
189  }
190  while (true) {
191  ret = sqlite3_step(stmt);
192  if (ret == SQLITE_DONE) {
193  break;
194  }
195  if (ret != SQLITE_ROW) {
196  error = strprintf(_("SQLiteDatabase: Failed to execute statement to verify database: %s"), sqlite3_errstr(ret));
197  break;
198  }
199  const char* msg = (const char*)sqlite3_column_text(stmt, 0);
200  if (!msg) {
201  error = strprintf(_("SQLiteDatabase: Failed to read database verification error: %s"), sqlite3_errstr(ret));
202  break;
203  }
204  std::string str_msg(msg);
205  if (str_msg == "ok") {
206  continue;
207  }
208  if (error.empty()) {
209  error = _("Failed to verify database") + Untranslated("\n");
210  }
211  error += Untranslated(strprintf("%s\n", str_msg));
212  }
213  sqlite3_finalize(stmt);
214  return error.empty();
215 }
216 
218 {
219  int flags = SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
220  if (m_mock) {
221  flags |= SQLITE_OPEN_MEMORY; // In memory database for mock db
222  }
223 
224  if (m_db == nullptr) {
225  if (!m_mock) {
227  }
228  int ret = sqlite3_open_v2(m_file_path.c_str(), &m_db, flags, nullptr);
229  if (ret != SQLITE_OK) {
230  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to open database: %s\n", sqlite3_errstr(ret)));
231  }
232  ret = sqlite3_extended_result_codes(m_db, 1);
233  if (ret != SQLITE_OK) {
234  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable extended result codes: %s\n", sqlite3_errstr(ret)));
235  }
236  }
237 
238  if (sqlite3_db_readonly(m_db, "main") != 0) {
239  throw std::runtime_error("SQLiteDatabase: Database opened in readonly mode but read-write permissions are needed");
240  }
241 
242  // Acquire an exclusive lock on the database
243  // First change the locking mode to exclusive
244  SetPragma(m_db, "locking_mode", "exclusive", "Unable to change database locking mode to exclusive");
245  // Now begin a transaction to acquire the exclusive lock. This lock won't be released until we close because of the exclusive locking mode.
246  int ret = sqlite3_exec(m_db, "BEGIN EXCLUSIVE TRANSACTION", nullptr, nullptr, nullptr);
247  if (ret != SQLITE_OK) {
248  throw std::runtime_error("SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another instance of " PACKAGE_NAME "?\n");
249  }
250  ret = sqlite3_exec(m_db, "COMMIT", nullptr, nullptr, nullptr);
251  if (ret != SQLITE_OK) {
252  throw std::runtime_error(strprintf("SQLiteDatabase: Unable to end exclusive lock transaction: %s\n", sqlite3_errstr(ret)));
253  }
254 
255  // Enable fullfsync for the platforms that use it
256  SetPragma(m_db, "fullfsync", "true", "Failed to enable fullfsync");
257 
258  if (m_use_unsafe_sync) {
259  // Use normal synchronous mode for the journal
260  LogPrintf("WARNING SQLite is configured to not wait for data to be flushed to disk. Data loss and corruption may occur.\n");
261  SetPragma(m_db, "synchronous", "OFF", "Failed to set synchronous mode to OFF");
262  }
263 
264  // Make the table for our key-value pairs
265  // First check that the main table exists
266  sqlite3_stmt* check_main_stmt{nullptr};
267  ret = sqlite3_prepare_v2(m_db, "SELECT name FROM sqlite_master WHERE type='table' AND name='main'", -1, &check_main_stmt, nullptr);
268  if (ret != SQLITE_OK) {
269  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to prepare statement to check table existence: %s\n", sqlite3_errstr(ret)));
270  }
271  ret = sqlite3_step(check_main_stmt);
272  if (sqlite3_finalize(check_main_stmt) != SQLITE_OK) {
273  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to finalize statement checking table existence: %s\n", sqlite3_errstr(ret)));
274  }
275  bool table_exists;
276  if (ret == SQLITE_DONE) {
277  table_exists = false;
278  } else if (ret == SQLITE_ROW) {
279  table_exists = true;
280  } else {
281  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to execute statement to check table existence: %s\n", sqlite3_errstr(ret)));
282  }
283 
284  // Do the db setup things because the table doesn't exist only when we are creating a new wallet
285  if (!table_exists) {
286  ret = sqlite3_exec(m_db, "CREATE TABLE main(key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL)", nullptr, nullptr, nullptr);
287  if (ret != SQLITE_OK) {
288  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to create new database: %s\n", sqlite3_errstr(ret)));
289  }
290 
291  // Set the application id
292  uint32_t app_id = ReadBE32(Params().MessageStart());
293  SetPragma(m_db, "application_id", strprintf("%d", static_cast<int32_t>(app_id)),
294  "Failed to set the application id");
295 
296  // Set the user version
297  SetPragma(m_db, "user_version", strprintf("%d", WALLET_SCHEMA_VERSION),
298  "Failed to set the wallet schema version");
299  }
300 }
301 
302 bool SQLiteDatabase::Rewrite(const char* skip)
303 {
304  // Rewrite the database using the VACUUM command: https://sqlite.org/lang_vacuum.html
305  int ret = sqlite3_exec(m_db, "VACUUM", nullptr, nullptr, nullptr);
306  return ret == SQLITE_OK;
307 }
308 
309 bool SQLiteDatabase::Backup(const std::string& dest) const
310 {
311  sqlite3* db_copy;
312  int res = sqlite3_open(dest.c_str(), &db_copy);
313  if (res != SQLITE_OK) {
314  sqlite3_close(db_copy);
315  return false;
316  }
317  sqlite3_backup* backup = sqlite3_backup_init(db_copy, "main", m_db, "main");
318  if (!backup) {
319  LogPrintf("%s: Unable to begin backup: %s\n", __func__, sqlite3_errmsg(m_db));
320  sqlite3_close(db_copy);
321  return false;
322  }
323  // Specifying -1 will copy all of the pages
324  res = sqlite3_backup_step(backup, -1);
325  if (res != SQLITE_DONE) {
326  LogPrintf("%s: Unable to backup: %s\n", __func__, sqlite3_errstr(res));
327  sqlite3_backup_finish(backup);
328  sqlite3_close(db_copy);
329  return false;
330  }
331  res = sqlite3_backup_finish(backup);
332  sqlite3_close(db_copy);
333  return res == SQLITE_OK;
334 }
335 
337 {
338  int res = sqlite3_close(m_db);
339  if (res != SQLITE_OK) {
340  throw std::runtime_error(strprintf("SQLiteDatabase: Failed to close database: %s\n", sqlite3_errstr(res)));
341  }
342  m_db = nullptr;
343 }
344 
345 std::unique_ptr<DatabaseBatch> SQLiteDatabase::MakeBatch(bool flush_on_close)
346 {
347  // We ignore flush_on_close because we don't do manual flushing for SQLite
348  return std::make_unique<SQLiteBatch>(*this);
349 }
350 
352  : m_database(database)
353 {
354  // Make sure we have a db handle
356 
358 }
359 
361 {
362  // If m_db is in a transaction (i.e. not in autocommit mode), then abort the transaction in progress
363  if (m_database.m_db && sqlite3_get_autocommit(m_database.m_db) == 0) {
364  if (TxnAbort()) {
365  LogPrintf("SQLiteBatch: Batch closed unexpectedly without the transaction being explicitly committed or aborted\n");
366  } else {
367  LogPrintf("SQLiteBatch: Batch closed and failed to abort transaction\n");
368  }
369  }
370 
371  // Free all of the prepared statements
372  const std::vector<std::pair<sqlite3_stmt**, const char*>> statements{
373  {&m_read_stmt, "read"},
374  {&m_insert_stmt, "insert"},
375  {&m_overwrite_stmt, "overwrite"},
376  {&m_delete_stmt, "delete"},
377  {&m_cursor_stmt, "cursor"},
378  };
379 
380  for (const auto& [stmt_prepared, stmt_description] : statements) {
381  int res = sqlite3_finalize(*stmt_prepared);
382  if (res != SQLITE_OK) {
383  LogPrintf("SQLiteBatch: Batch closed but could not finalize %s statement: %s\n",
384  stmt_description, sqlite3_errstr(res));
385  }
386  *stmt_prepared = nullptr;
387  }
388 }
389 
391 {
392  if (!m_database.m_db) return false;
394 
395  // Bind: leftmost parameter in statement is index 1
396  if (!BindBlobToStatement(m_read_stmt, 1, key, "key")) return false;
397  int res = sqlite3_step(m_read_stmt);
398  if (res != SQLITE_ROW) {
399  if (res != SQLITE_DONE) {
400  // SQLITE_DONE means "not found", don't log an error in that case.
401  LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res));
402  }
403  sqlite3_clear_bindings(m_read_stmt);
404  sqlite3_reset(m_read_stmt);
405  return false;
406  }
407  // Leftmost column in result is index 0
408  const std::byte* data{AsBytePtr(sqlite3_column_blob(m_read_stmt, 0))};
409  size_t data_size(sqlite3_column_bytes(m_read_stmt, 0));
410  value.write({data, data_size});
411 
412  sqlite3_clear_bindings(m_read_stmt);
413  sqlite3_reset(m_read_stmt);
414  return true;
415 }
416 
417 bool SQLiteBatch::WriteKey(CDataStream&& key, CDataStream&& value, bool overwrite)
418 {
419  if (!m_database.m_db) return false;
421 
422  sqlite3_stmt* stmt;
423  if (overwrite) {
424  stmt = m_overwrite_stmt;
425  } else {
426  stmt = m_insert_stmt;
427  }
428 
429  // Bind: leftmost parameter in statement is index 1
430  // Insert index 1 is key, 2 is value
431  if (!BindBlobToStatement(stmt, 1, key, "key")) return false;
432  if (!BindBlobToStatement(stmt, 2, value, "value")) return false;
433 
434  // Execute
435  int res = sqlite3_step(stmt);
436  sqlite3_clear_bindings(stmt);
437  sqlite3_reset(stmt);
438  if (res != SQLITE_DONE) {
439  LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res));
440  }
441  return res == SQLITE_DONE;
442 }
443 
445 {
446  if (!m_database.m_db) return false;
448 
449  // Bind: leftmost parameter in statement is index 1
450  if (!BindBlobToStatement(m_delete_stmt, 1, key, "key")) return false;
451 
452  // Execute
453  int res = sqlite3_step(m_delete_stmt);
454  sqlite3_clear_bindings(m_delete_stmt);
455  sqlite3_reset(m_delete_stmt);
456  if (res != SQLITE_DONE) {
457  LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res));
458  }
459  return res == SQLITE_DONE;
460 }
461 
463 {
464  if (!m_database.m_db) return false;
466 
467  // Bind: leftmost parameter in statement is index 1
468  if (!BindBlobToStatement(m_read_stmt, 1, key, "key")) return false;
469  int res = sqlite3_step(m_read_stmt);
470  sqlite3_clear_bindings(m_read_stmt);
471  sqlite3_reset(m_read_stmt);
472  return res == SQLITE_ROW;
473 }
474 
476 {
478  if (!m_database.m_db) return false;
479  m_cursor_init = true;
480  return true;
481 }
482 
483 bool SQLiteBatch::ReadAtCursor(CDataStream& key, CDataStream& value, bool& complete)
484 {
485  complete = false;
486 
487  if (!m_cursor_init) return false;
488 
489  int res = sqlite3_step(m_cursor_stmt);
490  if (res == SQLITE_DONE) {
491  complete = true;
492  return true;
493  }
494  if (res != SQLITE_ROW) {
495  LogPrintf("SQLiteBatch::ReadAtCursor: Unable to execute cursor step: %s\n", sqlite3_errstr(res));
496  return false;
497  }
498 
499  // Leftmost column in result is index 0
500  const std::byte* key_data{AsBytePtr(sqlite3_column_blob(m_cursor_stmt, 0))};
501  size_t key_data_size(sqlite3_column_bytes(m_cursor_stmt, 0));
502  key.write({key_data, key_data_size});
503  const std::byte* value_data{AsBytePtr(sqlite3_column_blob(m_cursor_stmt, 1))};
504  size_t value_data_size(sqlite3_column_bytes(m_cursor_stmt, 1));
505  value.write({value_data, value_data_size});
506  return true;
507 }
508 
510 {
511  sqlite3_reset(m_cursor_stmt);
512  m_cursor_init = false;
513 }
514 
516 {
517  if (!m_database.m_db || sqlite3_get_autocommit(m_database.m_db) == 0) return false;
518  int res = sqlite3_exec(m_database.m_db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr);
519  if (res != SQLITE_OK) {
520  LogPrintf("SQLiteBatch: Failed to begin the transaction\n");
521  }
522  return res == SQLITE_OK;
523 }
524 
526 {
527  if (!m_database.m_db || sqlite3_get_autocommit(m_database.m_db) != 0) return false;
528  int res = sqlite3_exec(m_database.m_db, "COMMIT TRANSACTION", nullptr, nullptr, nullptr);
529  if (res != SQLITE_OK) {
530  LogPrintf("SQLiteBatch: Failed to commit the transaction\n");
531  }
532  return res == SQLITE_OK;
533 }
534 
536 {
537  if (!m_database.m_db || sqlite3_get_autocommit(m_database.m_db) != 0) return false;
538  int res = sqlite3_exec(m_database.m_db, "ROLLBACK TRANSACTION", nullptr, nullptr, nullptr);
539  if (res != SQLITE_OK) {
540  LogPrintf("SQLiteBatch: Failed to abort the transaction\n");
541  }
542  return res == SQLITE_OK;
543 }
544 
545 std::unique_ptr<SQLiteDatabase> MakeSQLiteDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
546 {
547  try {
548  fs::path data_file = SQLiteDataFile(path);
549  auto db = std::make_unique<SQLiteDatabase>(data_file.parent_path(), data_file, options);
550  if (options.verify && !db->Verify(error)) {
552  return nullptr;
553  }
554  status = DatabaseStatus::SUCCESS;
555  return db;
556  } catch (const std::runtime_error& e) {
558  error = Untranslated(e.what());
559  return nullptr;
560  }
561 }
562 
564 {
565  return std::string(sqlite3_libversion());
566 }
567 } // namespace wallet
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:173
int ret
assert(!tx.IsCoinBase())
static bool BindBlobToStatement(sqlite3_stmt *stmt, int index, Span< const std::byte > blob, const std::string &description)
Definition: sqlite.cpp:40
Bilingual messages:
Definition: translation.h:18
std::unique_ptr< SQLiteDatabase > MakeSQLiteDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: sqlite.cpp:545
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static int g_sqlite_count GUARDED_BY(g_sqlite_mutex)=0
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
bool TxnCommit() override
Definition: sqlite.cpp:525
const std::string m_file_path
Definition: sqlite.h:64
void SetupSQLStatements()
Definition: sqlite.cpp:121
constexpr std::size_t size() const noexcept
Definition: span.h:186
SQLiteDatabase & m_database
Definition: sqlite.h:21
void CloseCursor() override
Definition: sqlite.cpp:509
std::string SQLiteDatabaseVersion()
Definition: sqlite.cpp:563
#define PACKAGE_NAME
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:185
sqlite3_stmt * m_overwrite_stmt
Definition: sqlite.h:27
bool m_cursor_init
Definition: sqlite.h:23
sqlite3_stmt * m_insert_stmt
Definition: sqlite.h:26
void write(Span< const value_type > src)
Definition: streams.h:313
static std::optional< int > ReadPragmaInteger(sqlite3 *db, const std::string &key, const std::string &description, bilingual_str &error)
Definition: sqlite.cpp:56
Filesystem operations and types.
Definition: fs.h:20
fs::path SQLiteDataFile(const fs::path &path)
Definition: db.cpp:78
bool EraseKey(CDataStream &&key) override
Definition: sqlite.cpp:444
bool Verify(bilingual_str &error)
Definition: sqlite.cpp:160
const bool m_mock
Definition: sqlite.h:60
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
bool Rewrite(const char *skip=nullptr) override
Rewrite the entire database on disk.
Definition: sqlite.cpp:302
bool TxnAbort() override
Definition: sqlite.cpp:535
const std::byte * AsBytePtr(const void *data)
Convert a data pointer to a std::byte data pointer.
Definition: span.h:248
#define LOCK(cs)
Definition: sync.h:261
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:65
void Open() override
Open the database if it is not already opened.
Definition: sqlite.cpp:217
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: system.cpp:1159
static uint32_t ReadBE32(const unsigned char *ptr)
Definition: common.h:63
bool WriteKey(CDataStream &&key, CDataStream &&value, bool overwrite=true) override
Definition: sqlite.cpp:417
sqlite3_stmt * m_cursor_stmt
Definition: sqlite.h:29
void Close() override
Definition: sqlite.cpp:360
static constexpr int32_t WALLET_SCHEMA_VERSION
Definition: sqlite.cpp:24
Definition: node.h:39
std::unique_ptr< DatabaseBatch > MakeBatch(bool flush_on_close=true) override
Make a SQLiteBatch connected to this database.
Definition: sqlite.cpp:345
SQLiteBatch(SQLiteDatabase &database)
Definition: sqlite.cpp:351
int flags
Definition: bitcoin-tx.cpp:525
DatabaseStatus
Definition: db.h:219
const std::string m_dir_path
Definition: sqlite.h:62
constexpr C * data() const noexcept
Definition: span.h:173
const CChainParams & Params()
Return the currently selected parameters.
bool HasKey(CDataStream &&key) override
Definition: sqlite.cpp:462
bool TxnBegin() override
Definition: sqlite.cpp:515
static void ErrorLogCallback(void *arg, int code, const char *msg)
Definition: sqlite.cpp:29
void Cleanup() noexcept
Definition: sqlite.cpp:147
An instance of this class represents one SQLite3 database.
Definition: sqlite.h:57
bool StartCursor() override
Definition: sqlite.cpp:475
bool ReadAtCursor(CDataStream &key, CDataStream &value, bool &complete) override
Definition: sqlite.cpp:483
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:96
Different type to mark Mutex at global scope.
Definition: sync.h:141
sqlite3_stmt * m_delete_stmt
Definition: sqlite.h:28
#define LogPrintf(...)
Definition: logging.h:234
bool ReadKey(CDataStream &&key, CDataStream &value) override
Definition: sqlite.cpp:390
static void SetPragma(sqlite3 *db, const std::string &key, const std::string &value, const std::string &err_msg)
Definition: sqlite.cpp:77
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
bool verify
Check data integrity on load.
Definition: db.h:213
bool Backup(const std::string &dest) const override
Back up the entire database to a file.
Definition: sqlite.cpp:309
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
An instance of this class represents one database.
Definition: db.h:105
sqlite3_stmt * m_read_stmt
Definition: sqlite.h:25
void Close() override
Close the database.
Definition: sqlite.cpp:336
static GlobalMutex g_sqlite_mutex
Definition: sqlite.cpp:26