[M85 Migration] Add an evas gl option for rotation
[platform/framework/web/chromium-efl.git] / sql / database.h
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.
4
5 #ifndef SQL_DATABASE_H_
6 #define SQL_DATABASE_H_
7
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <memory>
11 #include <set>
12 #include <string>
13 #include <utility>
14 #include <vector>
15
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/optional.h"
24 #include "base/sequence_checker.h"
25 #include "base/threading/scoped_blocking_call.h"
26 #include "sql/internal_api_token.h"
27 #include "sql/statement_id.h"
28
29 struct sqlite3;
30 struct sqlite3_stmt;
31
32 namespace base {
33 class FilePath;
34 class HistogramBase;
35 namespace trace_event {
36 class ProcessMemoryDump;
37 }  // namespace trace_event
38 }  // namespace base
39
40 namespace sql {
41
42 class DatabaseMemoryDumpProvider;
43 class Statement;
44
45 namespace test {
46 class ScopedErrorExpecter;
47 }  // namespace test
48
49 // Handle to an open SQLite database.
50 //
51 // Instances of this class are thread-unsafe and DCHECK that they are accessed
52 // on the same sequence.
53 class COMPONENT_EXPORT(SQL) Database {
54  private:
55   class StatementRef;  // Forward declaration, see real one below.
56
57  public:
58   // The database is opened by calling Open[InMemory](). Any uncommitted
59   // transactions will be rolled back when this object is deleted.
60   Database();
61   ~Database();
62
63   // Pre-init configuration ----------------------------------------------------
64
65   // Sets the page size that will be used when creating a new database. This
66   // must be called before Init(), and will only have an effect on new
67   // databases.
68   //
69   // The page size must be a power of two between 512 and 65536 inclusive.
70   void set_page_size(int page_size) {
71     DCHECK_GE(page_size, 512);
72     DCHECK_LE(page_size, 65536);
73     DCHECK(!(page_size & (page_size - 1)))
74         << "page_size must be a power of two";
75
76     page_size_ = page_size;
77   }
78
79   // The page size that will be used when creating a new database.
80   int page_size() const { return page_size_; }
81
82   // Sets the number of pages that will be cached in memory by sqlite. The
83   // total cache size in bytes will be page_size * cache_size. This must be
84   // called before Open() to have an effect.
85   void set_cache_size(int cache_size) {
86     DCHECK_GE(cache_size, 0);
87
88     cache_size_ = cache_size;
89   }
90
91   // Returns whether a database will be opened in WAL mode.
92   bool UseWALMode() const;
93
94   // Enables/disables WAL mode (https://www.sqlite.org/wal.html) when
95   // opening a new database.
96   //
97   // WAL mode is currently not fully supported on FuchsiaOS. It will only be
98   // turned on if the database is also using exclusive locking mode.
99   // (https://crbug.com/1082059)
100   //
101   // Note: Changing page size is not supported when in WAL mode. So running
102   // 'PRAGMA page_size = <new-size>' or using set_page_size will result in
103   // no-ops.
104   //
105   // This must be called before Open() to have an effect.
106   void want_wal_mode(bool enabled) { want_wal_mode_ = enabled; }
107
108   // Call to put the database in exclusive locking mode. There is no "back to
109   // normal" flag because of some additional requirements sqlite puts on this
110   // transaction (requires another access to the DB) and because we don't
111   // actually need it.
112   //
113   // Exclusive mode means that the database is not unlocked at the end of each
114   // transaction, which means there may be less time spent initializing the
115   // next transaction because it doesn't have to re-aquire locks.
116   //
117   // This must be called before Open() to have an effect.
118   void set_exclusive_locking() { exclusive_locking_ = true; }
119
120   // Call to use alternative status-tracking for mmap.  Usually this is tracked
121   // in the meta table, but some databases have no meta table.
122   // TODO(shess): Maybe just have all databases use the alt option?
123   void set_mmap_alt_status() { mmap_alt_status_ = true; }
124
125   // Opt out of memory-mapped file I/O.
126   void set_mmap_disabled() { mmap_disabled_ = true; }
127
128   // Set an error-handling callback.  On errors, the error number (and
129   // statement, if available) will be passed to the callback.
130   //
131   // If no callback is set, the default action is to crash in debug
132   // mode or return failure in release mode.
133   using ErrorCallback = base::RepeatingCallback<void(int, Statement*)>;
134   void set_error_callback(const ErrorCallback& callback) {
135     error_callback_ = callback;
136   }
137   bool has_error_callback() const { return !error_callback_.is_null(); }
138   void reset_error_callback() { error_callback_.Reset(); }
139
140   // Set this to enable additional per-database histogramming.  Must be called
141   // before Open().
142   void set_histogram_tag(const std::string& tag);
143
144   // Record a sparse UMA histogram sample under
145   // |name|+"."+|histogram_tag_|.  If |histogram_tag_| is empty, no
146   // histogram is recorded.
147   void AddTaggedHistogram(const std::string& name, int sample) const;
148
149   // Track various API calls and results.  Values correspond to UMA
150   // histograms, do not modify, or add or delete other than directly
151   // before EVENT_MAX_VALUE.
152   enum Events {
153     // Number of statements run, either with sql::Statement or Execute*().
154     EVENT_STATEMENT_RUN_DEPRECATED = 0,
155
156     // Number of rows returned by statements run.
157     EVENT_STATEMENT_ROWS_DEPRECATED,
158
159     // Number of statements successfully run (all steps returned SQLITE_DONE or
160     // SQLITE_ROW).
161     EVENT_STATEMENT_SUCCESS_DEPRECATED,
162
163     // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
164     EVENT_EXECUTE_DEPRECATED,
165
166     // Number of rows changed by autocommit statements.
167     EVENT_CHANGES_AUTOCOMMIT_DEPRECATED,
168
169     // Number of rows changed by statements in transactions.
170     EVENT_CHANGES_DEPRECATED,
171
172     // Count actual SQLite transaction statements (not including nesting).
173     EVENT_BEGIN_DEPRECATED,
174     EVENT_COMMIT_DEPRECATED,
175     EVENT_ROLLBACK_DEPRECATED,
176
177     // Track success and failure in GetAppropriateMmapSize().
178     // GetAppropriateMmapSize() should record at most one of these per run.  The
179     // case of mapping everything is not recorded.
180     EVENT_MMAP_META_MISSING,                    // No meta table present.
181     EVENT_MMAP_META_FAILURE_READ,               // Failed reading meta table.
182     EVENT_MMAP_META_FAILURE_UPDATE,             // Failed updating meta table.
183     EVENT_MMAP_VFS_FAILURE,                     // Failed to access VFS.
184     EVENT_MMAP_FAILED,                          // Failure from past run.
185     EVENT_MMAP_FAILED_NEW,                      // Read error in this run.
186     EVENT_MMAP_SUCCESS_NEW_DEPRECATED,          // Read to EOF in this run.
187     EVENT_MMAP_SUCCESS_PARTIAL_DEPRECATED,      // Read but did not reach EOF.
188     EVENT_MMAP_SUCCESS_NO_PROGRESS_DEPRECATED,  // Read quota exhausted.
189
190     EVENT_MMAP_STATUS_FAILURE_READ,    // Failure reading MmapStatus view.
191     EVENT_MMAP_STATUS_FAILURE_UPDATE,  // Failure updating MmapStatus view.
192
193     // Leave this at the end.
194     // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
195     EVENT_MAX_VALUE,
196   };
197   void RecordEvent(Events event, size_t count);
198   void RecordOneEvent(Events event) { RecordEvent(event, 1); }
199
200   // Run "PRAGMA integrity_check" and post each line of
201   // results into |messages|.  Returns the success of running the
202   // statement - per the SQLite documentation, if no errors are found the
203   // call should succeed, and a single value "ok" should be in messages.
204   bool FullIntegrityCheck(std::vector<std::string>* messages);
205
206   // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
207   // interprets the results returning true if the the statement executes
208   // without error and results in a single "ok" value.
209   bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
210
211   // Meant to be called from a client error callback so that it's able to
212   // get diagnostic information about the database.
213   std::string GetDiagnosticInfo(int extended_error, Statement* statement);
214
215   // Reports memory usage into provided memory dump with the given name.
216   bool ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
217                          const std::string& dump_name);
218
219   // Initialization ------------------------------------------------------------
220
221   // Initializes the SQL database for the given file, returning true if the
222   // file could be opened. You can call this or OpenInMemory.
223   bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
224
225   // Initializes the SQL database for a temporary in-memory database. There
226   // will be no associated file on disk, and the initial database will be
227   // empty. You can call this or Open.
228   bool OpenInMemory() WARN_UNUSED_RESULT;
229
230   // Create a temporary on-disk database.  The database will be
231   // deleted after close.  This kind of database is similar to
232   // OpenInMemory() for small databases, but can page to disk if the
233   // database becomes large.
234   bool OpenTemporary() WARN_UNUSED_RESULT;
235
236   // Returns true if the database has been successfully opened.
237   bool is_open() const { return static_cast<bool>(db_); }
238
239   // Closes the database. This is automatically performed on destruction for
240   // you, but this allows you to close the database early. You must not call
241   // any other functions after closing it. It is permissable to call Close on
242   // an uninitialized or already-closed database.
243   void Close();
244
245   // Reads the first <cache-size>*<page-size> bytes of the file to prime the
246   // filesystem cache.  This can be more efficient than faulting pages
247   // individually.  Since this involves blocking I/O, it should only be used if
248   // the caller will immediately read a substantial amount of data from the
249   // database.
250   //
251   // TODO(shess): Design a set of histograms or an experiment to inform this
252   // decision.  Preloading should almost always improve later performance
253   // numbers for this database simply because it pulls operations forward, but
254   // if the data isn't actually used soon then preloading just slows down
255   // everything else.
256   void Preload();
257
258   // Release all non-essential memory associated with this database connection.
259   void TrimMemory();
260
261   // Raze the database to the ground.  This approximates creating a
262   // fresh database from scratch, within the constraints of SQLite's
263   // locking protocol (locks and open handles can make doing this with
264   // filesystem operations problematic).  Returns true if the database
265   // was razed.
266   //
267   // false is returned if the database is locked by some other
268   // process.
269   //
270   // NOTE(shess): Raze() will DCHECK in the following situations:
271   // - database is not open.
272   // - the database has a transaction open.
273   // - a SQLite issue occurs which is structural in nature (like the
274   //   statements used are broken).
275   // Since Raze() is expected to be called in unexpected situations,
276   // these all return false, since it is unlikely that the caller
277   // could fix them.
278   //
279   // The database's page size is taken from |page_size_|.  The
280   // existing database's |auto_vacuum| setting is lost (the
281   // possibility of corruption makes it unreliable to pull it from the
282   // existing database).  To re-enable on the empty database requires
283   // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
284   //
285   // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
286   // so Raze() sets auto_vacuum to 1.
287   //
288   // TODO(shess): Raze() needs a database so cannot clear SQLITE_NOTADB.
289   // TODO(shess): Bake auto_vacuum into Database's API so it can
290   // just pick up the default.
291   bool Raze();
292
293   // Breaks all outstanding transactions (as initiated by
294   // BeginTransaction()), closes the SQLite database, and poisons the
295   // object so that all future operations against the Database (or
296   // its Statements) fail safely, without side effects.
297   //
298   // This is intended as an alternative to Close() in error callbacks.
299   // Close() should still be called at some point.
300   void Poison();
301
302   // Raze() the database and Poison() the handle.  Returns the return
303   // value from Raze().
304   // TODO(shess): Rename to RazeAndPoison().
305   bool RazeAndClose();
306
307   // Delete the underlying database files associated with |path|. This should be
308   // used on a database which is not opened by any Database instance. Open
309   // Database instances pointing to the database can cause odd results or
310   // corruption (for instance if a hot journal is deleted but the associated
311   // database is not).
312   //
313   // Returns true if the database file and associated journals no
314   // longer exist, false otherwise.  If the database has never
315   // existed, this will return true.
316   static bool Delete(const base::FilePath& path);
317
318   // Transactions --------------------------------------------------------------
319
320   // Transaction management. We maintain a virtual transaction stack to emulate
321   // nested transactions since sqlite can't do nested transactions. The
322   // limitation is you can't roll back a sub transaction: if any transaction
323   // fails, all transactions open will also be rolled back. Any nested
324   // transactions after one has rolled back will return fail for Begin(). If
325   // Begin() fails, you must not call Commit or Rollback().
326   //
327   // Normally you should use sql::Transaction to manage a transaction, which
328   // will scope it to a C++ context.
329   bool BeginTransaction();
330   void RollbackTransaction();
331   bool CommitTransaction();
332
333   // Rollback all outstanding transactions.  Use with care, there may
334   // be scoped transactions on the stack.
335   void RollbackAllTransactions();
336
337   // Returns the current transaction nesting, which will be 0 if there are
338   // no open transactions.
339   int transaction_nesting() const { return transaction_nesting_; }
340
341   // Attached databases---------------------------------------------------------
342
343   // SQLite supports attaching multiple database files to a single connection.
344   //
345   // Attach the database in |other_db_path| to the current connection under
346   // |attachment_point|. |attachment_point| must only contain characters from
347   // [a-zA-Z0-9_].
348   //
349   // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can
350   // be attached while a transaction is opened. However, these databases cannot
351   // be detached until the transaction is committed or aborted.
352   //
353   // These APIs are only exposed for use in recovery. They are extremely subtle
354   // and are not useful for features built on top of //sql.
355   bool AttachDatabase(const base::FilePath& other_db_path,
356                       const char* attachment_point,
357                       InternalApiToken);
358   bool DetachDatabase(const char* attachment_point, InternalApiToken);
359
360   // Statements ----------------------------------------------------------------
361
362   // Executes the given SQL string, returning true on success. This is
363   // normally used for simple, 1-off statements that don't take any bound
364   // parameters and don't return any data (e.g. CREATE TABLE).
365   //
366   // This will DCHECK if the |sql| contains errors.
367   //
368   // Do not use ignore_result() to ignore all errors.  Use
369   // ExecuteAndReturnErrorCode() and ignore only specific errors.
370   bool Execute(const char* sql) WARN_UNUSED_RESULT;
371
372   // Like Execute(), but returns the error code given by SQLite.
373   int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
374
375   // Returns a statement for the given SQL using the statement cache. It can
376   // take a nontrivial amount of work to parse and compile a statement, so
377   // keeping commonly-used ones around for future use is important for
378   // performance.
379   //
380   // The SQL_FROM_HERE macro is the recommended way of generating a StatementID.
381   // Code that generates custom IDs must ensure that a StatementID is never used
382   // for different SQL statements. Failing to meet this requirement results in
383   // incorrect behavior, and should be caught by a DCHECK.
384   //
385   // The SQL statement passed in |sql| must match the SQL statement reported
386   // back by SQLite. Mismatches are caught by a DCHECK, so any code that has
387   // automated test coverage or that was manually tested on a DCHECK build will
388   // not exhibit this problem. Mismatches generally imply that the statement
389   // passed in has extra whitespace or comments surrounding it, which waste
390   // storage and CPU cycles.
391   //
392   // If the |sql| has an error, an invalid, inert StatementRef is returned (and
393   // the code will crash in debug). The caller must deal with this eventuality,
394   // either by checking validity of the |sql| before calling, by correctly
395   // handling the return of an inert statement, or both.
396   //
397   // Example:
398   //   sql::Statement stmt(database_.GetCachedStatement(
399   //       SQL_FROM_HERE, "SELECT * FROM foo"));
400   //   if (!stmt)
401   //     return false;  // Error creating statement.
402   scoped_refptr<StatementRef> GetCachedStatement(StatementID id,
403                                                  const char* sql);
404
405   // Used to check a |sql| statement for syntactic validity. If the statement is
406   // valid SQL, returns true.
407   bool IsSQLValid(const char* sql);
408
409   // Returns a non-cached statement for the given SQL. Use this for SQL that
410   // is only executed once or only rarely (there is overhead associated with
411   // keeping a statement cached).
412   //
413   // See GetCachedStatement above for examples and error information.
414   scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
415
416   // Performs a passive checkpoint on the main attached database if it is in
417   // WAL mode. Returns true if the checkpoint was successful and false in case
418   // of an error. It is a no-op if the database is not in WAL mode.
419   //
420   // Note: Checkpointing is a very slow operation and will block any writes
421   // until it is finished. Please use with care.
422   bool CheckpointDatabase();
423
424   // Info querying -------------------------------------------------------------
425
426   // Returns true if the given structure exists.  Instead of test-then-create,
427   // callers should almost always prefer the "IF NOT EXISTS" version of the
428   // CREATE statement.
429   bool DoesIndexExist(const char* index_name) const;
430   bool DoesTableExist(const char* table_name) const;
431   bool DoesViewExist(const char* table_name) const;
432
433   // Returns true if a column with the given name exists in the given table.
434   //
435   // Calling this method on a VIEW returns an unspecified result.
436   //
437   // This should only be used by migration code for legacy features that do not
438   // use MetaTable, and need an alternative way of figuring out the database's
439   // current version.
440   bool DoesColumnExist(const char* table_name, const char* column_name) const;
441
442   // Returns sqlite's internal ID for the last inserted row. Valid only
443   // immediately after an insert.
444   int64_t GetLastInsertRowId() const;
445
446   // Returns sqlite's count of the number of rows modified by the last
447   // statement executed. Will be 0 if no statement has executed or the database
448   // is closed.
449   int GetLastChangeCount() const;
450
451   // Errors --------------------------------------------------------------------
452
453   // Returns the error code associated with the last sqlite operation.
454   int GetErrorCode() const;
455
456   // Returns the errno associated with GetErrorCode().  See
457   // SQLITE_LAST_ERRNO in SQLite documentation.
458   int GetLastErrno() const;
459
460   // Returns a pointer to a statically allocated string associated with the
461   // last sqlite operation.
462   const char* GetErrorMessage() const;
463
464   // Return a reproducible representation of the schema equivalent to
465   // running the following statement at a sqlite3 command-line:
466   //   SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
467   std::string GetSchema() const;
468
469   // Returns |true| if there is an error expecter (see SetErrorExpecter), and
470   // that expecter returns |true| when passed |error|.  Clients which provide an
471   // |error_callback| should use IsExpectedSqliteError() to check for unexpected
472   // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see
473   // OnSqliteError implementation).
474   static bool IsExpectedSqliteError(int error);
475
476   // Computes the path of a database's rollback journal.
477   //
478   // The journal file is created at the beginning of the database's first
479   // transaction. The file may be removed and re-created between transactions,
480   // depending on whether the database is opened in exclusive mode, and on
481   // configuration options. The journal file does not exist when the database
482   // operates in WAL mode.
483   //
484   // This is intended for internal use and tests. To preserve our ability to
485   // iterate on our SQLite configuration, features must avoid relying on
486   // the existence of specific files.
487   static base::FilePath JournalPath(const base::FilePath& db_path);
488
489   // Computes the path of a database's write-ahead log (WAL).
490   //
491   // The WAL file exists while a database is opened in WAL mode.
492   //
493   // This is intended for internal use and tests. To preserve our ability to
494   // iterate on our SQLite configuration, features must avoid relying on
495   // the existence of specific files.
496   static base::FilePath WriteAheadLogPath(const base::FilePath& db_path);
497
498   // Computes the path of a database's shared memory (SHM) file.
499   //
500   // The SHM file is used to coordinate between multiple processes using the
501   // same database in WAL mode. Thus, this file only exists for databases using
502   // WAL and not opened in exclusive mode.
503   //
504   // This is intended for internal use and tests. To preserve our ability to
505   // iterate on our SQLite configuration, features must avoid relying on
506   // the existence of specific files.
507   static base::FilePath SharedMemoryFilePath(const base::FilePath& db_path);
508
509   // Default page size for newly created databases.
510   //
511   // Guaranteed to match SQLITE_DEFAULT_PAGE_SIZE.
512   static constexpr int kDefaultPageSize = 4096;
513
514   // Internal state accessed by other classes in //sql.
515   sqlite3* db(InternalApiToken) const { return db_; }
516   bool poisoned(InternalApiToken) const { return poisoned_; }
517
518  private:
519   // Allow test-support code to set/reset error expecter.
520   friend class test::ScopedErrorExpecter;
521
522   // Statement accesses StatementRef which we don't want to expose to everybody
523   // (they should go through Statement).
524   friend class Statement;
525
526   FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CachedStatement);
527   FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CollectDiagnosticInfo);
528   FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSize);
529   FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSizeAltStatus);
530   FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, OnMemoryDump);
531   FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, RegisterIntentToUpload);
532   FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose);
533
534   // Internal initialize function used by both Init and InitInMemory. The file
535   // name is always 8 bits since we want to use the 8-bit version of
536   // sqlite3_open. The string can also be sqlite's special ":memory:" string.
537   //
538   // |retry_flag| controls retrying the open if the error callback
539   // addressed errors using RazeAndClose().
540   enum Retry { NO_RETRY = 0, RETRY_ON_POISON };
541   bool OpenInternal(const std::string& file_name, Retry retry_flag);
542
543   // Internal close function used by Close() and RazeAndClose().
544   // |forced| indicates that orderly-shutdown checks should not apply.
545   void CloseInternal(bool forced);
546
547   // Construct a ScopedBlockingCall to annotate IO calls, but only if
548   // database wasn't open in memory. ScopedBlockingCall uses |from_here| to
549   // declare its blocking execution scope (see https://www.crbug/934302).
550   void InitScopedBlockingCall(
551       const base::Location& from_here,
552       base::Optional<base::ScopedBlockingCall>* scoped_blocking_call) const {
553     if (!in_memory_)
554       scoped_blocking_call->emplace(from_here, base::BlockingType::MAY_BLOCK);
555   }
556
557   // Internal helper for Does*Exist() functions.
558   bool DoesSchemaItemExist(const char* name, const char* type) const;
559
560   // Accessors for global error-expecter, for injecting behavior during tests.
561   // See test/scoped_error_expecter.h.
562   using ErrorExpecterCallback = base::RepeatingCallback<bool(int)>;
563   static ErrorExpecterCallback* current_expecter_cb_;
564   static void SetErrorExpecter(ErrorExpecterCallback* expecter);
565   static void ResetErrorExpecter();
566
567   // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
568   // Refcounting allows us to give these statements out to sql::Statement
569   // objects while also optionally maintaining a cache of compiled statements
570   // by just keeping a refptr to these objects.
571   //
572   // A statement ref can be valid, in which case it can be used, or invalid to
573   // indicate that the statement hasn't been created yet, has an error, or has
574   // been destroyed.
575   //
576   // The Database may revoke a StatementRef in some error cases, so callers
577   // should always check validity before using.
578   class COMPONENT_EXPORT(SQL) StatementRef
579       : public base::RefCounted<StatementRef> {
580    public:
581     REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
582
583     // |database| is the sql::Database instance associated with
584     // the statement, and is used for tracking outstanding statements
585     // and for error handling.  Set to nullptr for invalid or untracked
586     // refs.  |stmt| is the actual statement, and should only be null
587     // to create an invalid ref.  |was_valid| indicates whether the
588     // statement should be considered valid for diagnostic purposes.
589     // |was_valid| can be true for a null |stmt| if the Database has
590     // been forcibly closed by an error handler.
591     StatementRef(Database* database, sqlite3_stmt* stmt, bool was_valid);
592
593     // When true, the statement can be used.
594     bool is_valid() const { return !!stmt_; }
595
596     // When true, the statement is either currently valid, or was
597     // previously valid but the database was forcibly closed.  Used
598     // for diagnostic checks.
599     bool was_valid() const { return was_valid_; }
600
601     // If we've not been linked to a database, this will be null.
602     //
603     // TODO(shess): database_ can be nullptr in case of
604     // GetUntrackedStatement(), which prevents Statement::OnError() from
605     // forwarding errors.
606     Database* database() const { return database_; }
607
608     // Returns the sqlite statement if any. If the statement is not active,
609     // this will return nullptr.
610     sqlite3_stmt* stmt() const { return stmt_; }
611
612     // Destroys the compiled statement and sets it to nullptr. The statement
613     // will no longer be active. |forced| is used to indicate if
614     // orderly-shutdown checks should apply (see Database::RazeAndClose()).
615     void Close(bool forced);
616
617     // Construct a ScopedBlockingCall to annotate IO calls, but only if
618     // database wasn't open in memory. ScopedBlockingCall uses |from_here| to
619     // declare its blocking execution scope (see https://www.crbug/934302).
620     void InitScopedBlockingCall(
621         const base::Location& from_here,
622         base::Optional<base::ScopedBlockingCall>* scoped_blocking_call) const {
623       if (database_)
624         database_->InitScopedBlockingCall(from_here, scoped_blocking_call);
625     }
626
627    private:
628     friend class base::RefCounted<StatementRef>;
629
630     ~StatementRef();
631
632     Database* database_;
633     sqlite3_stmt* stmt_;
634     bool was_valid_;
635
636     DISALLOW_COPY_AND_ASSIGN(StatementRef);
637   };
638   friend class StatementRef;
639
640   // Executes a rollback statement, ignoring all transaction state. Used
641   // internally in the transaction management code.
642   void DoRollback();
643
644   // Called by a StatementRef when it's being created or destroyed. See
645   // open_statements_ below.
646   void StatementRefCreated(StatementRef* ref);
647   void StatementRefDeleted(StatementRef* ref);
648
649   // Called when a sqlite function returns an error, which is passed
650   // as |err|.  The return value is the error code to be reflected
651   // back to client code.  |stmt| is non-null if the error relates to
652   // an sql::Statement instance.  |sql| is non-nullptr if the error
653   // relates to non-statement sql code (Execute, for instance).  Both
654   // can be null, but both should never be set.
655   // NOTE(shess): Originally, the return value was intended to allow
656   // error handlers to transparently convert errors into success.
657   // Unfortunately, transactions are not generally restartable, so
658   // this did not work out.
659   int OnSqliteError(int err, Statement* stmt, const char* sql) const;
660
661   // Like |Execute()|, but retries if the database is locked.
662   bool ExecuteWithTimeout(const char* sql,
663                           base::TimeDelta ms_timeout) WARN_UNUSED_RESULT;
664
665   // Implementation helper for GetUniqueStatement() and GetUntrackedStatement().
666   // |tracking_db| is the db the resulting ref should register with for
667   // outstanding statement tracking, which should be |this| to track or null to
668   // not track.
669   scoped_refptr<StatementRef> GetStatementImpl(sql::Database* tracking_db,
670                                                const char* sql) const;
671
672   // Helper for implementing const member functions.  Like GetUniqueStatement(),
673   // except the StatementRef is not entered into |open_statements_|, so an
674   // outstanding StatementRef from this function can block closing the database.
675   // The StatementRef will not call OnSqliteError(), because that can call
676   // |error_callback_| which can close the database.
677   scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
678
679   bool IntegrityCheckHelper(const char* pragma_sql,
680                             std::vector<std::string>* messages)
681       WARN_UNUSED_RESULT;
682
683   // Release page-cache memory if memory-mapped I/O is enabled and the database
684   // was changed.  Passing true for |implicit_change_performed| allows
685   // overriding the change detection for cases like DDL (CREATE, DROP, etc),
686   // which do not participate in the total-rows-changed tracking.
687   void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
688
689   // Returns the results of sqlite3_db_filename(), which should match the path
690   // passed to Open().
691   base::FilePath DbPath() const;
692
693   // Helper to collect diagnostic info for a corrupt database.
694   std::string CollectCorruptionInfo();
695
696   // Helper to collect diagnostic info for errors.
697   std::string CollectErrorInfo(int error, Statement* stmt) const;
698
699   // Calculates a value appropriate to pass to "PRAGMA mmap_size = ".  So errors
700   // can make it unsafe to map a file, so the file is read using regular I/O,
701   // with any errors causing 0 (don't map anything) to be returned.  If the
702   // entire file is read without error, a large value is returned which will
703   // allow the entire file to be mapped in most cases.
704   //
705   // Results are recorded in the database's meta table for future reference, so
706   // the file should only be read through once.
707   size_t GetAppropriateMmapSize();
708
709   // Helpers for GetAppropriateMmapSize().
710   bool GetMmapAltStatus(int64_t* status);
711   bool SetMmapAltStatus(int64_t status);
712
713   // The actual sqlite database. Will be null before Init has been called or if
714   // Init resulted in an error.
715   sqlite3* db_;
716
717   // Parameters we'll configure in sqlite before doing anything else. Zero means
718   // use the default value.
719   int page_size_;
720   int cache_size_;
721
722   bool exclusive_locking_;
723   bool want_wal_mode_;
724
725   // Holds references to all cached statements so they remain active.
726   //
727   // flat_map is appropriate here because the codebase has ~400 cached
728   // statements, and each statement is at most one insertion in the map
729   // throughout a process' lifetime.
730   base::flat_map<StatementID, scoped_refptr<StatementRef>> statement_cache_;
731
732   // A list of all StatementRefs we've given out. Each ref must register with
733   // us when it's created or destroyed. This allows us to potentially close
734   // any open statements when we encounter an error.
735   std::set<StatementRef*> open_statements_;
736
737   // Number of currently-nested transactions.
738   int transaction_nesting_;
739
740   // True if any of the currently nested transactions have been rolled back.
741   // When we get to the outermost transaction, this will determine if we do
742   // a rollback instead of a commit.
743   bool needs_rollback_;
744
745   // True if database is open with OpenInMemory(), False if database is open
746   // with Open().
747   bool in_memory_;
748
749   // |true| if the Database was closed using RazeAndClose().  Used
750   // to enable diagnostics to distinguish calls to never-opened
751   // databases (incorrect use of the API) from calls to once-valid
752   // databases.
753   bool poisoned_;
754
755   // |true| to use alternate storage for tracking mmap status.
756   bool mmap_alt_status_;
757
758   // |true| if SQLite memory-mapped I/O is not desired for this database.
759   bool mmap_disabled_;
760
761   // |true| if SQLite memory-mapped I/O was enabled for this database.
762   // Used by ReleaseCacheMemoryIfNeeded().
763   bool mmap_enabled_;
764
765   // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
766   // since memory was last released.
767   int total_changes_at_last_release_;
768
769   ErrorCallback error_callback_;
770
771   // Tag for auxiliary histograms.
772   std::string histogram_tag_;
773
774   // Linear histogram for RecordEvent().
775   base::HistogramBase* stats_histogram_;
776
777   // Stores the dump provider object when db is open.
778   std::unique_ptr<DatabaseMemoryDumpProvider> memory_dump_provider_;
779
780   DISALLOW_COPY_AND_ASSIGN(Database);
781 };
782
783 }  // namespace sql
784
785 #endif  // SQL_DATABASE_H_