1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef SQL_DATABASE_H_
6 #define SQL_DATABASE_H_
16 #include "base/callback.h"
17 #include "base/compiler_specific.h"
18 #include "base/component_export.h"
19 #include "base/containers/flat_map.h"
20 #include "base/gtest_prod_util.h"
21 #include "base/macros.h"
22 #include "base/memory/ref_counted.h"
23 #include "base/sequence_checker.h"
24 #include "base/threading/scoped_blocking_call.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/tick_clock.h"
27 #include "sql/internal_api_token.h"
28 #include "sql/statement_id.h"
36 namespace trace_event {
37 class ProcessMemoryDump;
38 } // namespace trace_event
43 class DatabaseMemoryDumpProvider;
46 // To allow some test classes to be friended.
48 class ScopedCommitHook;
49 class ScopedErrorExpecter;
50 class ScopedScalarFunction;
51 class ScopedMockTimeSource;
54 // Exposes private Database functionality to unit tests.
56 // This class is only defined in test targets.
57 class DatabaseTestPeer;
59 // Handle to an open SQLite database.
61 // Instances of this class are thread-unsafe and DCHECK that they are accessed
62 // on the same sequence.
64 // TODO(pwnall): This should be renamed to Database. Class instances are
65 // typically named "db_" / "db", and the class' equivalents in other systems
66 // used by Chrome are named LevelDB::DB and blink::IDBDatabase.
67 class COMPONENT_EXPORT(SQL) Database {
69 class StatementRef; // Forward declaration, see real one below.
72 // The database is opened by calling Open[InMemory](). Any uncommitted
73 // transactions will be rolled back when this object is deleted.
77 // Pre-init configuration ----------------------------------------------------
79 // Sets the page size that will be used when creating a new database. This
80 // must be called before Init(), and will only have an effect on new
83 // The page size must be a power of two between 512 and 65536 inclusive.
84 void set_page_size(int page_size) {
85 DCHECK_GE(page_size, 512);
86 DCHECK_LE(page_size, 65536);
87 DCHECK(!(page_size & (page_size - 1)))
88 << "page_size must be a power of two";
90 page_size_ = page_size;
93 // The page size that will be used when creating a new database.
94 int page_size() const { return page_size_; }
96 // Sets the number of pages that will be cached in memory by sqlite. The
97 // total cache size in bytes will be page_size * cache_size. This must be
98 // called before Open() to have an effect.
99 void set_cache_size(int cache_size) {
100 DCHECK_GE(cache_size, 0);
102 cache_size_ = cache_size;
105 // Call to put the database in exclusive locking mode. There is no "back to
106 // normal" flag because of some additional requirements sqlite puts on this
107 // transaction (requires another access to the DB) and because we don't
110 // Exclusive mode means that the database is not unlocked at the end of each
111 // transaction, which means there may be less time spent initializing the
112 // next transaction because it doesn't have to re-aquire locks.
114 // This must be called before Open() to have an effect.
115 void set_exclusive_locking() { exclusive_locking_ = true; }
117 // Call to use alternative status-tracking for mmap. Usually this is tracked
118 // in the meta table, but some databases have no meta table.
119 // TODO(shess): Maybe just have all databases use the alt option?
120 void set_mmap_alt_status() { mmap_alt_status_ = true; }
122 // Opt out of memory-mapped file I/O.
123 void set_mmap_disabled() { mmap_disabled_ = true; }
125 // Set an error-handling callback. On errors, the error number (and
126 // statement, if available) will be passed to the callback.
128 // If no callback is set, the default action is to crash in debug
129 // mode or return failure in release mode.
130 using ErrorCallback = base::RepeatingCallback<void(int, Statement*)>;
131 void set_error_callback(const ErrorCallback& callback) {
132 error_callback_ = callback;
134 bool has_error_callback() const { return !error_callback_.is_null(); }
135 void reset_error_callback() { error_callback_.Reset(); }
137 // Set this to enable additional per-database histogramming. Must be called
139 void set_histogram_tag(const std::string& tag);
141 // Record a sparse UMA histogram sample under
142 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
143 // histogram is recorded.
144 void AddTaggedHistogram(const std::string& name, int sample) const;
146 // Track various API calls and results. Values corrospond to UMA
147 // histograms, do not modify, or add or delete other than directly
148 // before EVENT_MAX_VALUE.
150 // Number of statements run, either with sql::Statement or Execute*().
151 EVENT_STATEMENT_RUN = 0,
153 // Number of rows returned by statements run.
154 EVENT_STATEMENT_ROWS,
156 // Number of statements successfully run (all steps returned SQLITE_DONE or
158 EVENT_STATEMENT_SUCCESS,
160 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
163 // Number of rows changed by autocommit statements.
164 EVENT_CHANGES_AUTOCOMMIT,
166 // Number of rows changed by statements in transactions.
169 // Count actual SQLite transaction statements (not including nesting).
174 // Track success and failure in GetAppropriateMmapSize().
175 // GetAppropriateMmapSize() should record at most one of these per run. The
176 // case of mapping everything is not recorded.
177 EVENT_MMAP_META_MISSING, // No meta table present.
178 EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table.
179 EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table.
180 EVENT_MMAP_VFS_FAILURE, // Failed to access VFS.
181 EVENT_MMAP_FAILED, // Failure from past run.
182 EVENT_MMAP_FAILED_NEW, // Read error in this run.
183 EVENT_MMAP_SUCCESS_NEW, // Read to EOF in this run.
184 EVENT_MMAP_SUCCESS_PARTIAL, // Read but did not reach EOF.
185 EVENT_MMAP_SUCCESS_NO_PROGRESS, // Read quota exhausted.
187 EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view.
188 EVENT_MMAP_STATUS_FAILURE_UPDATE, // Failure updating MmapStatus view.
190 // Leave this at the end.
191 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
194 void RecordEvent(Events event, size_t count);
195 void RecordOneEvent(Events event) { RecordEvent(event, 1); }
197 // Run "PRAGMA integrity_check" and post each line of
198 // results into |messages|. Returns the success of running the
199 // statement - per the SQLite documentation, if no errors are found the
200 // call should succeed, and a single value "ok" should be in messages.
201 bool FullIntegrityCheck(std::vector<std::string>* messages);
203 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
204 // interprets the results returning true if the the statement executes
205 // without error and results in a single "ok" value.
206 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
208 // Meant to be called from a client error callback so that it's able to
209 // get diagnostic information about the database.
210 std::string GetDiagnosticInfo(int extended_error, Statement* statement);
212 // Reports memory usage into provided memory dump with the given name.
213 bool ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
214 const std::string& dump_name);
216 // Initialization ------------------------------------------------------------
218 // Initializes the SQL database for the given file, returning true if the
219 // file could be opened. You can call this or OpenInMemory.
220 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
222 // Initializes the SQL database for a temporary in-memory database. There
223 // will be no associated file on disk, and the initial database will be
224 // empty. You can call this or Open.
225 bool OpenInMemory() WARN_UNUSED_RESULT;
227 // Create a temporary on-disk database. The database will be
228 // deleted after close. This kind of database is similar to
229 // OpenInMemory() for small databases, but can page to disk if the
230 // database becomes large.
231 bool OpenTemporary() WARN_UNUSED_RESULT;
233 // Returns true if the database has been successfully opened.
234 bool is_open() const { return static_cast<bool>(db_); }
236 // Closes the database. This is automatically performed on destruction for
237 // you, but this allows you to close the database early. You must not call
238 // any other functions after closing it. It is permissable to call Close on
239 // an uninitialized or already-closed database.
242 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
243 // filesystem cache. This can be more efficient than faulting pages
244 // individually. Since this involves blocking I/O, it should only be used if
245 // the caller will immediately read a substantial amount of data from the
248 // TODO(shess): Design a set of histograms or an experiment to inform this
249 // decision. Preloading should almost always improve later performance
250 // numbers for this database simply because it pulls operations forward, but
251 // if the data isn't actually used soon then preloading just slows down
255 // Release all non-essential memory associated with this database connection.
258 // Raze the database to the ground. This approximates creating a
259 // fresh database from scratch, within the constraints of SQLite's
260 // locking protocol (locks and open handles can make doing this with
261 // filesystem operations problematic). Returns true if the database
264 // false is returned if the database is locked by some other
267 // NOTE(shess): Raze() will DCHECK in the following situations:
268 // - database is not open.
269 // - the database has a transaction open.
270 // - a SQLite issue occurs which is structural in nature (like the
271 // statements used are broken).
272 // Since Raze() is expected to be called in unexpected situations,
273 // these all return false, since it is unlikely that the caller
276 // The database's page size is taken from |page_size_|. The
277 // existing database's |auto_vacuum| setting is lost (the
278 // possibility of corruption makes it unreliable to pull it from the
279 // existing database). To re-enable on the empty database requires
280 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
282 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
283 // so Raze() sets auto_vacuum to 1.
285 // TODO(shess): Raze() needs a database so cannot clear SQLITE_NOTADB.
286 // TODO(shess): Bake auto_vacuum into Database's API so it can
287 // just pick up the default.
290 // Breaks all outstanding transactions (as initiated by
291 // BeginTransaction()), closes the SQLite database, and poisons the
292 // object so that all future operations against the Database (or
293 // its Statements) fail safely, without side effects.
295 // This is intended as an alternative to Close() in error callbacks.
296 // Close() should still be called at some point.
299 // Raze() the database and Poison() the handle. Returns the return
300 // value from Raze().
301 // TODO(shess): Rename to RazeAndPoison().
304 // Delete the underlying database files associated with |path|. This should be
305 // used on a database which is not opened by any Database instance. Open
306 // Database instances pointing to the database can cause odd results or
307 // corruption (for instance if a hot journal is deleted but the associated
310 // Returns true if the database file and associated journals no
311 // longer exist, false otherwise. If the database has never
312 // existed, this will return true.
313 static bool Delete(const base::FilePath& path);
315 // Transactions --------------------------------------------------------------
317 // Transaction management. We maintain a virtual transaction stack to emulate
318 // nested transactions since sqlite can't do nested transactions. The
319 // limitation is you can't roll back a sub transaction: if any transaction
320 // fails, all transactions open will also be rolled back. Any nested
321 // transactions after one has rolled back will return fail for Begin(). If
322 // Begin() fails, you must not call Commit or Rollback().
324 // Normally you should use sql::Transaction to manage a transaction, which
325 // will scope it to a C++ context.
326 bool BeginTransaction();
327 void RollbackTransaction();
328 bool CommitTransaction();
330 // Rollback all outstanding transactions. Use with care, there may
331 // be scoped transactions on the stack.
332 void RollbackAllTransactions();
334 // Returns the current transaction nesting, which will be 0 if there are
335 // no open transactions.
336 int transaction_nesting() const { return transaction_nesting_; }
338 // Attached databases---------------------------------------------------------
340 // SQLite supports attaching multiple database files to a single connection.
342 // Attach the database in |other_db_path| to the current connection under
343 // |attachment_point|. |attachment_point| must only contain characters from
346 // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can
347 // be attached while a transaction is opened. However, these databases cannot
348 // be detached until the transaction is committed or aborted.
350 // These APIs are only exposed for use in recovery. They are extremely subtle
351 // and are not useful for features built on top of //sql.
352 bool AttachDatabase(const base::FilePath& other_db_path,
353 const char* attachment_point,
355 bool DetachDatabase(const char* attachment_point, InternalApiToken);
357 // Statements ----------------------------------------------------------------
359 // Executes the given SQL string, returning true on success. This is
360 // normally used for simple, 1-off statements that don't take any bound
361 // parameters and don't return any data (e.g. CREATE TABLE).
363 // This will DCHECK if the |sql| contains errors.
365 // Do not use ignore_result() to ignore all errors. Use
366 // ExecuteAndReturnErrorCode() and ignore only specific errors.
367 bool Execute(const char* sql) WARN_UNUSED_RESULT;
369 // Like Execute(), but returns the error code given by SQLite.
370 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
372 // Returns a statement for the given SQL using the statement cache. It can
373 // take a nontrivial amount of work to parse and compile a statement, so
374 // keeping commonly-used ones around for future use is important for
377 // The SQL_FROM_HERE macro is the recommended way of generating a StatementID.
378 // Code that generates custom IDs must ensure that a StatementID is never used
379 // for different SQL statements. Failing to meet this requirement results in
380 // incorrect behavior, and should be caught by a DCHECK.
382 // The SQL statement passed in |sql| must match the SQL statement reported
383 // back by SQLite. Mismatches are caught by a DCHECK, so any code that has
384 // automated test coverage or that was manually tested on a DCHECK build will
385 // not exhibit this problem. Mismatches generally imply that the statement
386 // passed in has extra whitespace or comments surrounding it, which waste
387 // storage and CPU cycles.
389 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
390 // the code will crash in debug). The caller must deal with this eventuality,
391 // either by checking validity of the |sql| before calling, by correctly
392 // handling the return of an inert statement, or both.
395 // sql::Statement stmt(database_.GetCachedStatement(
396 // SQL_FROM_HERE, "SELECT * FROM foo"));
398 // return false; // Error creating statement.
399 scoped_refptr<StatementRef> GetCachedStatement(StatementID id,
402 // Used to check a |sql| statement for syntactic validity. If the statement is
403 // valid SQL, returns true.
404 bool IsSQLValid(const char* sql);
406 // Returns a non-cached statement for the given SQL. Use this for SQL that
407 // is only executed once or only rarely (there is overhead associated with
408 // keeping a statement cached).
410 // See GetCachedStatement above for examples and error information.
411 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
413 // Info querying -------------------------------------------------------------
415 // Returns true if the given structure exists. Instead of test-then-create,
416 // callers should almost always prefer the "IF NOT EXISTS" version of the
418 bool DoesIndexExist(const char* index_name) const;
419 bool DoesTableExist(const char* table_name) const;
420 bool DoesViewExist(const char* table_name) const;
422 // Returns true if a column with the given name exists in the given table.
424 // Calling this method on a VIEW returns an unspecified result.
426 // This should only be used by migration code for legacy features that do not
427 // use MetaTable, and need an alternative way of figuring out the database's
429 bool DoesColumnExist(const char* table_name, const char* column_name) const;
431 // Returns sqlite's internal ID for the last inserted row. Valid only
432 // immediately after an insert.
433 int64_t GetLastInsertRowId() const;
435 // Returns sqlite's count of the number of rows modified by the last
436 // statement executed. Will be 0 if no statement has executed or the database
438 int GetLastChangeCount() const;
440 // Errors --------------------------------------------------------------------
442 // Returns the error code associated with the last sqlite operation.
443 int GetErrorCode() const;
445 // Returns the errno associated with GetErrorCode(). See
446 // SQLITE_LAST_ERRNO in SQLite documentation.
447 int GetLastErrno() const;
449 // Returns a pointer to a statically allocated string associated with the
450 // last sqlite operation.
451 const char* GetErrorMessage() const;
453 // Return a reproducible representation of the schema equivalent to
454 // running the following statement at a sqlite3 command-line:
455 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
456 std::string GetSchema() const;
458 // Returns |true| if there is an error expecter (see SetErrorExpecter), and
459 // that expecter returns |true| when passed |error|. Clients which provide an
460 // |error_callback| should use IsExpectedSqliteError() to check for unexpected
461 // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see
462 // OnSqliteError implementation).
463 static bool IsExpectedSqliteError(int error);
465 // Collect various diagnostic information and post a crash dump to aid
466 // debugging. Dump rate per database is limited to prevent overwhelming the
468 void ReportDiagnosticInfo(int extended_error, Statement* stmt);
470 // Helper to return the current time from the time source.
471 base::TimeTicks NowTicks() const { return clock_->NowTicks(); }
473 // Intended for tests to inject a mock time source.
475 // Inlined to avoid generating code in the production binary.
476 inline void set_clock_for_testing(std::unique_ptr<base::TickClock> clock) {
477 clock_ = std::move(clock);
480 // Computes the path of a database's rollback journal.
482 // The journal file is created at the beginning of the database's first
483 // transaction. The file may be removed and re-created between transactions,
484 // depending on whether the database is opened in exclusive mode, and on
485 // configuration options. The journal file does not exist when the database
486 // operates in WAL mode.
488 // This is intended for internal use and tests. To preserve our ability to
489 // iterate on our SQLite configuration, features must avoid relying on
490 // the existence of specific files.
491 static base::FilePath JournalPath(const base::FilePath& db_path);
493 // Computes the path of a database's write-ahead log (WAL).
495 // The WAL file exists while a database is opened in WAL mode.
497 // This is intended for internal use and tests. To preserve our ability to
498 // iterate on our SQLite configuration, features must avoid relying on
499 // the existence of specific files.
500 static base::FilePath WriteAheadLogPath(const base::FilePath& db_path);
502 // Computes the path of a database's shared memory (SHM) file.
504 // The SHM file is used to coordinate between multiple processes using the
505 // same database in WAL mode. Thus, this file only exists for databases using
506 // WAL and not opened in exclusive mode.
508 // This is intended for internal use and tests. To preserve our ability to
509 // iterate on our SQLite configuration, features must avoid relying on
510 // the existence of specific files.
511 static base::FilePath SharedMemoryFilePath(const base::FilePath& db_path);
513 // Default page size for newly created databases.
515 // Guaranteed to match SQLITE_DEFAULT_PAGE_SIZE.
516 static constexpr int kDefaultPageSize = 4096;
518 // Internal state accessed by other classes in //sql.
519 sqlite3* db(InternalApiToken) const { return db_; }
520 bool poisoned(InternalApiToken) const { return poisoned_; }
523 // Allow test-support code to set/reset error expecter.
524 friend class test::ScopedErrorExpecter;
526 // Statement accesses StatementRef which we don't want to expose to everybody
527 // (they should go through Statement).
528 friend class Statement;
530 friend class DatabaseTestPeer;
532 friend class test::ScopedCommitHook;
533 friend class test::ScopedScalarFunction;
534 friend class test::ScopedMockTimeSource;
536 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CachedStatement);
537 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CollectDiagnosticInfo);
538 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSize);
539 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSizeAltStatus);
540 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, OnMemoryDump);
541 FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, RegisterIntentToUpload);
542 FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose);
544 // Internal initialize function used by both Init and InitInMemory. The file
545 // name is always 8 bits since we want to use the 8-bit version of
546 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
548 // |retry_flag| controls retrying the open if the error callback
549 // addressed errors using RazeAndClose().
550 enum Retry { NO_RETRY = 0, RETRY_ON_POISON };
551 bool OpenInternal(const std::string& file_name, Retry retry_flag);
553 // Internal close function used by Close() and RazeAndClose().
554 // |forced| indicates that orderly-shutdown checks should not apply.
555 void CloseInternal(bool forced);
557 // Check whether the current thread is allowed to make IO calls, but only
558 // if database wasn't open in memory. Function is inlined to be a no-op in
560 void AssertIOAllowed() const {
562 base::AssertBlockingAllowedDeprecated();
565 // Internal helper for Does*Exist() functions.
566 bool DoesSchemaItemExist(const char* name, const char* type) const;
568 // Accessors for global error-expecter, for injecting behavior during tests.
569 // See test/scoped_error_expecter.h.
570 using ErrorExpecterCallback = base::RepeatingCallback<bool(int)>;
571 static ErrorExpecterCallback* current_expecter_cb_;
572 static void SetErrorExpecter(ErrorExpecterCallback* expecter);
573 static void ResetErrorExpecter();
575 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
576 // Refcounting allows us to give these statements out to sql::Statement
577 // objects while also optionally maintaining a cache of compiled statements
578 // by just keeping a refptr to these objects.
580 // A statement ref can be valid, in which case it can be used, or invalid to
581 // indicate that the statement hasn't been created yet, has an error, or has
584 // The Database may revoke a StatementRef in some error cases, so callers
585 // should always check validity before using.
586 class COMPONENT_EXPORT(SQL) StatementRef
587 : public base::RefCounted<StatementRef> {
589 REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
591 // |database| is the sql::Database instance associated with
592 // the statement, and is used for tracking outstanding statements
593 // and for error handling. Set to nullptr for invalid or untracked
594 // refs. |stmt| is the actual statement, and should only be null
595 // to create an invalid ref. |was_valid| indicates whether the
596 // statement should be considered valid for diagnistic purposes.
597 // |was_valid| can be true for a null |stmt| if the Database has
598 // been forcibly closed by an error handler.
599 StatementRef(Database* database, sqlite3_stmt* stmt, bool was_valid);
601 // When true, the statement can be used.
602 bool is_valid() const { return !!stmt_; }
604 // When true, the statement is either currently valid, or was
605 // previously valid but the database was forcibly closed. Used
606 // for diagnostic checks.
607 bool was_valid() const { return was_valid_; }
609 // If we've not been linked to a database, this will be null.
611 // TODO(shess): database_ can be nullptr in case of
612 // GetUntrackedStatement(), which prevents Statement::OnError() from
613 // forwarding errors.
614 Database* database() const { return database_; }
616 // Returns the sqlite statement if any. If the statement is not active,
617 // this will return nullptr.
618 sqlite3_stmt* stmt() const { return stmt_; }
620 // Destroys the compiled statement and sets it to nullptr. The statement
621 // will no longer be active. |forced| is used to indicate if
622 // orderly-shutdown checks should apply (see Database::RazeAndClose()).
623 void Close(bool forced);
625 // Check whether the current thread is allowed to make IO calls, but only
626 // if database wasn't open in memory.
627 void AssertIOAllowed() const {
629 database_->AssertIOAllowed();
633 friend class base::RefCounted<StatementRef>;
641 DISALLOW_COPY_AND_ASSIGN(StatementRef);
643 friend class StatementRef;
645 // Executes a rollback statement, ignoring all transaction state. Used
646 // internally in the transaction management code.
649 // Called by a StatementRef when it's being created or destroyed. See
650 // open_statements_ below.
651 void StatementRefCreated(StatementRef* ref);
652 void StatementRefDeleted(StatementRef* ref);
654 // Called when a sqlite function returns an error, which is passed
655 // as |err|. The return value is the error code to be reflected
656 // back to client code. |stmt| is non-null if the error relates to
657 // an sql::Statement instance. |sql| is non-nullptr if the error
658 // relates to non-statement sql code (Execute, for instance). Both
659 // can be null, but both should never be set.
660 // NOTE(shess): Originally, the return value was intended to allow
661 // error handlers to transparently convert errors into success.
662 // Unfortunately, transactions are not generally restartable, so
663 // this did not work out.
664 int OnSqliteError(int err, Statement* stmt, const char* sql) const;
666 // Like |Execute()|, but retries if the database is locked.
667 bool ExecuteWithTimeout(const char* sql,
668 base::TimeDelta ms_timeout) WARN_UNUSED_RESULT;
670 // Implementation helper for GetUniqueStatement() and GetUntrackedStatement().
671 // |tracking_db| is the db the resulting ref should register with for
672 // outstanding statement tracking, which should be |this| to track or null to
674 scoped_refptr<StatementRef> GetStatementImpl(sql::Database* tracking_db,
675 const char* sql) const;
677 // Helper for implementing const member functions. Like GetUniqueStatement(),
678 // except the StatementRef is not entered into |open_statements_|, so an
679 // outstanding StatementRef from this function can block closing the database.
680 // The StatementRef will not call OnSqliteError(), because that can call
681 // |error_callback_| which can close the database.
682 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
684 bool IntegrityCheckHelper(const char* pragma_sql,
685 std::vector<std::string>* messages)
688 // Record time spent executing explicit COMMIT statements.
689 void RecordCommitTime(const base::TimeDelta& delta);
691 // Record time in DML (Data Manipulation Language) statements such as INSERT
692 // or UPDATE outside of an explicit transaction. Due to implementation
693 // limitations time spent on DDL (Data Definition Language) statements such as
694 // ALTER and CREATE is not included.
695 void RecordAutoCommitTime(const base::TimeDelta& delta);
697 // Record all time spent on updating the database. This includes CommitTime()
698 // and AutoCommitTime(), plus any time spent spilling to the journal if
699 // transactions do not fit in cache.
700 void RecordUpdateTime(const base::TimeDelta& delta);
702 // Record all time spent running statements, including time spent doing
703 // updates and time spent on read-only queries.
704 void RecordQueryTime(const base::TimeDelta& delta);
706 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
707 // true, autocommit time if the database is not in a transaction, or update
708 // time if the database is in a transaction. Also records change count to
709 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
710 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
712 // Release page-cache memory if memory-mapped I/O is enabled and the database
713 // was changed. Passing true for |implicit_change_performed| allows
714 // overriding the change detection for cases like DDL (CREATE, DROP, etc),
715 // which do not participate in the total-rows-changed tracking.
716 void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
718 // Returns the results of sqlite3_db_filename(), which should match the path
720 base::FilePath DbPath() const;
722 // Helper to prevent uploading too many diagnostic dumps for a given database,
723 // since every dump will likely show the same problem. Returns |true| if this
724 // function was not previously called for this database, and the persistent
725 // storage which tracks state was updated.
727 // |false| is returned if the function was previously called for this
728 // database, even across restarts. |false| is also returned if the persistent
729 // storage cannot be updated, possibly indicating problems requiring user or
730 // admin intervention, such as filesystem corruption or disk full. |false| is
731 // also returned if the persistent storage contains invalid data or is not
734 // TODO(shess): It would make sense to reset the persistent state if the
735 // database is razed or recovered, or if the diagnostic code adds new
737 bool RegisterIntentToUpload() const;
739 // Helper to collect diagnostic info for a corrupt database.
740 std::string CollectCorruptionInfo();
742 // Helper to collect diagnostic info for errors.
743 std::string CollectErrorInfo(int error, Statement* stmt) const;
745 // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors
746 // can make it unsafe to map a file, so the file is read using regular I/O,
747 // with any errors causing 0 (don't map anything) to be returned. If the
748 // entire file is read without error, a large value is returned which will
749 // allow the entire file to be mapped in most cases.
751 // Results are recorded in the database's meta table for future reference, so
752 // the file should only be read through once.
753 size_t GetAppropriateMmapSize();
755 // Helpers for GetAppropriateMmapSize().
756 bool GetMmapAltStatus(int64_t* status);
757 bool SetMmapAltStatus(int64_t status);
759 // The actual sqlite database. Will be null before Init has been called or if
760 // Init resulted in an error.
763 // Parameters we'll configure in sqlite before doing anything else. Zero means
764 // use the default value.
767 bool exclusive_locking_;
769 // Holds references to all cached statements so they remain active.
771 // flat_map is appropriate here because the codebase has ~400 cached
772 // statements, and each statement is at most one insertion in the map
773 // throughout a process' lifetime.
774 base::flat_map<StatementID, scoped_refptr<StatementRef>> statement_cache_;
776 // A list of all StatementRefs we've given out. Each ref must register with
777 // us when it's created or destroyed. This allows us to potentially close
778 // any open statements when we encounter an error.
779 std::set<StatementRef*> open_statements_;
781 // Number of currently-nested transactions.
782 int transaction_nesting_;
784 // True if any of the currently nested transactions have been rolled back.
785 // When we get to the outermost transaction, this will determine if we do
786 // a rollback instead of a commit.
787 bool needs_rollback_;
789 // True if database is open with OpenInMemory(), False if database is open
793 // |true| if the Database was closed using RazeAndClose(). Used
794 // to enable diagnostics to distinguish calls to never-opened
795 // databases (incorrect use of the API) from calls to once-valid
799 // |true| to use alternate storage for tracking mmap status.
800 bool mmap_alt_status_;
802 // |true| if SQLite memory-mapped I/O is not desired for this database.
805 // |true| if SQLite memory-mapped I/O was enabled for this database.
806 // Used by ReleaseCacheMemoryIfNeeded().
809 // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
810 // since memory was last released.
811 int total_changes_at_last_release_;
813 ErrorCallback error_callback_;
815 // Tag for auxiliary histograms.
816 std::string histogram_tag_;
818 // Linear histogram for RecordEvent().
819 base::HistogramBase* stats_histogram_;
821 // Histogram for tracking time taken in commit.
822 base::HistogramBase* commit_time_histogram_;
824 // Histogram for tracking time taken in autocommit updates.
825 base::HistogramBase* autocommit_time_histogram_;
827 // Histogram for tracking time taken in updates (including commit and
829 base::HistogramBase* update_time_histogram_;
831 // Histogram for tracking time taken in all queries.
832 base::HistogramBase* query_time_histogram_;
834 // Source for timing information, provided to allow tests to inject time
836 std::unique_ptr<base::TickClock> clock_;
838 // Stores the dump provider object when db is open.
839 std::unique_ptr<DatabaseMemoryDumpProvider> memory_dump_provider_;
841 DISALLOW_COPY_AND_ASSIGN(Database);
846 #endif // SQL_DATABASE_H_