blob: cebf93b1300c3cbd13ae5a6ac9d92aa3a6c4d6e5 [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
[email protected]f0a54b22011-07-19 18:40:215#ifndef SQL_CONNECTION_H_
6#define SQL_CONNECTION_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>
[email protected]e5ffd0e42009-09-11 21:30:5610#include <map>
mostynbd82cd9952016-04-11 20:05:3411#include <memory>
[email protected]e5ffd0e42009-09-11 21:30:5612#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3313#include <string>
[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"
shessc8cd2a162015-10-22 20:30:4618#include "base/gtest_prod_util.h"
tfarina720d4f32015-05-11 22:31:2619#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1520#include "base/memory/ref_counted.h"
[email protected]35f7e5392012-07-27 19:54:5021#include "base/threading/thread_restrictions.h"
[email protected]2b59d682013-06-28 15:22:0322#include "base/time/time.h"
[email protected]d4526962011-11-10 21:40:2823#include "sql/sql_export.h"
[email protected]e5ffd0e42009-09-11 21:30:5624
[email protected]e5ffd0e42009-09-11 21:30:5625struct sqlite3;
26struct sqlite3_stmt;
27
[email protected]a3ef4832013-02-02 05:12:3328namespace base {
29class FilePath;
shess58b8df82015-06-03 00:19:3230class HistogramBase;
[email protected]a3ef4832013-02-02 05:12:3331}
32
[email protected]e5ffd0e42009-09-11 21:30:5633namespace sql {
34
ssid3be5b1ec2016-01-13 14:21:5735class ConnectionMemoryDumpProvider;
[email protected]8d409412013-07-19 18:25:3036class Recovery;
[email protected]e5ffd0e42009-09-11 21:30:5637class Statement;
38
shess58b8df82015-06-03 00:19:3239// To allow some test classes to be friended.
40namespace test {
41class ScopedCommitHook;
42class ScopedScalarFunction;
43class ScopedMockTimeSource;
44}
45
[email protected]e5ffd0e42009-09-11 21:30:5646// Uniquely identifies a statement. There are two modes of operation:
47//
48// - In the most common mode, you will use the source file and line number to
49// identify your statement. This is a convienient way to get uniqueness for
50// a statement that is only used in one place. Use the SQL_FROM_HERE macro
51// to generate a StatementID.
52//
53// - In the "custom" mode you may use the statement from different places or
54// need to manage it yourself for whatever reason. In this case, you should
55// make up your own unique name and pass it to the StatementID. This name
56// must be a static string, since this object only deals with pointers and
57// assumes the underlying string doesn't change or get deleted.
58//
59// This object is copyable and assignable using the compiler-generated
60// operator= and copy constructor.
61class StatementID {
62 public:
63 // Creates a uniquely named statement with the given file ane line number.
64 // Normally you will use SQL_FROM_HERE instead of calling yourself.
65 StatementID(const char* file, int line)
66 : number_(line),
67 str_(file) {
68 }
69
70 // Creates a uniquely named statement with the given user-defined name.
71 explicit StatementID(const char* unique_name)
72 : number_(-1),
73 str_(unique_name) {
74 }
75
76 // This constructor is unimplemented and will generate a linker error if
77 // called. It is intended to try to catch people dynamically generating
78 // a statement name that will be deallocated and will cause a crash later.
79 // All strings must be static and unchanging!
80 explicit StatementID(const std::string& dont_ever_do_this);
81
82 // We need this to insert into our map.
83 bool operator<(const StatementID& other) const;
84
85 private:
86 int number_;
87 const char* str_;
88};
89
90#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
91
[email protected]faa604e2009-09-25 22:38:5992class Connection;
93
shess58b8df82015-06-03 00:19:3294// Abstract the source of timing information for metrics (RecordCommitTime, etc)
95// to allow testing control.
96class SQL_EXPORT TimeSource {
97 public:
98 TimeSource() {}
99 virtual ~TimeSource() {}
100
101 // Return the current time (by default base::TimeTicks::Now()).
102 virtual base::TimeTicks Now();
103
104 private:
105 DISALLOW_COPY_AND_ASSIGN(TimeSource);
106};
107
ssid3be5b1ec2016-01-13 14:21:57108class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56109 private:
110 class StatementRef; // Forward declaration, see real one below.
111
112 public:
[email protected]765b44502009-10-02 05:01:42113 // The database is opened by calling Open[InMemory](). Any uncommitted
114 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56115 Connection();
ssid3be5b1ec2016-01-13 14:21:57116 ~Connection();
[email protected]e5ffd0e42009-09-11 21:30:56117
118 // Pre-init configuration ----------------------------------------------------
119
[email protected]765b44502009-10-02 05:01:42120 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56121 // must be called before Init(), and will only have an effect on new
122 // databases.
123 //
124 // From sqlite.org: "The page size must be a power of two greater than or
125 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
126 // value for SQLITE_MAX_PAGE_SIZE is 32768."
127 void set_page_size(int page_size) { page_size_ = page_size; }
128
129 // Sets the number of pages that will be cached in memory by sqlite. The
130 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42131 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56132 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
133
134 // Call to put the database in exclusive locking mode. There is no "back to
135 // normal" flag because of some additional requirements sqlite puts on this
[email protected]4ab952f2014-04-01 20:18:16136 // transaction (requires another access to the DB) and because we don't
[email protected]e5ffd0e42009-09-11 21:30:56137 // actually need it.
138 //
139 // Exclusive mode means that the database is not unlocked at the end of each
140 // transaction, which means there may be less time spent initializing the
141 // next transaction because it doesn't have to re-aquire locks.
142 //
[email protected]765b44502009-10-02 05:01:42143 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56144 void set_exclusive_locking() { exclusive_locking_ = true; }
145
[email protected]81a2a602013-07-17 19:10:36146 // Call to cause Open() to restrict access permissions of the
147 // database file to only the owner.
148 // TODO(shess): Currently only supported on OS_POSIX, is a noop on
149 // other platforms.
150 void set_restrict_to_user() { restrict_to_user_ = true; }
151
vichang7ce37c12016-01-28 22:09:03152 // Call to opt out of memory-mapped file I/O on per connection basis.
shess7dbd4dee2015-10-06 17:39:16153 void set_mmap_disabled() { mmap_disabled_ = true; }
154
vichang7ce37c12016-01-28 22:09:03155 // Call to opt out of memory-mapped file I/O on all connections.
156 static void set_mmap_disabled_by_default();
157
[email protected]c3881b372013-05-17 08:39:46158 // Set an error-handling callback. On errors, the error number (and
159 // statement, if available) will be passed to the callback.
160 //
161 // If no callback is set, the default action is to crash in debug
162 // mode or return failure in release mode.
[email protected]c3881b372013-05-17 08:39:46163 typedef base::Callback<void(int, Statement*)> ErrorCallback;
164 void set_error_callback(const ErrorCallback& callback) {
165 error_callback_ = callback;
166 }
[email protected]98cf3002013-07-12 01:38:56167 bool has_error_callback() const {
168 return !error_callback_.is_null();
169 }
[email protected]c3881b372013-05-17 08:39:46170 void reset_error_callback() {
171 error_callback_.Reset();
172 }
173
shess58b8df82015-06-03 00:19:32174 // Set this to enable additional per-connection histogramming. Must be called
175 // before Open().
176 void set_histogram_tag(const std::string& tag);
[email protected]c088e3a32013-01-03 23:59:14177
[email protected]210ce0af2013-05-15 09:10:39178 // Record a sparse UMA histogram sample under
179 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
180 // histogram is recorded.
181 void AddTaggedHistogram(const std::string& name, size_t sample) const;
182
shess58b8df82015-06-03 00:19:32183 // Track various API calls and results. Values corrospond to UMA
184 // histograms, do not modify, or add or delete other than directly
185 // before EVENT_MAX_VALUE.
186 enum Events {
187 // Number of statements run, either with sql::Statement or Execute*().
188 EVENT_STATEMENT_RUN = 0,
189
190 // Number of rows returned by statements run.
191 EVENT_STATEMENT_ROWS,
192
193 // Number of statements successfully run (all steps returned SQLITE_DONE or
194 // SQLITE_ROW).
195 EVENT_STATEMENT_SUCCESS,
196
197 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
198 EVENT_EXECUTE,
199
200 // Number of rows changed by autocommit statements.
201 EVENT_CHANGES_AUTOCOMMIT,
202
203 // Number of rows changed by statements in transactions.
204 EVENT_CHANGES,
205
206 // Count actual SQLite transaction statements (not including nesting).
207 EVENT_BEGIN,
208 EVENT_COMMIT,
209 EVENT_ROLLBACK,
210
shessd90aeea82015-11-13 02:24:31211 // Track success and failure in GetAppropriateMmapSize().
212 // GetAppropriateMmapSize() should record at most one of these per run. The
213 // case of mapping everything is not recorded.
214 EVENT_MMAP_META_MISSING, // No meta table present.
215 EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table.
216 EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table.
217 EVENT_MMAP_VFS_FAILURE, // Failed to access VFS.
218 EVENT_MMAP_FAILED, // Failure from past run.
219 EVENT_MMAP_FAILED_NEW, // Read error in this run.
220 EVENT_MMAP_SUCCESS_NEW, // Read to EOF in this run.
221 EVENT_MMAP_SUCCESS_PARTIAL, // Read but did not reach EOF.
222 EVENT_MMAP_SUCCESS_NO_PROGRESS, // Read quota exhausted.
223
shess58b8df82015-06-03 00:19:32224 // Leave this at the end.
225 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
226 EVENT_MAX_VALUE
227 };
228 void RecordEvent(Events event, size_t count);
229 void RecordOneEvent(Events event) {
230 RecordEvent(event, 1);
231 }
232
[email protected]579446c2013-12-16 18:36:52233 // Run "PRAGMA integrity_check" and post each line of
234 // results into |messages|. Returns the success of running the
235 // statement - per the SQLite documentation, if no errors are found the
236 // call should succeed, and a single value "ok" should be in messages.
237 bool FullIntegrityCheck(std::vector<std::string>* messages);
238
239 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
240 // interprets the results returning true if the the statement executes
241 // without error and results in a single "ok" value.
242 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42243
[email protected]e5ffd0e42009-09-11 21:30:56244 // Initialization ------------------------------------------------------------
245
246 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55247 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33248 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42249
250 // Initializes the SQL connection for a temporary in-memory database. There
251 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55252 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20253 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42254
[email protected]8d409412013-07-19 18:25:30255 // Create a temporary on-disk database. The database will be
256 // deleted after close. This kind of database is similar to
257 // OpenInMemory() for small databases, but can page to disk if the
258 // database becomes large.
259 bool OpenTemporary() WARN_UNUSED_RESULT;
260
[email protected]41a97c812013-02-07 02:35:38261 // Returns true if the database has been successfully opened.
[email protected]765b44502009-10-02 05:01:42262 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56263
264 // Closes the database. This is automatically performed on destruction for
265 // you, but this allows you to close the database early. You must not call
266 // any other functions after closing it. It is permissable to call Close on
267 // an uninitialized or already-closed database.
268 void Close();
269
[email protected]8ada10f2013-12-21 00:42:34270 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
271 // filesystem cache. This can be more efficient than faulting pages
272 // individually. Since this involves blocking I/O, it should only be used if
273 // the caller will immediately read a substantial amount of data from the
274 // database.
[email protected]e5ffd0e42009-09-11 21:30:56275 //
[email protected]8ada10f2013-12-21 00:42:34276 // TODO(shess): Design a set of histograms or an experiment to inform this
277 // decision. Preloading should almost always improve later performance
278 // numbers for this database simply because it pulls operations forward, but
279 // if the data isn't actually used soon then preloading just slows down
280 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56281 void Preload();
282
[email protected]be7995f12013-07-18 18:49:14283 // Try to trim the cache memory used by the database. If |aggressively| is
284 // true, this function will try to free all of the cache memory it can. If
285 // |aggressively| is false, this function will try to cut cache memory
286 // usage by half.
287 void TrimMemory(bool aggressively);
288
[email protected]8e0c01282012-04-06 19:36:49289 // Raze the database to the ground. This approximates creating a
290 // fresh database from scratch, within the constraints of SQLite's
291 // locking protocol (locks and open handles can make doing this with
292 // filesystem operations problematic). Returns true if the database
293 // was razed.
294 //
295 // false is returned if the database is locked by some other
296 // process. RazeWithTimeout() may be used if appropriate.
297 //
298 // NOTE(shess): Raze() will DCHECK in the following situations:
299 // - database is not open.
300 // - the connection has a transaction open.
301 // - a SQLite issue occurs which is structural in nature (like the
302 // statements used are broken).
303 // Since Raze() is expected to be called in unexpected situations,
304 // these all return false, since it is unlikely that the caller
305 // could fix them.
[email protected]6d42f152012-11-10 00:38:24306 //
307 // The database's page size is taken from |page_size_|. The
308 // existing database's |auto_vacuum| setting is lost (the
309 // possibility of corruption makes it unreliable to pull it from the
310 // existing database). To re-enable on the empty database requires
311 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
312 //
313 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
314 // so Raze() sets auto_vacuum to 1.
315 //
316 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
317 // TODO(shess): Bake auto_vacuum into Connection's API so it can
318 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49319 bool Raze();
320 bool RazeWithTimout(base::TimeDelta timeout);
321
[email protected]41a97c812013-02-07 02:35:38322 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30323 // BeginTransaction()), closes the SQLite database, and poisons the
324 // object so that all future operations against the Connection (or
325 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38326 //
[email protected]8d409412013-07-19 18:25:30327 // This is intended as an alternative to Close() in error callbacks.
328 // Close() should still be called at some point.
329 void Poison();
330
331 // Raze() the database and Poison() the handle. Returns the return
332 // value from Raze().
333 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38334 bool RazeAndClose();
335
[email protected]8d2e39e2013-06-24 05:55:08336 // Delete the underlying database files associated with |path|.
337 // This should be used on a database which has no existing
338 // connections. If any other connections are open to the same
339 // database, this could cause odd results or corruption (for
340 // instance if a hot journal is deleted but the associated database
341 // is not).
342 //
343 // Returns true if the database file and associated journals no
344 // longer exist, false otherwise. If the database has never
345 // existed, this will return true.
346 static bool Delete(const base::FilePath& path);
347
[email protected]e5ffd0e42009-09-11 21:30:56348 // Transactions --------------------------------------------------------------
349
350 // Transaction management. We maintain a virtual transaction stack to emulate
351 // nested transactions since sqlite can't do nested transactions. The
352 // limitation is you can't roll back a sub transaction: if any transaction
353 // fails, all transactions open will also be rolled back. Any nested
354 // transactions after one has rolled back will return fail for Begin(). If
355 // Begin() fails, you must not call Commit or Rollback().
356 //
357 // Normally you should use sql::Transaction to manage a transaction, which
358 // will scope it to a C++ context.
359 bool BeginTransaction();
360 void RollbackTransaction();
361 bool CommitTransaction();
362
[email protected]8d409412013-07-19 18:25:30363 // Rollback all outstanding transactions. Use with care, there may
364 // be scoped transactions on the stack.
365 void RollbackAllTransactions();
366
[email protected]e5ffd0e42009-09-11 21:30:56367 // Returns the current transaction nesting, which will be 0 if there are
368 // no open transactions.
369 int transaction_nesting() const { return transaction_nesting_; }
370
[email protected]8d409412013-07-19 18:25:30371 // Attached databases---------------------------------------------------------
372
373 // SQLite supports attaching multiple database files to a single
374 // handle. Attach the database in |other_db_path| to the current
375 // handle under |attachment_point|. |attachment_point| should only
376 // contain characters from [a-zA-Z0-9_].
377 //
378 // Note that calling attach or detach with an open transaction is an
379 // error.
380 bool AttachDatabase(const base::FilePath& other_db_path,
381 const char* attachment_point);
382 bool DetachDatabase(const char* attachment_point);
383
[email protected]e5ffd0e42009-09-11 21:30:56384 // Statements ----------------------------------------------------------------
385
386 // Executes the given SQL string, returning true on success. This is
387 // normally used for simple, 1-off statements that don't take any bound
388 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20389 //
[email protected]eff1fa522011-12-12 23:50:59390 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20391 //
392 // Do not use ignore_result() to ignore all errors. Use
393 // ExecuteAndReturnErrorCode() and ignore only specific errors.
394 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56395
[email protected]eff1fa522011-12-12 23:50:59396 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20397 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59398
[email protected]e5ffd0e42009-09-11 21:30:56399 // Returns true if we have a statement with the given identifier already
400 // cached. This is normally not necessary to call, but can be useful if the
401 // caller has to dynamically build up SQL to avoid doing so if it's already
402 // cached.
403 bool HasCachedStatement(const StatementID& id) const;
404
405 // Returns a statement for the given SQL using the statement cache. It can
406 // take a nontrivial amount of work to parse and compile a statement, so
407 // keeping commonly-used ones around for future use is important for
408 // performance.
409 //
[email protected]eff1fa522011-12-12 23:50:59410 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
411 // the code will crash in debug). The caller must deal with this eventuality,
412 // either by checking validity of the |sql| before calling, by correctly
413 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56414 //
415 // The StatementID and the SQL must always correspond to one-another. The
416 // ID is the lookup into the cache, so crazy things will happen if you use
417 // different SQL with the same ID.
418 //
419 // You will normally use the SQL_FROM_HERE macro to generate a statement
420 // ID associated with the current line of code. This gives uniqueness without
421 // you having to manage unique names. See StatementID above for more.
422 //
423 // Example:
[email protected]3273dce2010-01-27 16:08:08424 // sql::Statement stmt(connection_.GetCachedStatement(
425 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56426 // if (!stmt)
427 // return false; // Error creating statement.
428 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
429 const char* sql);
430
[email protected]eff1fa522011-12-12 23:50:59431 // Used to check a |sql| statement for syntactic validity. If the statement is
432 // valid SQL, returns true.
433 bool IsSQLValid(const char* sql);
434
[email protected]e5ffd0e42009-09-11 21:30:56435 // Returns a non-cached statement for the given SQL. Use this for SQL that
436 // is only executed once or only rarely (there is overhead associated with
437 // keeping a statement cached).
438 //
439 // See GetCachedStatement above for examples and error information.
440 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
441
442 // Info querying -------------------------------------------------------------
443
shess92a2ab12015-04-09 01:59:47444 // Returns true if the given table (or index) exists. Instead of
445 // test-then-create, callers should almost always prefer "CREATE TABLE IF NOT
446 // EXISTS" or "CREATE INDEX IF NOT EXISTS".
[email protected]765b44502009-10-02 05:01:42447 bool DoesTableExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53448 bool DoesIndexExist(const char* index_name) const;
449
[email protected]e5ffd0e42009-09-11 21:30:56450 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17451 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56452
453 // Returns sqlite's internal ID for the last inserted row. Valid only
454 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26455 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56456
[email protected]1ed78a32009-09-15 20:24:17457 // Returns sqlite's count of the number of rows modified by the last
458 // statement executed. Will be 0 if no statement has executed or the database
459 // is closed.
460 int GetLastChangeCount() const;
461
[email protected]e5ffd0e42009-09-11 21:30:56462 // Errors --------------------------------------------------------------------
463
464 // Returns the error code associated with the last sqlite operation.
465 int GetErrorCode() const;
466
[email protected]767718e52010-09-21 23:18:49467 // Returns the errno associated with GetErrorCode(). See
468 // SQLITE_LAST_ERRNO in SQLite documentation.
469 int GetLastErrno() const;
470
[email protected]e5ffd0e42009-09-11 21:30:56471 // Returns a pointer to a statically allocated string associated with the
472 // last sqlite operation.
473 const char* GetErrorMessage() const;
474
[email protected]92cd00a2013-08-16 11:09:58475 // Return a reproducible representation of the schema equivalent to
476 // running the following statement at a sqlite3 command-line:
477 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
478 std::string GetSchema() const;
479
[email protected]74cdede2013-09-25 05:39:57480 // Clients which provide an error_callback don't see the
481 // error-handling at the end of OnSqliteError(). Expose to allow
482 // those clients to work appropriately with ScopedErrorIgnorer in
483 // tests.
484 static bool ShouldIgnoreSqliteError(int error);
485
shessf7e988f2015-11-13 00:41:06486 // Additionally ignores errors which are unlikely to be caused by problems
487 // with the syntax of a SQL statement, or problems with the database schema.
488 static bool ShouldIgnoreSqliteCompileError(int error);
489
shessc8cd2a162015-10-22 20:30:46490 // Collect various diagnostic information and post a crash dump to aid
491 // debugging. Dump rate per database is limited to prevent overwhelming the
492 // crash server.
493 void ReportDiagnosticInfo(int extended_error, Statement* stmt);
494
[email protected]e5ffd0e42009-09-11 21:30:56495 private:
[email protected]8d409412013-07-19 18:25:30496 // For recovery module.
497 friend class Recovery;
498
[email protected]4350e322013-06-18 22:18:10499 // Allow test-support code to set/reset error ignorer.
500 friend class ScopedErrorIgnorer;
501
[email protected]eff1fa522011-12-12 23:50:59502 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56503 // (they should go through Statement).
504 friend class Statement;
505
shess58b8df82015-06-03 00:19:32506 friend class test::ScopedCommitHook;
507 friend class test::ScopedScalarFunction;
508 friend class test::ScopedMockTimeSource;
509
shessc8cd2a162015-10-22 20:30:46510 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, CollectDiagnosticInfo);
shess9bf2c672015-12-18 01:18:08511 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSize);
ssid3be5b1ec2016-01-13 14:21:57512 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, OnMemoryDump);
shessc8cd2a162015-10-22 20:30:46513 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, RegisterIntentToUpload);
514
[email protected]765b44502009-10-02 05:01:42515 // Internal initialize function used by both Init and InitInMemory. The file
516 // name is always 8 bits since we want to use the 8-bit version of
517 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13518 //
519 // |retry_flag| controls retrying the open if the error callback
520 // addressed errors using RazeAndClose().
521 enum Retry {
522 NO_RETRY = 0,
523 RETRY_ON_POISON
524 };
525 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42526
[email protected]41a97c812013-02-07 02:35:38527 // Internal close function used by Close() and RazeAndClose().
528 // |forced| indicates that orderly-shutdown checks should not apply.
529 void CloseInternal(bool forced);
530
[email protected]35f7e5392012-07-27 19:54:50531 // Check whether the current thread is allowed to make IO calls, but only
532 // if database wasn't open in memory. Function is inlined to be a no-op in
533 // official build.
shessc8cd2a162015-10-22 20:30:46534 void AssertIOAllowed() const {
[email protected]35f7e5392012-07-27 19:54:50535 if (!in_memory_)
536 base::ThreadRestrictions::AssertIOAllowed();
537 }
538
[email protected]e2cadec82011-12-13 02:00:53539 // Internal helper for DoesTableExist and DoesIndexExist.
540 bool DoesTableOrIndexExist(const char* name, const char* type) const;
541
[email protected]4350e322013-06-18 22:18:10542 // Accessors for global error-ignorer, for injecting behavior during tests.
543 // See test/scoped_error_ignorer.h.
544 typedef base::Callback<bool(int)> ErrorIgnorerCallback;
545 static ErrorIgnorerCallback* current_ignorer_cb_;
[email protected]4350e322013-06-18 22:18:10546 static void SetErrorIgnorer(ErrorIgnorerCallback* ignorer);
547 static void ResetErrorIgnorer();
548
[email protected]e5ffd0e42009-09-11 21:30:56549 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
550 // Refcounting allows us to give these statements out to sql::Statement
551 // objects while also optionally maintaining a cache of compiled statements
552 // by just keeping a refptr to these objects.
553 //
554 // A statement ref can be valid, in which case it can be used, or invalid to
555 // indicate that the statement hasn't been created yet, has an error, or has
556 // been destroyed.
557 //
558 // The Connection may revoke a StatementRef in some error cases, so callers
559 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23560 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56561 public:
[email protected]41a97c812013-02-07 02:35:38562 // |connection| is the sql::Connection instance associated with
563 // the statement, and is used for tracking outstanding statements
564 // and for error handling. Set to NULL for invalid or untracked
565 // refs. |stmt| is the actual statement, and should only be NULL
566 // to create an invalid ref. |was_valid| indicates whether the
567 // statement should be considered valid for diagnistic purposes.
568 // |was_valid| can be true for NULL |stmt| if the connection has
569 // been forcibly closed by an error handler.
570 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56571
572 // When true, the statement can be used.
573 bool is_valid() const { return !!stmt_; }
574
[email protected]41a97c812013-02-07 02:35:38575 // When true, the statement is either currently valid, or was
576 // previously valid but the connection was forcibly closed. Used
577 // for diagnostic checks.
578 bool was_valid() const { return was_valid_; }
579
[email protected]b4c363b2013-01-17 13:11:17580 // If we've not been linked to a connection, this will be NULL.
581 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
582 // which prevents Statement::OnError() from forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56583 Connection* connection() const { return connection_; }
584
585 // Returns the sqlite statement if any. If the statement is not active,
586 // this will return NULL.
587 sqlite3_stmt* stmt() const { return stmt_; }
588
589 // Destroys the compiled statement and marks it NULL. The statement will
[email protected]41a97c812013-02-07 02:35:38590 // no longer be active. |forced| is used to indicate if orderly-shutdown
591 // checks should apply (see Connection::RazeAndClose()).
592 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56593
[email protected]35f7e5392012-07-27 19:54:50594 // Check whether the current thread is allowed to make IO calls, but only
595 // if database wasn't open in memory.
596 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
597
[email protected]e5ffd0e42009-09-11 21:30:56598 private:
[email protected]877d55d2009-11-05 21:53:08599 friend class base::RefCounted<StatementRef>;
600
601 ~StatementRef();
602
[email protected]e5ffd0e42009-09-11 21:30:56603 Connection* connection_;
604 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38605 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56606
607 DISALLOW_COPY_AND_ASSIGN(StatementRef);
608 };
609 friend class StatementRef;
610
611 // Executes a rollback statement, ignoring all transaction state. Used
612 // internally in the transaction management code.
613 void DoRollback();
614
615 // Called by a StatementRef when it's being created or destroyed. See
616 // open_statements_ below.
617 void StatementRefCreated(StatementRef* ref);
618 void StatementRefDeleted(StatementRef* ref);
619
[email protected]2f496b42013-09-26 18:36:58620 // Called when a sqlite function returns an error, which is passed
621 // as |err|. The return value is the error code to be reflected
622 // back to client code. |stmt| is non-NULL if the error relates to
623 // an sql::Statement instance. |sql| is non-NULL if the error
624 // relates to non-statement sql code (Execute, for instance). Both
625 // can be NULL, but both should never be set.
626 // NOTE(shess): Originally, the return value was intended to allow
627 // error handlers to transparently convert errors into success.
628 // Unfortunately, transactions are not generally restartable, so
629 // this did not work out.
630 int OnSqliteError(int err, Statement* stmt, const char* sql);
[email protected]faa604e2009-09-25 22:38:59631
[email protected]5b96f3772010-09-28 16:30:57632 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20633 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
634 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57635
[email protected]2eec0a22012-07-24 01:59:58636 // Internal helper for const functions. Like GetUniqueStatement(),
637 // except the statement is not entered into open_statements_,
638 // allowing this function to be const. Open statements can block
639 // closing the database, so only use in cases where the last ref is
640 // released before close could be called (which should always be the
641 // case for const functions).
642 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
643
[email protected]579446c2013-12-16 18:36:52644 bool IntegrityCheckHelper(
645 const char* pragma_sql,
646 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
647
shess58b8df82015-06-03 00:19:32648 // Record time spent executing explicit COMMIT statements.
649 void RecordCommitTime(const base::TimeDelta& delta);
650
651 // Record time in DML (Data Manipulation Language) statements such as INSERT
652 // or UPDATE outside of an explicit transaction. Due to implementation
653 // limitations time spent on DDL (Data Definition Language) statements such as
654 // ALTER and CREATE is not included.
655 void RecordAutoCommitTime(const base::TimeDelta& delta);
656
657 // Record all time spent on updating the database. This includes CommitTime()
658 // and AutoCommitTime(), plus any time spent spilling to the journal if
659 // transactions do not fit in cache.
660 void RecordUpdateTime(const base::TimeDelta& delta);
661
662 // Record all time spent running statements, including time spent doing
663 // updates and time spent on read-only queries.
664 void RecordQueryTime(const base::TimeDelta& delta);
665
666 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
667 // true, autocommit time if the database is not in a transaction, or update
668 // time if the database is in a transaction. Also records change count to
669 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
670 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
671
672 // Helper to return the current time from the time source.
673 base::TimeTicks Now() {
674 return clock_->Now();
675 }
676
shess7dbd4dee2015-10-06 17:39:16677 // Release page-cache memory if memory-mapped I/O is enabled and the database
678 // was changed. Passing true for |implicit_change_performed| allows
679 // overriding the change detection for cases like DDL (CREATE, DROP, etc),
680 // which do not participate in the total-rows-changed tracking.
681 void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
682
shessc8cd2a162015-10-22 20:30:46683 // Returns the results of sqlite3_db_filename(), which should match the path
684 // passed to Open().
685 base::FilePath DbPath() const;
686
687 // Helper to prevent uploading too many diagnostic dumps for a given database,
688 // since every dump will likely show the same problem. Returns |true| if this
689 // function was not previously called for this database, and the persistent
690 // storage which tracks state was updated.
691 //
692 // |false| is returned if the function was previously called for this
693 // database, even across restarts. |false| is also returned if the persistent
694 // storage cannot be updated, possibly indicating problems requiring user or
695 // admin intervention, such as filesystem corruption or disk full. |false| is
696 // also returned if the persistent storage contains invalid data or is not
697 // readable.
698 //
699 // TODO(shess): It would make sense to reset the persistent state if the
700 // database is razed or recovered, or if the diagnostic code adds new
701 // capabilities.
702 bool RegisterIntentToUpload() const;
703
704 // Helper to collect diagnostic info for a corrupt database.
705 std::string CollectCorruptionInfo();
706
707 // Helper to collect diagnostic info for errors.
708 std::string CollectErrorInfo(int error, Statement* stmt) const;
709
shessd90aeea82015-11-13 02:24:31710 // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors
711 // can make it unsafe to map a file, so the file is read using regular I/O,
712 // with any errors causing 0 (don't map anything) to be returned. If the
713 // entire file is read without error, a large value is returned which will
714 // allow the entire file to be mapped in most cases.
715 //
716 // Results are recorded in the database's meta table for future reference, so
717 // the file should only be read through once.
718 size_t GetAppropriateMmapSize();
719
[email protected]e5ffd0e42009-09-11 21:30:56720 // The actual sqlite database. Will be NULL before Init has been called or if
721 // Init resulted in an error.
722 sqlite3* db_;
723
724 // Parameters we'll configure in sqlite before doing anything else. Zero means
725 // use the default value.
726 int page_size_;
727 int cache_size_;
728 bool exclusive_locking_;
[email protected]81a2a602013-07-17 19:10:36729 bool restrict_to_user_;
[email protected]e5ffd0e42009-09-11 21:30:56730
731 // All cached statements. Keeping a reference to these statements means that
732 // they'll remain active.
733 typedef std::map<StatementID, scoped_refptr<StatementRef> >
734 CachedStatementMap;
735 CachedStatementMap statement_cache_;
736
737 // A list of all StatementRefs we've given out. Each ref must register with
738 // us when it's created or destroyed. This allows us to potentially close
739 // any open statements when we encounter an error.
740 typedef std::set<StatementRef*> StatementRefSet;
741 StatementRefSet open_statements_;
742
743 // Number of currently-nested transactions.
744 int transaction_nesting_;
745
746 // True if any of the currently nested transactions have been rolled back.
747 // When we get to the outermost transaction, this will determine if we do
748 // a rollback instead of a commit.
749 bool needs_rollback_;
750
[email protected]35f7e5392012-07-27 19:54:50751 // True if database is open with OpenInMemory(), False if database is open
752 // with Open().
753 bool in_memory_;
754
[email protected]41a97c812013-02-07 02:35:38755 // |true| if the connection was closed using RazeAndClose(). Used
756 // to enable diagnostics to distinguish calls to never-opened
757 // databases (incorrect use of the API) from calls to once-valid
758 // databases.
759 bool poisoned_;
760
shess7dbd4dee2015-10-06 17:39:16761 // |true| if SQLite memory-mapped I/O is not desired for this connection.
762 bool mmap_disabled_;
763
764 // |true| if SQLite memory-mapped I/O was enabled for this connection.
765 // Used by ReleaseCacheMemoryIfNeeded().
766 bool mmap_enabled_;
767
768 // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
769 // since memory was last released.
770 int total_changes_at_last_release_;
771
[email protected]c3881b372013-05-17 08:39:46772 ErrorCallback error_callback_;
773
[email protected]210ce0af2013-05-15 09:10:39774 // Tag for auxiliary histograms.
775 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14776
shess58b8df82015-06-03 00:19:32777 // Linear histogram for RecordEvent().
778 base::HistogramBase* stats_histogram_;
779
780 // Histogram for tracking time taken in commit.
781 base::HistogramBase* commit_time_histogram_;
782
783 // Histogram for tracking time taken in autocommit updates.
784 base::HistogramBase* autocommit_time_histogram_;
785
786 // Histogram for tracking time taken in updates (including commit and
787 // autocommit).
788 base::HistogramBase* update_time_histogram_;
789
790 // Histogram for tracking time taken in all queries.
791 base::HistogramBase* query_time_histogram_;
792
793 // Source for timing information, provided to allow tests to inject time
794 // changes.
mostynbd82cd9952016-04-11 20:05:34795 std::unique_ptr<TimeSource> clock_;
shess58b8df82015-06-03 00:19:32796
ssid3be5b1ec2016-01-13 14:21:57797 // Stores the dump provider object when db is open.
mostynbd82cd9952016-04-11 20:05:34798 std::unique_ptr<ConnectionMemoryDumpProvider> memory_dump_provider_;
ssid3be5b1ec2016-01-13 14:21:57799
[email protected]e5ffd0e42009-09-11 21:30:56800 DISALLOW_COPY_AND_ASSIGN(Connection);
801};
802
803} // namespace sql
804
[email protected]f0a54b22011-07-19 18:40:21805#endif // SQL_CONNECTION_H_