blob: b4eeb9b0c6acb64acae77ef988b510f783235d23 [file] [log] [blame]
[email protected]2eec0a22012-07-24 01:59:581// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Victor Costancfbfa602018-08-01 23:24:465#ifndef SQL_DATABASE_H_
6#define SQL_DATABASE_H_
[email protected]e5ffd0e42009-09-11 21:30:567
avi0b519202015-12-21 07:25:198#include <stddef.h>
tfarina720d4f32015-05-11 22:31:269#include <stdint.h>
mostynbd82cd9952016-04-11 20:05:3410#include <memory>
[email protected]e5ffd0e42009-09-11 21:30:5611#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3312#include <string>
Victor Costan87cf8c72018-07-19 19:36:0413#include <utility>
[email protected]80abf152013-05-22 12:42:4214#include <vector>
[email protected]e5ffd0e42009-09-11 21:30:5615
[email protected]c3881b372013-05-17 08:39:4616#include "base/callback.h"
[email protected]9fe37552011-12-23 17:07:2017#include "base/compiler_specific.h"
Victor Costane56cc682018-12-27 01:53:4618#include "base/component_export.h"
Dmitry Skibaa9ad8fe42017-08-16 21:02:4819#include "base/containers/flat_map.h"
Shubham Aggarwal7b60fe6e2020-10-15 06:00:2820#include "base/feature_list.h"
shessc8cd2a162015-10-22 20:30:4621#include "base/gtest_prod_util.h"
tfarina720d4f32015-05-11 22:31:2622#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1523#include "base/memory/ref_counted.h"
Etienne Pierre-Doraya71d7af2019-02-07 02:07:5424#include "base/optional.h"
Victor Costan12daa3ac92018-07-19 01:05:5825#include "base/sequence_checker.h"
Etienne Pierre-Doray0400dfb62018-12-03 19:12:2526#include "base/threading/scoped_blocking_call.h"
Victor Costan7f6abbbe2018-07-29 02:57:2727#include "sql/internal_api_token.h"
Shubham Aggarwal7b60fe6e2020-10-15 06:00:2828#include "sql/sql_features.h"
Victor Costan12daa3ac92018-07-19 01:05:5829#include "sql/statement_id.h"
[email protected]e5ffd0e42009-09-11 21:30:5630
[email protected]e5ffd0e42009-09-11 21:30:5631struct sqlite3;
32struct sqlite3_stmt;
33
[email protected]a3ef4832013-02-02 05:12:3334namespace base {
35class FilePath;
shess58b8df82015-06-03 00:19:3236class HistogramBase;
dskibab4199f82016-11-21 20:16:1337namespace trace_event {
ssid1f4e5362016-12-08 20:41:3838class ProcessMemoryDump;
Victor Costan87cf8c72018-07-19 19:36:0439} // namespace trace_event
40} // namespace base
[email protected]a3ef4832013-02-02 05:12:3341
[email protected]e5ffd0e42009-09-11 21:30:5642namespace sql {
43
Victor Costancfbfa602018-08-01 23:24:4644class DatabaseMemoryDumpProvider;
[email protected]e5ffd0e42009-09-11 21:30:5645class Statement;
46
shess58b8df82015-06-03 00:19:3247namespace test {
shess976814402016-06-21 06:56:2548class ScopedErrorExpecter;
Victor Costan87cf8c72018-07-19 19:36:0449} // namespace test
shess58b8df82015-06-03 00:19:3250
Shubham Aggarwal7b60fe6e2020-10-15 06:00:2851struct COMPONENT_EXPORT(SQL) DatabaseOptions {
52 // Default page size for newly created databases.
53 //
54 // Guaranteed to match SQLITE_DEFAULT_PAGE_SIZE.
55 static constexpr int kDefaultPageSize = 4096;
56
57 // If true, the database can only be opened by one process at a time.
58 //
59 // Exclusive mode is strongly recommended. It reduces the I/O cost of setting
60 // up a transaction. It also removes the need of handling transaction failures
61 // due to lock contention.
62 bool exclusive_locking = true;
63
64 // If true, enables SQLite's Write-Ahead Logging (WAL).
65 //
66 // WAL integration is under development, and should not be used in shipping
67 // Chrome features yet. In particular, our custom database recovery code does
68 // not support the WAL log file.
69 //
70 // More details at https://www.sqlite.org/wal.html
71 bool wal_mode =
72 base::FeatureList::IsEnabled(sql::features::kEnableWALModeByDefault);
73
74 // Database page size.
75 //
76 // Larger page sizes result in shallower B-trees, because they allow an inner
77 // page to hold more keys. On the flip side, larger page sizes may result in
78 // more I/O when making small changes to existing records.
79 int page_size = kDefaultPageSize;
80
81 // The size of in-memory cache, in pages.
82 //
83 // SQLite's database cache will take up at most (`page_size` * `cache_size`)
84 // bytes of RAM.
85 //
86 // 0 invokes SQLite's default, which is currently to size up the cache to use
87 // exactly 2,048,000 bytes of RAM.
88 int cache_size = 0;
89};
90
Victor Costan87cf8c72018-07-19 19:36:0491// Handle to an open SQLite database.
92//
93// Instances of this class are thread-unsafe and DCHECK that they are accessed
94// on the same sequence.
Victor Costane56cc682018-12-27 01:53:4695class COMPONENT_EXPORT(SQL) Database {
[email protected]e5ffd0e42009-09-11 21:30:5696 private:
97 class StatementRef; // Forward declaration, see real one below.
98
99 public:
[email protected]765b44502009-10-02 05:01:42100 // The database is opened by calling Open[InMemory](). Any uncommitted
101 // transactions will be rolled back when this object is deleted.
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28102 //
103 // This constructor is deprecated.
104 // TODO(crbug.com/1126968): Remove this constructor after migrating all
105 // uses to the explicit constructor below.
Victor Costancfbfa602018-08-01 23:24:46106 Database();
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28107 // |options| only affects newly created databases.
108 explicit Database(DatabaseOptions options);
Victor Costancfbfa602018-08-01 23:24:46109 ~Database();
[email protected]e5ffd0e42009-09-11 21:30:56110
Ken Rockot01687422020-08-17 18:00:59111 // Allows mmapping to be disabled globally by default in the calling process.
112 // Must be called before any threads attempt to create a Database.
113 //
114 // TODO(crbug.com/1117049): Remove this global configuration.
115 static void DisableMmapByDefault();
116
[email protected]e5ffd0e42009-09-11 21:30:56117 // Pre-init configuration ----------------------------------------------------
118
[email protected]765b44502009-10-02 05:01:42119 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56120 // must be called before Init(), and will only have an effect on new
121 // databases.
122 //
Victor Costan7f6abbbe2018-07-29 02:57:27123 // The page size must be a power of two between 512 and 65536 inclusive.
Victor Costan87cf8c72018-07-19 19:36:04124 void set_page_size(int page_size) {
Victor Costan7f6abbbe2018-07-29 02:57:27125 DCHECK_GE(page_size, 512);
126 DCHECK_LE(page_size, 65536);
127 DCHECK(!(page_size & (page_size - 1)))
Victor Costan87cf8c72018-07-19 19:36:04128 << "page_size must be a power of two";
129
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28130 options_.page_size = page_size;
Victor Costan87cf8c72018-07-19 19:36:04131 }
[email protected]e5ffd0e42009-09-11 21:30:56132
Victor Costan7f6abbbe2018-07-29 02:57:27133 // The page size that will be used when creating a new database.
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28134 int page_size() const { return options_.page_size; }
Victor Costan7f6abbbe2018-07-29 02:57:27135
[email protected]e5ffd0e42009-09-11 21:30:56136 // Sets the number of pages that will be cached in memory by sqlite. The
137 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42138 // called before Open() to have an effect.
Victor Costan87cf8c72018-07-19 19:36:04139 void set_cache_size(int cache_size) {
140 DCHECK_GE(cache_size, 0);
141
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28142 options_.cache_size = cache_size;
Victor Costan87cf8c72018-07-19 19:36:04143 }
[email protected]e5ffd0e42009-09-11 21:30:56144
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57145 // Returns whether a database will be opened in WAL mode.
146 bool UseWALMode() const;
147
148 // Enables/disables WAL mode (https://www.sqlite.org/wal.html) when
149 // opening a new database.
150 //
151 // WAL mode is currently not fully supported on FuchsiaOS. It will only be
152 // turned on if the database is also using exclusive locking mode.
153 // (https://crbug.com/1082059)
154 //
155 // Note: Changing page size is not supported when in WAL mode. So running
156 // 'PRAGMA page_size = <new-size>' or using set_page_size will result in
157 // no-ops.
158 //
159 // This must be called before Open() to have an effect.
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28160 void want_wal_mode(bool enabled) { options_.wal_mode = enabled; }
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57161
Victor Costanb2230792020-10-09 08:35:14162 // Makes database accessible by only one process at a time.
[email protected]e5ffd0e42009-09-11 21:30:56163 //
Victor Costanb2230792020-10-09 08:35:14164 // TODO(https://crbug.com/1120969): This should be the default mode. The
165 // "NORMAL" mode should be opt-in.
[email protected]e5ffd0e42009-09-11 21:30:56166 //
Victor Costanb2230792020-10-09 08:35:14167 // SQLite supports a locking protocol that allows multiple processes to safely
168 // operate on the same database at the same time. The locking protocol is used
169 // on every transaction, and comes with a small performance penalty.
170 //
171 // Calling this method causes the locking protocol to be used once, when the
172 // database is opened. No other process will be able to access the database at
173 // the same time.
174 //
175 // This method must be called before Open() to have an effect.
176 //
177 // More details at https://www.sqlite.org/pragma.html#pragma_locking_mode
178 //
179 // SQLite's locking protocol is summarized at
180 // https://www.sqlite.org/c3ref/io_methods.html
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28181 void set_exclusive_locking() { options_.exclusive_locking = true; }
[email protected]e5ffd0e42009-09-11 21:30:56182
shessa62504d2016-11-07 19:26:12183 // Call to use alternative status-tracking for mmap. Usually this is tracked
184 // in the meta table, but some databases have no meta table.
185 // TODO(shess): Maybe just have all databases use the alt option?
186 void set_mmap_alt_status() { mmap_alt_status_ = true; }
187
Victor Costan87cf8c72018-07-19 19:36:04188 // Opt out of memory-mapped file I/O.
shess7dbd4dee2015-10-06 17:39:16189 void set_mmap_disabled() { mmap_disabled_ = true; }
190
[email protected]c3881b372013-05-17 08:39:46191 // Set an error-handling callback. On errors, the error number (and
192 // statement, if available) will be passed to the callback.
193 //
194 // If no callback is set, the default action is to crash in debug
195 // mode or return failure in release mode.
Victor Costanc7e7f2e2018-07-18 20:07:55196 using ErrorCallback = base::RepeatingCallback<void(int, Statement*)>;
[email protected]c3881b372013-05-17 08:39:46197 void set_error_callback(const ErrorCallback& callback) {
198 error_callback_ = callback;
199 }
Victor Costan87cf8c72018-07-19 19:36:04200 bool has_error_callback() const { return !error_callback_.is_null(); }
201 void reset_error_callback() { error_callback_.Reset(); }
[email protected]c3881b372013-05-17 08:39:46202
Victor Costancfbfa602018-08-01 23:24:46203 // Set this to enable additional per-database histogramming. Must be called
shess58b8df82015-06-03 00:19:32204 // before Open().
205 void set_histogram_tag(const std::string& tag);
[email protected]c088e3a32013-01-03 23:59:14206
[email protected]210ce0af2013-05-15 09:10:39207 // Record a sparse UMA histogram sample under
208 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
209 // histogram is recorded.
Will Harrisb8693592018-08-28 22:58:44210 void AddTaggedHistogram(const std::string& name, int sample) const;
[email protected]210ce0af2013-05-15 09:10:39211
Etienne Bergerone7681c72020-01-17 00:51:20212 // Track various API calls and results. Values correspond to UMA
shess58b8df82015-06-03 00:19:32213 // histograms, do not modify, or add or delete other than directly
214 // before EVENT_MAX_VALUE.
215 enum Events {
216 // Number of statements run, either with sql::Statement or Execute*().
Victor Costan5e785e32019-02-26 20:39:31217 EVENT_STATEMENT_RUN_DEPRECATED = 0,
shess58b8df82015-06-03 00:19:32218
219 // Number of rows returned by statements run.
Victor Costan5e785e32019-02-26 20:39:31220 EVENT_STATEMENT_ROWS_DEPRECATED,
shess58b8df82015-06-03 00:19:32221
222 // Number of statements successfully run (all steps returned SQLITE_DONE or
223 // SQLITE_ROW).
Victor Costan5e785e32019-02-26 20:39:31224 EVENT_STATEMENT_SUCCESS_DEPRECATED,
shess58b8df82015-06-03 00:19:32225
226 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
Victor Costan5e785e32019-02-26 20:39:31227 EVENT_EXECUTE_DEPRECATED,
shess58b8df82015-06-03 00:19:32228
229 // Number of rows changed by autocommit statements.
Victor Costan5e785e32019-02-26 20:39:31230 EVENT_CHANGES_AUTOCOMMIT_DEPRECATED,
shess58b8df82015-06-03 00:19:32231
232 // Number of rows changed by statements in transactions.
Victor Costan5e785e32019-02-26 20:39:31233 EVENT_CHANGES_DEPRECATED,
shess58b8df82015-06-03 00:19:32234
235 // Count actual SQLite transaction statements (not including nesting).
Victor Costan5e785e32019-02-26 20:39:31236 EVENT_BEGIN_DEPRECATED,
237 EVENT_COMMIT_DEPRECATED,
238 EVENT_ROLLBACK_DEPRECATED,
shess58b8df82015-06-03 00:19:32239
shessd90aeea82015-11-13 02:24:31240 // Track success and failure in GetAppropriateMmapSize().
241 // GetAppropriateMmapSize() should record at most one of these per run. The
242 // case of mapping everything is not recorded.
Victor Costan5e785e32019-02-26 20:39:31243 EVENT_MMAP_META_MISSING, // No meta table present.
244 EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table.
245 EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table.
246 EVENT_MMAP_VFS_FAILURE, // Failed to access VFS.
247 EVENT_MMAP_FAILED, // Failure from past run.
248 EVENT_MMAP_FAILED_NEW, // Read error in this run.
249 EVENT_MMAP_SUCCESS_NEW_DEPRECATED, // Read to EOF in this run.
250 EVENT_MMAP_SUCCESS_PARTIAL_DEPRECATED, // Read but did not reach EOF.
251 EVENT_MMAP_SUCCESS_NO_PROGRESS_DEPRECATED, // Read quota exhausted.
shessd90aeea82015-11-13 02:24:31252
Victor Costancfbfa602018-08-01 23:24:46253 EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view.
254 EVENT_MMAP_STATUS_FAILURE_UPDATE, // Failure updating MmapStatus view.
shessa62504d2016-11-07 19:26:12255
shess58b8df82015-06-03 00:19:32256 // Leave this at the end.
257 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
Victor Costan5e785e32019-02-26 20:39:31258 EVENT_MAX_VALUE,
shess58b8df82015-06-03 00:19:32259 };
260 void RecordEvent(Events event, size_t count);
Victor Costan87cf8c72018-07-19 19:36:04261 void RecordOneEvent(Events event) { RecordEvent(event, 1); }
shess58b8df82015-06-03 00:19:32262
[email protected]579446c2013-12-16 18:36:52263 // Run "PRAGMA integrity_check" and post each line of
264 // results into |messages|. Returns the success of running the
265 // statement - per the SQLite documentation, if no errors are found the
266 // call should succeed, and a single value "ok" should be in messages.
267 bool FullIntegrityCheck(std::vector<std::string>* messages);
268
269 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
270 // interprets the results returning true if the the statement executes
271 // without error and results in a single "ok" value.
272 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42273
afakhry7c9abe72016-08-05 17:33:19274 // Meant to be called from a client error callback so that it's able to
275 // get diagnostic information about the database.
276 std::string GetDiagnosticInfo(int extended_error, Statement* statement);
277
ssid1f4e5362016-12-08 20:41:38278 // Reports memory usage into provided memory dump with the given name.
279 bool ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
280 const std::string& dump_name);
dskibab4199f82016-11-21 20:16:13281
[email protected]e5ffd0e42009-09-11 21:30:56282 // Initialization ------------------------------------------------------------
283
Victor Costancfbfa602018-08-01 23:24:46284 // Initializes the SQL database for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55285 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33286 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42287
Victor Costancfbfa602018-08-01 23:24:46288 // Initializes the SQL database for a temporary in-memory database. There
[email protected]765b44502009-10-02 05:01:42289 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55290 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20291 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42292
[email protected]8d409412013-07-19 18:25:30293 // Create a temporary on-disk database. The database will be
294 // deleted after close. This kind of database is similar to
295 // OpenInMemory() for small databases, but can page to disk if the
296 // database becomes large.
297 bool OpenTemporary() WARN_UNUSED_RESULT;
298
[email protected]41a97c812013-02-07 02:35:38299 // Returns true if the database has been successfully opened.
Victor Costan87cf8c72018-07-19 19:36:04300 bool is_open() const { return static_cast<bool>(db_); }
[email protected]e5ffd0e42009-09-11 21:30:56301
302 // Closes the database. This is automatically performed on destruction for
303 // you, but this allows you to close the database early. You must not call
304 // any other functions after closing it. It is permissable to call Close on
305 // an uninitialized or already-closed database.
306 void Close();
307
[email protected]8ada10f2013-12-21 00:42:34308 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
309 // filesystem cache. This can be more efficient than faulting pages
310 // individually. Since this involves blocking I/O, it should only be used if
311 // the caller will immediately read a substantial amount of data from the
312 // database.
[email protected]e5ffd0e42009-09-11 21:30:56313 //
[email protected]8ada10f2013-12-21 00:42:34314 // TODO(shess): Design a set of histograms or an experiment to inform this
315 // decision. Preloading should almost always improve later performance
316 // numbers for this database simply because it pulls operations forward, but
317 // if the data isn't actually used soon then preloading just slows down
318 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56319 void Preload();
320
Victor Costan52bef812018-12-05 07:41:49321 // Release all non-essential memory associated with this database connection.
322 void TrimMemory();
[email protected]be7995f12013-07-18 18:49:14323
[email protected]8e0c01282012-04-06 19:36:49324 // Raze the database to the ground. This approximates creating a
325 // fresh database from scratch, within the constraints of SQLite's
326 // locking protocol (locks and open handles can make doing this with
327 // filesystem operations problematic). Returns true if the database
328 // was razed.
329 //
330 // false is returned if the database is locked by some other
Carlos Knippschild46800c9f2017-09-02 02:21:43331 // process.
[email protected]8e0c01282012-04-06 19:36:49332 //
333 // NOTE(shess): Raze() will DCHECK in the following situations:
334 // - database is not open.
Victor Costancfbfa602018-08-01 23:24:46335 // - the database has a transaction open.
[email protected]8e0c01282012-04-06 19:36:49336 // - a SQLite issue occurs which is structural in nature (like the
337 // statements used are broken).
338 // Since Raze() is expected to be called in unexpected situations,
339 // these all return false, since it is unlikely that the caller
340 // could fix them.
[email protected]6d42f152012-11-10 00:38:24341 //
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28342 // The database's page size is taken from |options_.page_size|. The
[email protected]6d42f152012-11-10 00:38:24343 // existing database's |auto_vacuum| setting is lost (the
344 // possibility of corruption makes it unreliable to pull it from the
345 // existing database). To re-enable on the empty database requires
346 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
347 //
348 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
349 // so Raze() sets auto_vacuum to 1.
350 //
Victor Costancfbfa602018-08-01 23:24:46351 // TODO(shess): Raze() needs a database so cannot clear SQLITE_NOTADB.
352 // TODO(shess): Bake auto_vacuum into Database's API so it can
[email protected]6d42f152012-11-10 00:38:24353 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49354 bool Raze();
[email protected]8e0c01282012-04-06 19:36:49355
[email protected]41a97c812013-02-07 02:35:38356 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30357 // BeginTransaction()), closes the SQLite database, and poisons the
Victor Costancfbfa602018-08-01 23:24:46358 // object so that all future operations against the Database (or
[email protected]8d409412013-07-19 18:25:30359 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38360 //
[email protected]8d409412013-07-19 18:25:30361 // This is intended as an alternative to Close() in error callbacks.
362 // Close() should still be called at some point.
363 void Poison();
364
365 // Raze() the database and Poison() the handle. Returns the return
366 // value from Raze().
367 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38368 bool RazeAndClose();
369
Victor Costancfbfa602018-08-01 23:24:46370 // Delete the underlying database files associated with |path|. This should be
371 // used on a database which is not opened by any Database instance. Open
372 // Database instances pointing to the database can cause odd results or
373 // corruption (for instance if a hot journal is deleted but the associated
374 // database is not).
[email protected]8d2e39e2013-06-24 05:55:08375 //
376 // Returns true if the database file and associated journals no
377 // longer exist, false otherwise. If the database has never
378 // existed, this will return true.
379 static bool Delete(const base::FilePath& path);
380
[email protected]e5ffd0e42009-09-11 21:30:56381 // Transactions --------------------------------------------------------------
382
383 // Transaction management. We maintain a virtual transaction stack to emulate
384 // nested transactions since sqlite can't do nested transactions. The
385 // limitation is you can't roll back a sub transaction: if any transaction
386 // fails, all transactions open will also be rolled back. Any nested
387 // transactions after one has rolled back will return fail for Begin(). If
388 // Begin() fails, you must not call Commit or Rollback().
389 //
390 // Normally you should use sql::Transaction to manage a transaction, which
391 // will scope it to a C++ context.
392 bool BeginTransaction();
393 void RollbackTransaction();
394 bool CommitTransaction();
395
[email protected]8d409412013-07-19 18:25:30396 // Rollback all outstanding transactions. Use with care, there may
397 // be scoped transactions on the stack.
398 void RollbackAllTransactions();
399
[email protected]e5ffd0e42009-09-11 21:30:56400 // Returns the current transaction nesting, which will be 0 if there are
401 // no open transactions.
402 int transaction_nesting() const { return transaction_nesting_; }
403
[email protected]8d409412013-07-19 18:25:30404 // Attached databases---------------------------------------------------------
405
Victor Costan7f6abbbe2018-07-29 02:57:27406 // SQLite supports attaching multiple database files to a single connection.
[email protected]8d409412013-07-19 18:25:30407 //
Victor Costan7f6abbbe2018-07-29 02:57:27408 // Attach the database in |other_db_path| to the current connection under
409 // |attachment_point|. |attachment_point| must only contain characters from
410 // [a-zA-Z0-9_].
Victor Costan8a87f7e52017-11-10 01:29:30411 //
412 // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can
413 // be attached while a transaction is opened. However, these databases cannot
Victor Costan70bedf22018-07-18 21:21:14414 // be detached until the transaction is committed or aborted.
Victor Costan7f6abbbe2018-07-29 02:57:27415 //
416 // These APIs are only exposed for use in recovery. They are extremely subtle
417 // and are not useful for features built on top of //sql.
[email protected]8d409412013-07-19 18:25:30418 bool AttachDatabase(const base::FilePath& other_db_path,
Victor Costan7f6abbbe2018-07-29 02:57:27419 const char* attachment_point,
420 InternalApiToken);
421 bool DetachDatabase(const char* attachment_point, InternalApiToken);
[email protected]8d409412013-07-19 18:25:30422
[email protected]e5ffd0e42009-09-11 21:30:56423 // Statements ----------------------------------------------------------------
424
425 // Executes the given SQL string, returning true on success. This is
426 // normally used for simple, 1-off statements that don't take any bound
427 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20428 //
[email protected]eff1fa522011-12-12 23:50:59429 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20430 //
431 // Do not use ignore_result() to ignore all errors. Use
432 // ExecuteAndReturnErrorCode() and ignore only specific errors.
433 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56434
[email protected]eff1fa522011-12-12 23:50:59435 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20436 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59437
[email protected]e5ffd0e42009-09-11 21:30:56438 // Returns a statement for the given SQL using the statement cache. It can
439 // take a nontrivial amount of work to parse and compile a statement, so
440 // keeping commonly-used ones around for future use is important for
441 // performance.
442 //
Victor Costan613b4302018-11-20 05:32:43443 // The SQL_FROM_HERE macro is the recommended way of generating a StatementID.
444 // Code that generates custom IDs must ensure that a StatementID is never used
445 // for different SQL statements. Failing to meet this requirement results in
446 // incorrect behavior, and should be caught by a DCHECK.
447 //
448 // The SQL statement passed in |sql| must match the SQL statement reported
449 // back by SQLite. Mismatches are caught by a DCHECK, so any code that has
450 // automated test coverage or that was manually tested on a DCHECK build will
451 // not exhibit this problem. Mismatches generally imply that the statement
452 // passed in has extra whitespace or comments surrounding it, which waste
453 // storage and CPU cycles.
454 //
[email protected]eff1fa522011-12-12 23:50:59455 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
456 // the code will crash in debug). The caller must deal with this eventuality,
457 // either by checking validity of the |sql| before calling, by correctly
458 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56459 //
[email protected]e5ffd0e42009-09-11 21:30:56460 // Example:
Victor Costancfbfa602018-08-01 23:24:46461 // sql::Statement stmt(database_.GetCachedStatement(
[email protected]3273dce2010-01-27 16:08:08462 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56463 // if (!stmt)
464 // return false; // Error creating statement.
Victor Costan12daa3ac92018-07-19 01:05:58465 scoped_refptr<StatementRef> GetCachedStatement(StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:56466 const char* sql);
467
[email protected]eff1fa522011-12-12 23:50:59468 // Used to check a |sql| statement for syntactic validity. If the statement is
469 // valid SQL, returns true.
470 bool IsSQLValid(const char* sql);
471
[email protected]e5ffd0e42009-09-11 21:30:56472 // Returns a non-cached statement for the given SQL. Use this for SQL that
473 // is only executed once or only rarely (there is overhead associated with
474 // keeping a statement cached).
475 //
476 // See GetCachedStatement above for examples and error information.
477 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
478
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57479 // Performs a passive checkpoint on the main attached database if it is in
480 // WAL mode. Returns true if the checkpoint was successful and false in case
481 // of an error. It is a no-op if the database is not in WAL mode.
482 //
483 // Note: Checkpointing is a very slow operation and will block any writes
484 // until it is finished. Please use with care.
485 bool CheckpointDatabase();
486
[email protected]e5ffd0e42009-09-11 21:30:56487 // Info querying -------------------------------------------------------------
488
shessa62504d2016-11-07 19:26:12489 // Returns true if the given structure exists. Instead of test-then-create,
490 // callers should almost always prefer the "IF NOT EXISTS" version of the
491 // CREATE statement.
[email protected]e2cadec82011-12-13 02:00:53492 bool DoesIndexExist(const char* index_name) const;
shessa62504d2016-11-07 19:26:12493 bool DoesTableExist(const char* table_name) const;
494 bool DoesViewExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53495
[email protected]e5ffd0e42009-09-11 21:30:56496 // Returns true if a column with the given name exists in the given table.
Victor Costan1ff47e92018-12-07 11:10:43497 //
498 // Calling this method on a VIEW returns an unspecified result.
499 //
500 // This should only be used by migration code for legacy features that do not
501 // use MetaTable, and need an alternative way of figuring out the database's
502 // current version.
[email protected]1ed78a32009-09-15 20:24:17503 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56504
505 // Returns sqlite's internal ID for the last inserted row. Valid only
506 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26507 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56508
[email protected]1ed78a32009-09-15 20:24:17509 // Returns sqlite's count of the number of rows modified by the last
510 // statement executed. Will be 0 if no statement has executed or the database
511 // is closed.
512 int GetLastChangeCount() const;
513
Victor Costand6e73252020-10-14 21:11:25514 // Approximates the amount of memory used by SQLite for this database.
515 //
516 // This measures the memory used for the page cache (most likely the biggest
517 // consumer), database schema, and prepared statements.
518 //
519 // The memory used by the page cache can be recovered by calling TrimMemory(),
520 // which will cause SQLite to drop the page cache.
521 int GetMemoryUsage();
522
[email protected]e5ffd0e42009-09-11 21:30:56523 // Errors --------------------------------------------------------------------
524
525 // Returns the error code associated with the last sqlite operation.
526 int GetErrorCode() const;
527
[email protected]767718e52010-09-21 23:18:49528 // Returns the errno associated with GetErrorCode(). See
529 // SQLITE_LAST_ERRNO in SQLite documentation.
530 int GetLastErrno() const;
531
[email protected]e5ffd0e42009-09-11 21:30:56532 // Returns a pointer to a statically allocated string associated with the
533 // last sqlite operation.
534 const char* GetErrorMessage() const;
535
[email protected]92cd00a2013-08-16 11:09:58536 // Return a reproducible representation of the schema equivalent to
537 // running the following statement at a sqlite3 command-line:
538 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
539 std::string GetSchema() const;
540
shess976814402016-06-21 06:56:25541 // Returns |true| if there is an error expecter (see SetErrorExpecter), and
542 // that expecter returns |true| when passed |error|. Clients which provide an
543 // |error_callback| should use IsExpectedSqliteError() to check for unexpected
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52544 // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see
shess976814402016-06-21 06:56:25545 // OnSqliteError implementation).
546 static bool IsExpectedSqliteError(int error);
[email protected]74cdede2013-09-25 05:39:57547
Victor Costance678e72018-07-24 10:25:00548 // Computes the path of a database's rollback journal.
549 //
550 // The journal file is created at the beginning of the database's first
551 // transaction. The file may be removed and re-created between transactions,
552 // depending on whether the database is opened in exclusive mode, and on
553 // configuration options. The journal file does not exist when the database
554 // operates in WAL mode.
555 //
556 // This is intended for internal use and tests. To preserve our ability to
557 // iterate on our SQLite configuration, features must avoid relying on
558 // the existence of specific files.
559 static base::FilePath JournalPath(const base::FilePath& db_path);
560
561 // Computes the path of a database's write-ahead log (WAL).
562 //
563 // The WAL file exists while a database is opened in WAL mode.
564 //
565 // This is intended for internal use and tests. To preserve our ability to
566 // iterate on our SQLite configuration, features must avoid relying on
567 // the existence of specific files.
568 static base::FilePath WriteAheadLogPath(const base::FilePath& db_path);
569
570 // Computes the path of a database's shared memory (SHM) file.
571 //
572 // The SHM file is used to coordinate between multiple processes using the
573 // same database in WAL mode. Thus, this file only exists for databases using
574 // WAL and not opened in exclusive mode.
575 //
576 // This is intended for internal use and tests. To preserve our ability to
577 // iterate on our SQLite configuration, features must avoid relying on
578 // the existence of specific files.
579 static base::FilePath SharedMemoryFilePath(const base::FilePath& db_path);
580
Victor Costan7f6abbbe2018-07-29 02:57:27581 // Internal state accessed by other classes in //sql.
582 sqlite3* db(InternalApiToken) const { return db_; }
583 bool poisoned(InternalApiToken) const { return poisoned_; }
584
585 private:
shess976814402016-06-21 06:56:25586 // Allow test-support code to set/reset error expecter.
587 friend class test::ScopedErrorExpecter;
[email protected]4350e322013-06-18 22:18:10588
[email protected]eff1fa522011-12-12 23:50:59589 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56590 // (they should go through Statement).
591 friend class Statement;
592
Victor Costancfbfa602018-08-01 23:24:46593 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CachedStatement);
594 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CollectDiagnosticInfo);
595 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSize);
596 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSizeAltStatus);
597 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, OnMemoryDump);
598 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, RegisterIntentToUpload);
shessf7fcc452017-04-19 22:10:41599 FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose);
shessc8cd2a162015-10-22 20:30:46600
[email protected]765b44502009-10-02 05:01:42601 // Internal initialize function used by both Init and InitInMemory. The file
602 // name is always 8 bits since we want to use the 8-bit version of
603 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13604 //
605 // |retry_flag| controls retrying the open if the error callback
606 // addressed errors using RazeAndClose().
Victor Costancfbfa602018-08-01 23:24:46607 enum Retry { NO_RETRY = 0, RETRY_ON_POISON };
[email protected]fed734a2013-07-17 04:45:13608 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42609
[email protected]41a97c812013-02-07 02:35:38610 // Internal close function used by Close() and RazeAndClose().
611 // |forced| indicates that orderly-shutdown checks should not apply.
612 void CloseInternal(bool forced);
613
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54614 // Construct a ScopedBlockingCall to annotate IO calls, but only if
Etienne Bergerone7681c72020-01-17 00:51:20615 // database wasn't open in memory. ScopedBlockingCall uses |from_here| to
616 // declare its blocking execution scope (see https://www.crbug/934302).
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54617 void InitScopedBlockingCall(
Etienne Bergerone7681c72020-01-17 00:51:20618 const base::Location& from_here,
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54619 base::Optional<base::ScopedBlockingCall>* scoped_blocking_call) const {
[email protected]35f7e5392012-07-27 19:54:50620 if (!in_memory_)
Etienne Bergerone7681c72020-01-17 00:51:20621 scoped_blocking_call->emplace(from_here, base::BlockingType::MAY_BLOCK);
[email protected]35f7e5392012-07-27 19:54:50622 }
623
shessa62504d2016-11-07 19:26:12624 // Internal helper for Does*Exist() functions.
625 bool DoesSchemaItemExist(const char* name, const char* type) const;
[email protected]e2cadec82011-12-13 02:00:53626
shess976814402016-06-21 06:56:25627 // Accessors for global error-expecter, for injecting behavior during tests.
628 // See test/scoped_error_expecter.h.
Victor Costanc7e7f2e2018-07-18 20:07:55629 using ErrorExpecterCallback = base::RepeatingCallback<bool(int)>;
shess976814402016-06-21 06:56:25630 static ErrorExpecterCallback* current_expecter_cb_;
631 static void SetErrorExpecter(ErrorExpecterCallback* expecter);
632 static void ResetErrorExpecter();
[email protected]4350e322013-06-18 22:18:10633
[email protected]e5ffd0e42009-09-11 21:30:56634 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
635 // Refcounting allows us to give these statements out to sql::Statement
636 // objects while also optionally maintaining a cache of compiled statements
637 // by just keeping a refptr to these objects.
638 //
639 // A statement ref can be valid, in which case it can be used, or invalid to
640 // indicate that the statement hasn't been created yet, has an error, or has
641 // been destroyed.
642 //
Victor Costancfbfa602018-08-01 23:24:46643 // The Database may revoke a StatementRef in some error cases, so callers
[email protected]e5ffd0e42009-09-11 21:30:56644 // should always check validity before using.
Victor Costane56cc682018-12-27 01:53:46645 class COMPONENT_EXPORT(SQL) StatementRef
646 : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56647 public:
Victor Costan3b02cdf2018-07-18 00:39:56648 REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
649
Victor Costancfbfa602018-08-01 23:24:46650 // |database| is the sql::Database instance associated with
[email protected]41a97c812013-02-07 02:35:38651 // the statement, and is used for tracking outstanding statements
Victor Costanbd623112018-07-18 04:17:27652 // and for error handling. Set to nullptr for invalid or untracked
653 // refs. |stmt| is the actual statement, and should only be null
[email protected]41a97c812013-02-07 02:35:38654 // to create an invalid ref. |was_valid| indicates whether the
Etienne Bergeron95a01c2a2019-02-26 21:32:50655 // statement should be considered valid for diagnostic purposes.
Victor Costancfbfa602018-08-01 23:24:46656 // |was_valid| can be true for a null |stmt| if the Database has
[email protected]41a97c812013-02-07 02:35:38657 // been forcibly closed by an error handler.
Victor Costancfbfa602018-08-01 23:24:46658 StatementRef(Database* database, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56659
660 // When true, the statement can be used.
661 bool is_valid() const { return !!stmt_; }
662
[email protected]41a97c812013-02-07 02:35:38663 // When true, the statement is either currently valid, or was
Victor Costancfbfa602018-08-01 23:24:46664 // previously valid but the database was forcibly closed. Used
[email protected]41a97c812013-02-07 02:35:38665 // for diagnostic checks.
666 bool was_valid() const { return was_valid_; }
667
Victor Costancfbfa602018-08-01 23:24:46668 // If we've not been linked to a database, this will be null.
Victor Costanbd623112018-07-18 04:17:27669 //
Victor Costancfbfa602018-08-01 23:24:46670 // TODO(shess): database_ can be nullptr in case of
Victor Costanbd623112018-07-18 04:17:27671 // GetUntrackedStatement(), which prevents Statement::OnError() from
672 // forwarding errors.
Victor Costancfbfa602018-08-01 23:24:46673 Database* database() const { return database_; }
[email protected]e5ffd0e42009-09-11 21:30:56674
675 // Returns the sqlite statement if any. If the statement is not active,
Victor Costanbd623112018-07-18 04:17:27676 // this will return nullptr.
[email protected]e5ffd0e42009-09-11 21:30:56677 sqlite3_stmt* stmt() const { return stmt_; }
678
Victor Costanbd623112018-07-18 04:17:27679 // Destroys the compiled statement and sets it to nullptr. The statement
680 // will no longer be active. |forced| is used to indicate if
Victor Costancfbfa602018-08-01 23:24:46681 // orderly-shutdown checks should apply (see Database::RazeAndClose()).
[email protected]41a97c812013-02-07 02:35:38682 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56683
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54684 // Construct a ScopedBlockingCall to annotate IO calls, but only if
Etienne Bergerone7681c72020-01-17 00:51:20685 // database wasn't open in memory. ScopedBlockingCall uses |from_here| to
686 // declare its blocking execution scope (see https://www.crbug/934302).
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54687 void InitScopedBlockingCall(
Etienne Bergerone7681c72020-01-17 00:51:20688 const base::Location& from_here,
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54689 base::Optional<base::ScopedBlockingCall>* scoped_blocking_call) const {
Victor Costancfbfa602018-08-01 23:24:46690 if (database_)
Etienne Bergerone7681c72020-01-17 00:51:20691 database_->InitScopedBlockingCall(from_here, scoped_blocking_call);
Victor Costanc7e7f2e2018-07-18 20:07:55692 }
[email protected]35f7e5392012-07-27 19:54:50693
[email protected]e5ffd0e42009-09-11 21:30:56694 private:
[email protected]877d55d2009-11-05 21:53:08695 friend class base::RefCounted<StatementRef>;
696
697 ~StatementRef();
698
Victor Costancfbfa602018-08-01 23:24:46699 Database* database_;
[email protected]e5ffd0e42009-09-11 21:30:56700 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38701 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56702
703 DISALLOW_COPY_AND_ASSIGN(StatementRef);
704 };
705 friend class StatementRef;
706
707 // Executes a rollback statement, ignoring all transaction state. Used
708 // internally in the transaction management code.
709 void DoRollback();
710
711 // Called by a StatementRef when it's being created or destroyed. See
712 // open_statements_ below.
713 void StatementRefCreated(StatementRef* ref);
714 void StatementRefDeleted(StatementRef* ref);
715
[email protected]2f496b42013-09-26 18:36:58716 // Called when a sqlite function returns an error, which is passed
717 // as |err|. The return value is the error code to be reflected
Victor Costanbd623112018-07-18 04:17:27718 // back to client code. |stmt| is non-null if the error relates to
719 // an sql::Statement instance. |sql| is non-nullptr if the error
[email protected]2f496b42013-09-26 18:36:58720 // relates to non-statement sql code (Execute, for instance). Both
Victor Costanbd623112018-07-18 04:17:27721 // can be null, but both should never be set.
[email protected]2f496b42013-09-26 18:36:58722 // NOTE(shess): Originally, the return value was intended to allow
723 // error handlers to transparently convert errors into success.
724 // Unfortunately, transactions are not generally restartable, so
725 // this did not work out.
shess9e77283d2016-06-13 23:53:20726 int OnSqliteError(int err, Statement* stmt, const char* sql) const;
[email protected]faa604e2009-09-25 22:38:59727
[email protected]5b96f3772010-09-28 16:30:57728 // Like |Execute()|, but retries if the database is locked.
Victor Costancfbfa602018-08-01 23:24:46729 bool ExecuteWithTimeout(const char* sql,
730 base::TimeDelta ms_timeout) WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57731
shess9e77283d2016-06-13 23:53:20732 // Implementation helper for GetUniqueStatement() and GetUntrackedStatement().
733 // |tracking_db| is the db the resulting ref should register with for
Victor Costanbd623112018-07-18 04:17:27734 // outstanding statement tracking, which should be |this| to track or null to
shess9e77283d2016-06-13 23:53:20735 // not track.
Victor Costancfbfa602018-08-01 23:24:46736 scoped_refptr<StatementRef> GetStatementImpl(sql::Database* tracking_db,
737 const char* sql) const;
shess9e77283d2016-06-13 23:53:20738
739 // Helper for implementing const member functions. Like GetUniqueStatement(),
740 // except the StatementRef is not entered into |open_statements_|, so an
741 // outstanding StatementRef from this function can block closing the database.
742 // The StatementRef will not call OnSqliteError(), because that can call
743 // |error_callback_| which can close the database.
[email protected]2eec0a22012-07-24 01:59:58744 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
745
Victor Costancfbfa602018-08-01 23:24:46746 bool IntegrityCheckHelper(const char* pragma_sql,
747 std::vector<std::string>* messages)
748 WARN_UNUSED_RESULT;
[email protected]579446c2013-12-16 18:36:52749
shess7dbd4dee2015-10-06 17:39:16750 // Release page-cache memory if memory-mapped I/O is enabled and the database
751 // was changed. Passing true for |implicit_change_performed| allows
752 // overriding the change detection for cases like DDL (CREATE, DROP, etc),
753 // which do not participate in the total-rows-changed tracking.
754 void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
755
shessc8cd2a162015-10-22 20:30:46756 // Returns the results of sqlite3_db_filename(), which should match the path
757 // passed to Open().
758 base::FilePath DbPath() const;
759
shessc8cd2a162015-10-22 20:30:46760 // Helper to collect diagnostic info for a corrupt database.
761 std::string CollectCorruptionInfo();
762
763 // Helper to collect diagnostic info for errors.
764 std::string CollectErrorInfo(int error, Statement* stmt) const;
765
shessd90aeea82015-11-13 02:24:31766 // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors
767 // can make it unsafe to map a file, so the file is read using regular I/O,
768 // with any errors causing 0 (don't map anything) to be returned. If the
769 // entire file is read without error, a large value is returned which will
770 // allow the entire file to be mapped in most cases.
771 //
772 // Results are recorded in the database's meta table for future reference, so
773 // the file should only be read through once.
774 size_t GetAppropriateMmapSize();
775
shessa62504d2016-11-07 19:26:12776 // Helpers for GetAppropriateMmapSize().
777 bool GetMmapAltStatus(int64_t* status);
778 bool SetMmapAltStatus(int64_t status);
779
Victor Costanbd623112018-07-18 04:17:27780 // The actual sqlite database. Will be null before Init has been called or if
[email protected]e5ffd0e42009-09-11 21:30:56781 // Init resulted in an error.
Shubham Aggarwale2d6b60d2020-10-22 04:41:48782 sqlite3* db_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56783
Shubham Aggarwal7b60fe6e2020-10-15 06:00:28784 // TODO([email protected]): Make `options_` const after removing all
785 // setters.
786 DatabaseOptions options_;
[email protected]e5ffd0e42009-09-11 21:30:56787
Victor Costanc7e7f2e2018-07-18 20:07:55788 // Holds references to all cached statements so they remain active.
789 //
790 // flat_map is appropriate here because the codebase has ~400 cached
791 // statements, and each statement is at most one insertion in the map
792 // throughout a process' lifetime.
793 base::flat_map<StatementID, scoped_refptr<StatementRef>> statement_cache_;
[email protected]e5ffd0e42009-09-11 21:30:56794
795 // A list of all StatementRefs we've given out. Each ref must register with
796 // us when it's created or destroyed. This allows us to potentially close
797 // any open statements when we encounter an error.
Victor Costanc7e7f2e2018-07-18 20:07:55798 std::set<StatementRef*> open_statements_;
[email protected]e5ffd0e42009-09-11 21:30:56799
800 // Number of currently-nested transactions.
Shubham Aggarwale2d6b60d2020-10-22 04:41:48801 int transaction_nesting_ = 0;
[email protected]e5ffd0e42009-09-11 21:30:56802
803 // True if any of the currently nested transactions have been rolled back.
804 // When we get to the outermost transaction, this will determine if we do
805 // a rollback instead of a commit.
Shubham Aggarwale2d6b60d2020-10-22 04:41:48806 bool needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56807
[email protected]35f7e5392012-07-27 19:54:50808 // True if database is open with OpenInMemory(), False if database is open
809 // with Open().
Shubham Aggarwale2d6b60d2020-10-22 04:41:48810 bool in_memory_ = false;
[email protected]35f7e5392012-07-27 19:54:50811
Victor Costancfbfa602018-08-01 23:24:46812 // |true| if the Database was closed using RazeAndClose(). Used
[email protected]41a97c812013-02-07 02:35:38813 // to enable diagnostics to distinguish calls to never-opened
814 // databases (incorrect use of the API) from calls to once-valid
815 // databases.
Shubham Aggarwale2d6b60d2020-10-22 04:41:48816 bool poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:38817
shessa62504d2016-11-07 19:26:12818 // |true| to use alternate storage for tracking mmap status.
Shubham Aggarwale2d6b60d2020-10-22 04:41:48819 bool mmap_alt_status_ = false;
shessa62504d2016-11-07 19:26:12820
Victor Costancfbfa602018-08-01 23:24:46821 // |true| if SQLite memory-mapped I/O is not desired for this database.
shess7dbd4dee2015-10-06 17:39:16822 bool mmap_disabled_;
823
Victor Costancfbfa602018-08-01 23:24:46824 // |true| if SQLite memory-mapped I/O was enabled for this database.
shess7dbd4dee2015-10-06 17:39:16825 // Used by ReleaseCacheMemoryIfNeeded().
Shubham Aggarwale2d6b60d2020-10-22 04:41:48826 bool mmap_enabled_ = false;
shess7dbd4dee2015-10-06 17:39:16827
828 // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
829 // since memory was last released.
Shubham Aggarwale2d6b60d2020-10-22 04:41:48830 int total_changes_at_last_release_ = 0;
shess7dbd4dee2015-10-06 17:39:16831
[email protected]c3881b372013-05-17 08:39:46832 ErrorCallback error_callback_;
833
[email protected]210ce0af2013-05-15 09:10:39834 // Tag for auxiliary histograms.
835 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14836
shess58b8df82015-06-03 00:19:32837 // Linear histogram for RecordEvent().
Shubham Aggarwale2d6b60d2020-10-22 04:41:48838 base::HistogramBase* stats_histogram_ = nullptr;
shess58b8df82015-06-03 00:19:32839
ssid3be5b1ec2016-01-13 14:21:57840 // Stores the dump provider object when db is open.
Victor Costancfbfa602018-08-01 23:24:46841 std::unique_ptr<DatabaseMemoryDumpProvider> memory_dump_provider_;
ssid3be5b1ec2016-01-13 14:21:57842
Victor Costancfbfa602018-08-01 23:24:46843 DISALLOW_COPY_AND_ASSIGN(Database);
[email protected]e5ffd0e42009-09-11 21:30:56844};
845
846} // namespace sql
847
Victor Costancfbfa602018-08-01 23:24:46848#endif // SQL_DATABASE_H_