blob: 12e7041c9fd2fa10f7bec8c04b182c14c5d302ad [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;
shess976814402016-06-21 06:56:2542class ScopedErrorExpecter;
shess58b8df82015-06-03 00:19:3243class ScopedScalarFunction;
44class ScopedMockTimeSource;
45}
46
[email protected]e5ffd0e42009-09-11 21:30:5647// Uniquely identifies a statement. There are two modes of operation:
48//
49// - In the most common mode, you will use the source file and line number to
50// identify your statement. This is a convienient way to get uniqueness for
51// a statement that is only used in one place. Use the SQL_FROM_HERE macro
52// to generate a StatementID.
53//
54// - In the "custom" mode you may use the statement from different places or
55// need to manage it yourself for whatever reason. In this case, you should
56// make up your own unique name and pass it to the StatementID. This name
57// must be a static string, since this object only deals with pointers and
58// assumes the underlying string doesn't change or get deleted.
59//
60// This object is copyable and assignable using the compiler-generated
61// operator= and copy constructor.
62class StatementID {
63 public:
64 // Creates a uniquely named statement with the given file ane line number.
65 // Normally you will use SQL_FROM_HERE instead of calling yourself.
66 StatementID(const char* file, int line)
67 : number_(line),
68 str_(file) {
69 }
70
71 // Creates a uniquely named statement with the given user-defined name.
72 explicit StatementID(const char* unique_name)
73 : number_(-1),
74 str_(unique_name) {
75 }
76
77 // This constructor is unimplemented and will generate a linker error if
78 // called. It is intended to try to catch people dynamically generating
79 // a statement name that will be deallocated and will cause a crash later.
80 // All strings must be static and unchanging!
81 explicit StatementID(const std::string& dont_ever_do_this);
82
83 // We need this to insert into our map.
84 bool operator<(const StatementID& other) const;
85
86 private:
87 int number_;
88 const char* str_;
89};
90
91#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
92
[email protected]faa604e2009-09-25 22:38:5993class Connection;
94
shess58b8df82015-06-03 00:19:3295// Abstract the source of timing information for metrics (RecordCommitTime, etc)
96// to allow testing control.
97class SQL_EXPORT TimeSource {
98 public:
99 TimeSource() {}
100 virtual ~TimeSource() {}
101
102 // Return the current time (by default base::TimeTicks::Now()).
103 virtual base::TimeTicks Now();
104
105 private:
106 DISALLOW_COPY_AND_ASSIGN(TimeSource);
107};
108
ssid3be5b1ec2016-01-13 14:21:57109class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56110 private:
111 class StatementRef; // Forward declaration, see real one below.
112
113 public:
[email protected]765b44502009-10-02 05:01:42114 // The database is opened by calling Open[InMemory](). Any uncommitted
115 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56116 Connection();
ssid3be5b1ec2016-01-13 14:21:57117 ~Connection();
[email protected]e5ffd0e42009-09-11 21:30:56118
119 // Pre-init configuration ----------------------------------------------------
120
[email protected]765b44502009-10-02 05:01:42121 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56122 // must be called before Init(), and will only have an effect on new
123 // databases.
124 //
125 // From sqlite.org: "The page size must be a power of two greater than or
126 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
127 // value for SQLITE_MAX_PAGE_SIZE is 32768."
128 void set_page_size(int page_size) { page_size_ = page_size; }
129
130 // Sets the number of pages that will be cached in memory by sqlite. The
131 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42132 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56133 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
134
135 // Call to put the database in exclusive locking mode. There is no "back to
136 // normal" flag because of some additional requirements sqlite puts on this
[email protected]4ab952f2014-04-01 20:18:16137 // transaction (requires another access to the DB) and because we don't
[email protected]e5ffd0e42009-09-11 21:30:56138 // actually need it.
139 //
140 // Exclusive mode means that the database is not unlocked at the end of each
141 // transaction, which means there may be less time spent initializing the
142 // next transaction because it doesn't have to re-aquire locks.
143 //
[email protected]765b44502009-10-02 05:01:42144 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56145 void set_exclusive_locking() { exclusive_locking_ = true; }
146
[email protected]81a2a602013-07-17 19:10:36147 // Call to cause Open() to restrict access permissions of the
148 // database file to only the owner.
149 // TODO(shess): Currently only supported on OS_POSIX, is a noop on
150 // other platforms.
151 void set_restrict_to_user() { restrict_to_user_ = true; }
152
kerz42ff2a012016-04-27 04:50:06153 // Call to opt out of memory-mapped file I/O.
shess7dbd4dee2015-10-06 17:39:16154 void set_mmap_disabled() { mmap_disabled_ = true; }
155
[email protected]c3881b372013-05-17 08:39:46156 // Set an error-handling callback. On errors, the error number (and
157 // statement, if available) will be passed to the callback.
158 //
159 // If no callback is set, the default action is to crash in debug
160 // mode or return failure in release mode.
[email protected]c3881b372013-05-17 08:39:46161 typedef base::Callback<void(int, Statement*)> ErrorCallback;
162 void set_error_callback(const ErrorCallback& callback) {
163 error_callback_ = callback;
164 }
[email protected]98cf3002013-07-12 01:38:56165 bool has_error_callback() const {
166 return !error_callback_.is_null();
167 }
[email protected]c3881b372013-05-17 08:39:46168 void reset_error_callback() {
169 error_callback_.Reset();
170 }
171
shess58b8df82015-06-03 00:19:32172 // Set this to enable additional per-connection histogramming. Must be called
173 // before Open().
174 void set_histogram_tag(const std::string& tag);
[email protected]c088e3a32013-01-03 23:59:14175
[email protected]210ce0af2013-05-15 09:10:39176 // Record a sparse UMA histogram sample under
177 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
178 // histogram is recorded.
179 void AddTaggedHistogram(const std::string& name, size_t sample) const;
180
shess58b8df82015-06-03 00:19:32181 // Track various API calls and results. Values corrospond to UMA
182 // histograms, do not modify, or add or delete other than directly
183 // before EVENT_MAX_VALUE.
184 enum Events {
185 // Number of statements run, either with sql::Statement or Execute*().
186 EVENT_STATEMENT_RUN = 0,
187
188 // Number of rows returned by statements run.
189 EVENT_STATEMENT_ROWS,
190
191 // Number of statements successfully run (all steps returned SQLITE_DONE or
192 // SQLITE_ROW).
193 EVENT_STATEMENT_SUCCESS,
194
195 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
196 EVENT_EXECUTE,
197
198 // Number of rows changed by autocommit statements.
199 EVENT_CHANGES_AUTOCOMMIT,
200
201 // Number of rows changed by statements in transactions.
202 EVENT_CHANGES,
203
204 // Count actual SQLite transaction statements (not including nesting).
205 EVENT_BEGIN,
206 EVENT_COMMIT,
207 EVENT_ROLLBACK,
208
shessd90aeea82015-11-13 02:24:31209 // Track success and failure in GetAppropriateMmapSize().
210 // GetAppropriateMmapSize() should record at most one of these per run. The
211 // case of mapping everything is not recorded.
212 EVENT_MMAP_META_MISSING, // No meta table present.
213 EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table.
214 EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table.
215 EVENT_MMAP_VFS_FAILURE, // Failed to access VFS.
216 EVENT_MMAP_FAILED, // Failure from past run.
217 EVENT_MMAP_FAILED_NEW, // Read error in this run.
218 EVENT_MMAP_SUCCESS_NEW, // Read to EOF in this run.
219 EVENT_MMAP_SUCCESS_PARTIAL, // Read but did not reach EOF.
220 EVENT_MMAP_SUCCESS_NO_PROGRESS, // Read quota exhausted.
221
shess58b8df82015-06-03 00:19:32222 // Leave this at the end.
223 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
224 EVENT_MAX_VALUE
225 };
226 void RecordEvent(Events event, size_t count);
227 void RecordOneEvent(Events event) {
228 RecordEvent(event, 1);
229 }
230
[email protected]579446c2013-12-16 18:36:52231 // Run "PRAGMA integrity_check" and post each line of
232 // results into |messages|. Returns the success of running the
233 // statement - per the SQLite documentation, if no errors are found the
234 // call should succeed, and a single value "ok" should be in messages.
235 bool FullIntegrityCheck(std::vector<std::string>* messages);
236
237 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
238 // interprets the results returning true if the the statement executes
239 // without error and results in a single "ok" value.
240 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42241
[email protected]e5ffd0e42009-09-11 21:30:56242 // Initialization ------------------------------------------------------------
243
244 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55245 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33246 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42247
248 // Initializes the SQL connection for a temporary in-memory database. There
249 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55250 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20251 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42252
[email protected]8d409412013-07-19 18:25:30253 // Create a temporary on-disk database. The database will be
254 // deleted after close. This kind of database is similar to
255 // OpenInMemory() for small databases, but can page to disk if the
256 // database becomes large.
257 bool OpenTemporary() WARN_UNUSED_RESULT;
258
[email protected]41a97c812013-02-07 02:35:38259 // Returns true if the database has been successfully opened.
[email protected]765b44502009-10-02 05:01:42260 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56261
262 // Closes the database. This is automatically performed on destruction for
263 // you, but this allows you to close the database early. You must not call
264 // any other functions after closing it. It is permissable to call Close on
265 // an uninitialized or already-closed database.
266 void Close();
267
[email protected]8ada10f2013-12-21 00:42:34268 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
269 // filesystem cache. This can be more efficient than faulting pages
270 // individually. Since this involves blocking I/O, it should only be used if
271 // the caller will immediately read a substantial amount of data from the
272 // database.
[email protected]e5ffd0e42009-09-11 21:30:56273 //
[email protected]8ada10f2013-12-21 00:42:34274 // TODO(shess): Design a set of histograms or an experiment to inform this
275 // decision. Preloading should almost always improve later performance
276 // numbers for this database simply because it pulls operations forward, but
277 // if the data isn't actually used soon then preloading just slows down
278 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56279 void Preload();
280
[email protected]be7995f12013-07-18 18:49:14281 // Try to trim the cache memory used by the database. If |aggressively| is
282 // true, this function will try to free all of the cache memory it can. If
283 // |aggressively| is false, this function will try to cut cache memory
284 // usage by half.
285 void TrimMemory(bool aggressively);
286
[email protected]8e0c01282012-04-06 19:36:49287 // Raze the database to the ground. This approximates creating a
288 // fresh database from scratch, within the constraints of SQLite's
289 // locking protocol (locks and open handles can make doing this with
290 // filesystem operations problematic). Returns true if the database
291 // was razed.
292 //
293 // false is returned if the database is locked by some other
294 // process. RazeWithTimeout() may be used if appropriate.
295 //
296 // NOTE(shess): Raze() will DCHECK in the following situations:
297 // - database is not open.
298 // - the connection has a transaction open.
299 // - a SQLite issue occurs which is structural in nature (like the
300 // statements used are broken).
301 // Since Raze() is expected to be called in unexpected situations,
302 // these all return false, since it is unlikely that the caller
303 // could fix them.
[email protected]6d42f152012-11-10 00:38:24304 //
305 // The database's page size is taken from |page_size_|. The
306 // existing database's |auto_vacuum| setting is lost (the
307 // possibility of corruption makes it unreliable to pull it from the
308 // existing database). To re-enable on the empty database requires
309 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
310 //
311 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
312 // so Raze() sets auto_vacuum to 1.
313 //
314 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
315 // TODO(shess): Bake auto_vacuum into Connection's API so it can
316 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49317 bool Raze();
318 bool RazeWithTimout(base::TimeDelta timeout);
319
[email protected]41a97c812013-02-07 02:35:38320 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30321 // BeginTransaction()), closes the SQLite database, and poisons the
322 // object so that all future operations against the Connection (or
323 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38324 //
[email protected]8d409412013-07-19 18:25:30325 // This is intended as an alternative to Close() in error callbacks.
326 // Close() should still be called at some point.
327 void Poison();
328
329 // Raze() the database and Poison() the handle. Returns the return
330 // value from Raze().
331 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38332 bool RazeAndClose();
333
[email protected]8d2e39e2013-06-24 05:55:08334 // Delete the underlying database files associated with |path|.
335 // This should be used on a database which has no existing
336 // connections. If any other connections are open to the same
337 // database, this could cause odd results or corruption (for
338 // instance if a hot journal is deleted but the associated database
339 // is not).
340 //
341 // Returns true if the database file and associated journals no
342 // longer exist, false otherwise. If the database has never
343 // existed, this will return true.
344 static bool Delete(const base::FilePath& path);
345
[email protected]e5ffd0e42009-09-11 21:30:56346 // Transactions --------------------------------------------------------------
347
348 // Transaction management. We maintain a virtual transaction stack to emulate
349 // nested transactions since sqlite can't do nested transactions. The
350 // limitation is you can't roll back a sub transaction: if any transaction
351 // fails, all transactions open will also be rolled back. Any nested
352 // transactions after one has rolled back will return fail for Begin(). If
353 // Begin() fails, you must not call Commit or Rollback().
354 //
355 // Normally you should use sql::Transaction to manage a transaction, which
356 // will scope it to a C++ context.
357 bool BeginTransaction();
358 void RollbackTransaction();
359 bool CommitTransaction();
360
[email protected]8d409412013-07-19 18:25:30361 // Rollback all outstanding transactions. Use with care, there may
362 // be scoped transactions on the stack.
363 void RollbackAllTransactions();
364
[email protected]e5ffd0e42009-09-11 21:30:56365 // Returns the current transaction nesting, which will be 0 if there are
366 // no open transactions.
367 int transaction_nesting() const { return transaction_nesting_; }
368
[email protected]8d409412013-07-19 18:25:30369 // Attached databases---------------------------------------------------------
370
371 // SQLite supports attaching multiple database files to a single
372 // handle. Attach the database in |other_db_path| to the current
373 // handle under |attachment_point|. |attachment_point| should only
374 // contain characters from [a-zA-Z0-9_].
375 //
376 // Note that calling attach or detach with an open transaction is an
377 // error.
378 bool AttachDatabase(const base::FilePath& other_db_path,
379 const char* attachment_point);
380 bool DetachDatabase(const char* attachment_point);
381
[email protected]e5ffd0e42009-09-11 21:30:56382 // Statements ----------------------------------------------------------------
383
384 // Executes the given SQL string, returning true on success. This is
385 // normally used for simple, 1-off statements that don't take any bound
386 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20387 //
[email protected]eff1fa522011-12-12 23:50:59388 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20389 //
390 // Do not use ignore_result() to ignore all errors. Use
391 // ExecuteAndReturnErrorCode() and ignore only specific errors.
392 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56393
[email protected]eff1fa522011-12-12 23:50:59394 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20395 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59396
[email protected]e5ffd0e42009-09-11 21:30:56397 // Returns true if we have a statement with the given identifier already
398 // cached. This is normally not necessary to call, but can be useful if the
399 // caller has to dynamically build up SQL to avoid doing so if it's already
400 // cached.
401 bool HasCachedStatement(const StatementID& id) const;
402
403 // Returns a statement for the given SQL using the statement cache. It can
404 // take a nontrivial amount of work to parse and compile a statement, so
405 // keeping commonly-used ones around for future use is important for
406 // performance.
407 //
[email protected]eff1fa522011-12-12 23:50:59408 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
409 // the code will crash in debug). The caller must deal with this eventuality,
410 // either by checking validity of the |sql| before calling, by correctly
411 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56412 //
413 // The StatementID and the SQL must always correspond to one-another. The
414 // ID is the lookup into the cache, so crazy things will happen if you use
415 // different SQL with the same ID.
416 //
417 // You will normally use the SQL_FROM_HERE macro to generate a statement
418 // ID associated with the current line of code. This gives uniqueness without
419 // you having to manage unique names. See StatementID above for more.
420 //
421 // Example:
[email protected]3273dce2010-01-27 16:08:08422 // sql::Statement stmt(connection_.GetCachedStatement(
423 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56424 // if (!stmt)
425 // return false; // Error creating statement.
426 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
427 const char* sql);
428
[email protected]eff1fa522011-12-12 23:50:59429 // Used to check a |sql| statement for syntactic validity. If the statement is
430 // valid SQL, returns true.
431 bool IsSQLValid(const char* sql);
432
[email protected]e5ffd0e42009-09-11 21:30:56433 // Returns a non-cached statement for the given SQL. Use this for SQL that
434 // is only executed once or only rarely (there is overhead associated with
435 // keeping a statement cached).
436 //
437 // See GetCachedStatement above for examples and error information.
438 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
439
440 // Info querying -------------------------------------------------------------
441
shess92a2ab12015-04-09 01:59:47442 // Returns true if the given table (or index) exists. Instead of
443 // test-then-create, callers should almost always prefer "CREATE TABLE IF NOT
444 // EXISTS" or "CREATE INDEX IF NOT EXISTS".
[email protected]765b44502009-10-02 05:01:42445 bool DoesTableExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53446 bool DoesIndexExist(const char* index_name) const;
447
[email protected]e5ffd0e42009-09-11 21:30:56448 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17449 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56450
451 // Returns sqlite's internal ID for the last inserted row. Valid only
452 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26453 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56454
[email protected]1ed78a32009-09-15 20:24:17455 // Returns sqlite's count of the number of rows modified by the last
456 // statement executed. Will be 0 if no statement has executed or the database
457 // is closed.
458 int GetLastChangeCount() const;
459
[email protected]e5ffd0e42009-09-11 21:30:56460 // Errors --------------------------------------------------------------------
461
462 // Returns the error code associated with the last sqlite operation.
463 int GetErrorCode() const;
464
[email protected]767718e52010-09-21 23:18:49465 // Returns the errno associated with GetErrorCode(). See
466 // SQLITE_LAST_ERRNO in SQLite documentation.
467 int GetLastErrno() const;
468
[email protected]e5ffd0e42009-09-11 21:30:56469 // Returns a pointer to a statically allocated string associated with the
470 // last sqlite operation.
471 const char* GetErrorMessage() const;
472
[email protected]92cd00a2013-08-16 11:09:58473 // Return a reproducible representation of the schema equivalent to
474 // running the following statement at a sqlite3 command-line:
475 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
476 std::string GetSchema() const;
477
shess976814402016-06-21 06:56:25478 // Returns |true| if there is an error expecter (see SetErrorExpecter), and
479 // that expecter returns |true| when passed |error|. Clients which provide an
480 // |error_callback| should use IsExpectedSqliteError() to check for unexpected
481 // errors; if one is detected, DLOG(FATAL) is generally appropriate (see
482 // OnSqliteError implementation).
483 static bool IsExpectedSqliteError(int error);
[email protected]74cdede2013-09-25 05:39:57484
shessc8cd2a162015-10-22 20:30:46485 // Collect various diagnostic information and post a crash dump to aid
486 // debugging. Dump rate per database is limited to prevent overwhelming the
487 // crash server.
488 void ReportDiagnosticInfo(int extended_error, Statement* stmt);
489
[email protected]e5ffd0e42009-09-11 21:30:56490 private:
[email protected]8d409412013-07-19 18:25:30491 // For recovery module.
492 friend class Recovery;
493
shess976814402016-06-21 06:56:25494 // Allow test-support code to set/reset error expecter.
495 friend class test::ScopedErrorExpecter;
[email protected]4350e322013-06-18 22:18:10496
[email protected]eff1fa522011-12-12 23:50:59497 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56498 // (they should go through Statement).
499 friend class Statement;
500
shess58b8df82015-06-03 00:19:32501 friend class test::ScopedCommitHook;
502 friend class test::ScopedScalarFunction;
503 friend class test::ScopedMockTimeSource;
504
shessc8cd2a162015-10-22 20:30:46505 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, CollectDiagnosticInfo);
shess9bf2c672015-12-18 01:18:08506 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSize);
ssid3be5b1ec2016-01-13 14:21:57507 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, OnMemoryDump);
shessc8cd2a162015-10-22 20:30:46508 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, RegisterIntentToUpload);
509
[email protected]765b44502009-10-02 05:01:42510 // Internal initialize function used by both Init and InitInMemory. The file
511 // name is always 8 bits since we want to use the 8-bit version of
512 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13513 //
514 // |retry_flag| controls retrying the open if the error callback
515 // addressed errors using RazeAndClose().
516 enum Retry {
517 NO_RETRY = 0,
518 RETRY_ON_POISON
519 };
520 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42521
[email protected]41a97c812013-02-07 02:35:38522 // Internal close function used by Close() and RazeAndClose().
523 // |forced| indicates that orderly-shutdown checks should not apply.
524 void CloseInternal(bool forced);
525
[email protected]35f7e5392012-07-27 19:54:50526 // Check whether the current thread is allowed to make IO calls, but only
527 // if database wasn't open in memory. Function is inlined to be a no-op in
528 // official build.
shessc8cd2a162015-10-22 20:30:46529 void AssertIOAllowed() const {
[email protected]35f7e5392012-07-27 19:54:50530 if (!in_memory_)
531 base::ThreadRestrictions::AssertIOAllowed();
532 }
533
[email protected]e2cadec82011-12-13 02:00:53534 // Internal helper for DoesTableExist and DoesIndexExist.
535 bool DoesTableOrIndexExist(const char* name, const char* type) const;
536
shess976814402016-06-21 06:56:25537 // Accessors for global error-expecter, for injecting behavior during tests.
538 // See test/scoped_error_expecter.h.
539 typedef base::Callback<bool(int)> ErrorExpecterCallback;
540 static ErrorExpecterCallback* current_expecter_cb_;
541 static void SetErrorExpecter(ErrorExpecterCallback* expecter);
542 static void ResetErrorExpecter();
[email protected]4350e322013-06-18 22:18:10543
[email protected]e5ffd0e42009-09-11 21:30:56544 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
545 // Refcounting allows us to give these statements out to sql::Statement
546 // objects while also optionally maintaining a cache of compiled statements
547 // by just keeping a refptr to these objects.
548 //
549 // A statement ref can be valid, in which case it can be used, or invalid to
550 // indicate that the statement hasn't been created yet, has an error, or has
551 // been destroyed.
552 //
553 // The Connection may revoke a StatementRef in some error cases, so callers
554 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23555 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56556 public:
[email protected]41a97c812013-02-07 02:35:38557 // |connection| is the sql::Connection instance associated with
558 // the statement, and is used for tracking outstanding statements
559 // and for error handling. Set to NULL for invalid or untracked
560 // refs. |stmt| is the actual statement, and should only be NULL
561 // to create an invalid ref. |was_valid| indicates whether the
562 // statement should be considered valid for diagnistic purposes.
563 // |was_valid| can be true for NULL |stmt| if the connection has
564 // been forcibly closed by an error handler.
565 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56566
567 // When true, the statement can be used.
568 bool is_valid() const { return !!stmt_; }
569
[email protected]41a97c812013-02-07 02:35:38570 // When true, the statement is either currently valid, or was
571 // previously valid but the connection was forcibly closed. Used
572 // for diagnostic checks.
573 bool was_valid() const { return was_valid_; }
574
[email protected]b4c363b2013-01-17 13:11:17575 // If we've not been linked to a connection, this will be NULL.
576 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
577 // which prevents Statement::OnError() from forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56578 Connection* connection() const { return connection_; }
579
580 // Returns the sqlite statement if any. If the statement is not active,
581 // this will return NULL.
582 sqlite3_stmt* stmt() const { return stmt_; }
583
584 // Destroys the compiled statement and marks it NULL. The statement will
[email protected]41a97c812013-02-07 02:35:38585 // no longer be active. |forced| is used to indicate if orderly-shutdown
586 // checks should apply (see Connection::RazeAndClose()).
587 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56588
[email protected]35f7e5392012-07-27 19:54:50589 // Check whether the current thread is allowed to make IO calls, but only
590 // if database wasn't open in memory.
591 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
592
[email protected]e5ffd0e42009-09-11 21:30:56593 private:
[email protected]877d55d2009-11-05 21:53:08594 friend class base::RefCounted<StatementRef>;
595
596 ~StatementRef();
597
[email protected]e5ffd0e42009-09-11 21:30:56598 Connection* connection_;
599 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38600 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56601
602 DISALLOW_COPY_AND_ASSIGN(StatementRef);
603 };
604 friend class StatementRef;
605
606 // Executes a rollback statement, ignoring all transaction state. Used
607 // internally in the transaction management code.
608 void DoRollback();
609
610 // Called by a StatementRef when it's being created or destroyed. See
611 // open_statements_ below.
612 void StatementRefCreated(StatementRef* ref);
613 void StatementRefDeleted(StatementRef* ref);
614
[email protected]2f496b42013-09-26 18:36:58615 // Called when a sqlite function returns an error, which is passed
616 // as |err|. The return value is the error code to be reflected
617 // back to client code. |stmt| is non-NULL if the error relates to
618 // an sql::Statement instance. |sql| is non-NULL if the error
619 // relates to non-statement sql code (Execute, for instance). Both
620 // can be NULL, but both should never be set.
621 // NOTE(shess): Originally, the return value was intended to allow
622 // error handlers to transparently convert errors into success.
623 // Unfortunately, transactions are not generally restartable, so
624 // this did not work out.
shess9e77283d2016-06-13 23:53:20625 int OnSqliteError(int err, Statement* stmt, const char* sql) const;
[email protected]faa604e2009-09-25 22:38:59626
[email protected]5b96f3772010-09-28 16:30:57627 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20628 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
629 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57630
shess9e77283d2016-06-13 23:53:20631 // Implementation helper for GetUniqueStatement() and GetUntrackedStatement().
632 // |tracking_db| is the db the resulting ref should register with for
633 // outstanding statement tracking, which should be |this| to track or NULL to
634 // not track.
635 scoped_refptr<StatementRef> GetStatementImpl(
636 sql::Connection* tracking_db, const char* sql) const;
637
638 // Helper for implementing const member functions. Like GetUniqueStatement(),
639 // except the StatementRef is not entered into |open_statements_|, so an
640 // outstanding StatementRef from this function can block closing the database.
641 // The StatementRef will not call OnSqliteError(), because that can call
642 // |error_callback_| which can close the database.
[email protected]2eec0a22012-07-24 01:59:58643 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
644
[email protected]579446c2013-12-16 18:36:52645 bool IntegrityCheckHelper(
646 const char* pragma_sql,
647 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
648
shess58b8df82015-06-03 00:19:32649 // Record time spent executing explicit COMMIT statements.
650 void RecordCommitTime(const base::TimeDelta& delta);
651
652 // Record time in DML (Data Manipulation Language) statements such as INSERT
653 // or UPDATE outside of an explicit transaction. Due to implementation
654 // limitations time spent on DDL (Data Definition Language) statements such as
655 // ALTER and CREATE is not included.
656 void RecordAutoCommitTime(const base::TimeDelta& delta);
657
658 // Record all time spent on updating the database. This includes CommitTime()
659 // and AutoCommitTime(), plus any time spent spilling to the journal if
660 // transactions do not fit in cache.
661 void RecordUpdateTime(const base::TimeDelta& delta);
662
663 // Record all time spent running statements, including time spent doing
664 // updates and time spent on read-only queries.
665 void RecordQueryTime(const base::TimeDelta& delta);
666
667 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
668 // true, autocommit time if the database is not in a transaction, or update
669 // time if the database is in a transaction. Also records change count to
670 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
671 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
672
673 // Helper to return the current time from the time source.
674 base::TimeTicks Now() {
675 return clock_->Now();
676 }
677
shess7dbd4dee2015-10-06 17:39:16678 // Release page-cache memory if memory-mapped I/O is enabled and the database
679 // was changed. Passing true for |implicit_change_performed| allows
680 // overriding the change detection for cases like DDL (CREATE, DROP, etc),
681 // which do not participate in the total-rows-changed tracking.
682 void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
683
shessc8cd2a162015-10-22 20:30:46684 // Returns the results of sqlite3_db_filename(), which should match the path
685 // passed to Open().
686 base::FilePath DbPath() const;
687
688 // Helper to prevent uploading too many diagnostic dumps for a given database,
689 // since every dump will likely show the same problem. Returns |true| if this
690 // function was not previously called for this database, and the persistent
691 // storage which tracks state was updated.
692 //
693 // |false| is returned if the function was previously called for this
694 // database, even across restarts. |false| is also returned if the persistent
695 // storage cannot be updated, possibly indicating problems requiring user or
696 // admin intervention, such as filesystem corruption or disk full. |false| is
697 // also returned if the persistent storage contains invalid data or is not
698 // readable.
699 //
700 // TODO(shess): It would make sense to reset the persistent state if the
701 // database is razed or recovered, or if the diagnostic code adds new
702 // capabilities.
703 bool RegisterIntentToUpload() const;
704
705 // Helper to collect diagnostic info for a corrupt database.
706 std::string CollectCorruptionInfo();
707
708 // Helper to collect diagnostic info for errors.
709 std::string CollectErrorInfo(int error, Statement* stmt) const;
710
shessd90aeea82015-11-13 02:24:31711 // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors
712 // can make it unsafe to map a file, so the file is read using regular I/O,
713 // with any errors causing 0 (don't map anything) to be returned. If the
714 // entire file is read without error, a large value is returned which will
715 // allow the entire file to be mapped in most cases.
716 //
717 // Results are recorded in the database's meta table for future reference, so
718 // the file should only be read through once.
719 size_t GetAppropriateMmapSize();
720
[email protected]e5ffd0e42009-09-11 21:30:56721 // The actual sqlite database. Will be NULL before Init has been called or if
722 // Init resulted in an error.
723 sqlite3* db_;
724
725 // Parameters we'll configure in sqlite before doing anything else. Zero means
726 // use the default value.
727 int page_size_;
728 int cache_size_;
729 bool exclusive_locking_;
[email protected]81a2a602013-07-17 19:10:36730 bool restrict_to_user_;
[email protected]e5ffd0e42009-09-11 21:30:56731
732 // All cached statements. Keeping a reference to these statements means that
733 // they'll remain active.
734 typedef std::map<StatementID, scoped_refptr<StatementRef> >
735 CachedStatementMap;
736 CachedStatementMap statement_cache_;
737
738 // A list of all StatementRefs we've given out. Each ref must register with
739 // us when it's created or destroyed. This allows us to potentially close
740 // any open statements when we encounter an error.
741 typedef std::set<StatementRef*> StatementRefSet;
742 StatementRefSet open_statements_;
743
744 // Number of currently-nested transactions.
745 int transaction_nesting_;
746
747 // True if any of the currently nested transactions have been rolled back.
748 // When we get to the outermost transaction, this will determine if we do
749 // a rollback instead of a commit.
750 bool needs_rollback_;
751
[email protected]35f7e5392012-07-27 19:54:50752 // True if database is open with OpenInMemory(), False if database is open
753 // with Open().
754 bool in_memory_;
755
[email protected]41a97c812013-02-07 02:35:38756 // |true| if the connection was closed using RazeAndClose(). Used
757 // to enable diagnostics to distinguish calls to never-opened
758 // databases (incorrect use of the API) from calls to once-valid
759 // databases.
760 bool poisoned_;
761
shess7dbd4dee2015-10-06 17:39:16762 // |true| if SQLite memory-mapped I/O is not desired for this connection.
763 bool mmap_disabled_;
764
765 // |true| if SQLite memory-mapped I/O was enabled for this connection.
766 // Used by ReleaseCacheMemoryIfNeeded().
767 bool mmap_enabled_;
768
769 // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
770 // since memory was last released.
771 int total_changes_at_last_release_;
772
[email protected]c3881b372013-05-17 08:39:46773 ErrorCallback error_callback_;
774
[email protected]210ce0af2013-05-15 09:10:39775 // Tag for auxiliary histograms.
776 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14777
shess58b8df82015-06-03 00:19:32778 // Linear histogram for RecordEvent().
779 base::HistogramBase* stats_histogram_;
780
781 // Histogram for tracking time taken in commit.
782 base::HistogramBase* commit_time_histogram_;
783
784 // Histogram for tracking time taken in autocommit updates.
785 base::HistogramBase* autocommit_time_histogram_;
786
787 // Histogram for tracking time taken in updates (including commit and
788 // autocommit).
789 base::HistogramBase* update_time_histogram_;
790
791 // Histogram for tracking time taken in all queries.
792 base::HistogramBase* query_time_histogram_;
793
794 // Source for timing information, provided to allow tests to inject time
795 // changes.
mostynbd82cd9952016-04-11 20:05:34796 std::unique_ptr<TimeSource> clock_;
shess58b8df82015-06-03 00:19:32797
ssid3be5b1ec2016-01-13 14:21:57798 // Stores the dump provider object when db is open.
mostynbd82cd9952016-04-11 20:05:34799 std::unique_ptr<ConnectionMemoryDumpProvider> memory_dump_provider_;
ssid3be5b1ec2016-01-13 14:21:57800
[email protected]e5ffd0e42009-09-11 21:30:56801 DISALLOW_COPY_AND_ASSIGN(Connection);
802};
803
804} // namespace sql
805
[email protected]f0a54b22011-07-19 18:40:21806#endif // SQL_CONNECTION_H_