blob: 19592d9f0e44ed68764b9d25a88d9a65424ba9b7 [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
tfarina720d4f32015-05-11 22:31:268#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:569#include <map>
10#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3311#include <string>
[email protected]80abf152013-05-22 12:42:4212#include <vector>
[email protected]e5ffd0e42009-09-11 21:30:5613
[email protected]c3881b372013-05-17 08:39:4614#include "base/callback.h"
[email protected]9fe37552011-12-23 17:07:2015#include "base/compiler_specific.h"
tfarina720d4f32015-05-11 22:31:2616#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1517#include "base/memory/ref_counted.h"
[email protected]49dc4f22012-10-17 17:41:1618#include "base/memory/scoped_ptr.h"
[email protected]35f7e5392012-07-27 19:54:5019#include "base/threading/thread_restrictions.h"
[email protected]2b59d682013-06-28 15:22:0320#include "base/time/time.h"
[email protected]d4526962011-11-10 21:40:2821#include "sql/sql_export.h"
[email protected]e5ffd0e42009-09-11 21:30:5622
[email protected]e5ffd0e42009-09-11 21:30:5623struct sqlite3;
24struct sqlite3_stmt;
25
[email protected]a3ef4832013-02-02 05:12:3326namespace base {
27class FilePath;
shess58b8df82015-06-03 00:19:3228class HistogramBase;
[email protected]a3ef4832013-02-02 05:12:3329}
30
[email protected]e5ffd0e42009-09-11 21:30:5631namespace sql {
32
[email protected]8d409412013-07-19 18:25:3033class Recovery;
[email protected]e5ffd0e42009-09-11 21:30:5634class Statement;
35
shess58b8df82015-06-03 00:19:3236// To allow some test classes to be friended.
37namespace test {
38class ScopedCommitHook;
39class ScopedScalarFunction;
40class ScopedMockTimeSource;
41}
42
[email protected]e5ffd0e42009-09-11 21:30:5643// Uniquely identifies a statement. There are two modes of operation:
44//
45// - In the most common mode, you will use the source file and line number to
46// identify your statement. This is a convienient way to get uniqueness for
47// a statement that is only used in one place. Use the SQL_FROM_HERE macro
48// to generate a StatementID.
49//
50// - In the "custom" mode you may use the statement from different places or
51// need to manage it yourself for whatever reason. In this case, you should
52// make up your own unique name and pass it to the StatementID. This name
53// must be a static string, since this object only deals with pointers and
54// assumes the underlying string doesn't change or get deleted.
55//
56// This object is copyable and assignable using the compiler-generated
57// operator= and copy constructor.
58class StatementID {
59 public:
60 // Creates a uniquely named statement with the given file ane line number.
61 // Normally you will use SQL_FROM_HERE instead of calling yourself.
62 StatementID(const char* file, int line)
63 : number_(line),
64 str_(file) {
65 }
66
67 // Creates a uniquely named statement with the given user-defined name.
68 explicit StatementID(const char* unique_name)
69 : number_(-1),
70 str_(unique_name) {
71 }
72
73 // This constructor is unimplemented and will generate a linker error if
74 // called. It is intended to try to catch people dynamically generating
75 // a statement name that will be deallocated and will cause a crash later.
76 // All strings must be static and unchanging!
77 explicit StatementID(const std::string& dont_ever_do_this);
78
79 // We need this to insert into our map.
80 bool operator<(const StatementID& other) const;
81
82 private:
83 int number_;
84 const char* str_;
85};
86
87#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
88
[email protected]faa604e2009-09-25 22:38:5989class Connection;
90
shess58b8df82015-06-03 00:19:3291// Abstract the source of timing information for metrics (RecordCommitTime, etc)
92// to allow testing control.
93class SQL_EXPORT TimeSource {
94 public:
95 TimeSource() {}
96 virtual ~TimeSource() {}
97
98 // Return the current time (by default base::TimeTicks::Now()).
99 virtual base::TimeTicks Now();
100
101 private:
102 DISALLOW_COPY_AND_ASSIGN(TimeSource);
103};
104
[email protected]d4526962011-11-10 21:40:28105class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56106 private:
107 class StatementRef; // Forward declaration, see real one below.
108
109 public:
[email protected]765b44502009-10-02 05:01:42110 // The database is opened by calling Open[InMemory](). Any uncommitted
111 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56112 Connection();
113 ~Connection();
114
115 // Pre-init configuration ----------------------------------------------------
116
[email protected]765b44502009-10-02 05:01:42117 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56118 // must be called before Init(), and will only have an effect on new
119 // databases.
120 //
121 // From sqlite.org: "The page size must be a power of two greater than or
122 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
123 // value for SQLITE_MAX_PAGE_SIZE is 32768."
124 void set_page_size(int page_size) { page_size_ = page_size; }
125
126 // Sets the number of pages that will be cached in memory by sqlite. The
127 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42128 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56129 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
130
131 // Call to put the database in exclusive locking mode. There is no "back to
132 // normal" flag because of some additional requirements sqlite puts on this
[email protected]4ab952f2014-04-01 20:18:16133 // transaction (requires another access to the DB) and because we don't
[email protected]e5ffd0e42009-09-11 21:30:56134 // actually need it.
135 //
136 // Exclusive mode means that the database is not unlocked at the end of each
137 // transaction, which means there may be less time spent initializing the
138 // next transaction because it doesn't have to re-aquire locks.
139 //
[email protected]765b44502009-10-02 05:01:42140 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56141 void set_exclusive_locking() { exclusive_locking_ = true; }
142
[email protected]81a2a602013-07-17 19:10:36143 // Call to cause Open() to restrict access permissions of the
144 // database file to only the owner.
145 // TODO(shess): Currently only supported on OS_POSIX, is a noop on
146 // other platforms.
147 void set_restrict_to_user() { restrict_to_user_ = true; }
148
[email protected]c3881b372013-05-17 08:39:46149 // Set an error-handling callback. On errors, the error number (and
150 // statement, if available) will be passed to the callback.
151 //
152 // If no callback is set, the default action is to crash in debug
153 // mode or return failure in release mode.
[email protected]c3881b372013-05-17 08:39:46154 typedef base::Callback<void(int, Statement*)> ErrorCallback;
155 void set_error_callback(const ErrorCallback& callback) {
156 error_callback_ = callback;
157 }
[email protected]98cf3002013-07-12 01:38:56158 bool has_error_callback() const {
159 return !error_callback_.is_null();
160 }
[email protected]c3881b372013-05-17 08:39:46161 void reset_error_callback() {
162 error_callback_.Reset();
163 }
164
shess58b8df82015-06-03 00:19:32165 // Set this to enable additional per-connection histogramming. Must be called
166 // before Open().
167 void set_histogram_tag(const std::string& tag);
[email protected]c088e3a32013-01-03 23:59:14168
[email protected]210ce0af2013-05-15 09:10:39169 // Record a sparse UMA histogram sample under
170 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
171 // histogram is recorded.
172 void AddTaggedHistogram(const std::string& name, size_t sample) const;
173
shess58b8df82015-06-03 00:19:32174 // Track various API calls and results. Values corrospond to UMA
175 // histograms, do not modify, or add or delete other than directly
176 // before EVENT_MAX_VALUE.
177 enum Events {
178 // Number of statements run, either with sql::Statement or Execute*().
179 EVENT_STATEMENT_RUN = 0,
180
181 // Number of rows returned by statements run.
182 EVENT_STATEMENT_ROWS,
183
184 // Number of statements successfully run (all steps returned SQLITE_DONE or
185 // SQLITE_ROW).
186 EVENT_STATEMENT_SUCCESS,
187
188 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
189 EVENT_EXECUTE,
190
191 // Number of rows changed by autocommit statements.
192 EVENT_CHANGES_AUTOCOMMIT,
193
194 // Number of rows changed by statements in transactions.
195 EVENT_CHANGES,
196
197 // Count actual SQLite transaction statements (not including nesting).
198 EVENT_BEGIN,
199 EVENT_COMMIT,
200 EVENT_ROLLBACK,
201
202 // Leave this at the end.
203 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
204 EVENT_MAX_VALUE
205 };
206 void RecordEvent(Events event, size_t count);
207 void RecordOneEvent(Events event) {
208 RecordEvent(event, 1);
209 }
210
[email protected]579446c2013-12-16 18:36:52211 // Run "PRAGMA integrity_check" and post each line of
212 // results into |messages|. Returns the success of running the
213 // statement - per the SQLite documentation, if no errors are found the
214 // call should succeed, and a single value "ok" should be in messages.
215 bool FullIntegrityCheck(std::vector<std::string>* messages);
216
217 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
218 // interprets the results returning true if the the statement executes
219 // without error and results in a single "ok" value.
220 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42221
[email protected]e5ffd0e42009-09-11 21:30:56222 // Initialization ------------------------------------------------------------
223
224 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55225 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33226 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42227
228 // Initializes the SQL connection for a temporary in-memory database. There
229 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55230 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20231 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42232
[email protected]8d409412013-07-19 18:25:30233 // Create a temporary on-disk database. The database will be
234 // deleted after close. This kind of database is similar to
235 // OpenInMemory() for small databases, but can page to disk if the
236 // database becomes large.
237 bool OpenTemporary() WARN_UNUSED_RESULT;
238
[email protected]41a97c812013-02-07 02:35:38239 // Returns true if the database has been successfully opened.
[email protected]765b44502009-10-02 05:01:42240 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56241
242 // Closes the database. This is automatically performed on destruction for
243 // you, but this allows you to close the database early. You must not call
244 // any other functions after closing it. It is permissable to call Close on
245 // an uninitialized or already-closed database.
246 void Close();
247
[email protected]8ada10f2013-12-21 00:42:34248 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
249 // filesystem cache. This can be more efficient than faulting pages
250 // individually. Since this involves blocking I/O, it should only be used if
251 // the caller will immediately read a substantial amount of data from the
252 // database.
[email protected]e5ffd0e42009-09-11 21:30:56253 //
[email protected]8ada10f2013-12-21 00:42:34254 // TODO(shess): Design a set of histograms or an experiment to inform this
255 // decision. Preloading should almost always improve later performance
256 // numbers for this database simply because it pulls operations forward, but
257 // if the data isn't actually used soon then preloading just slows down
258 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56259 void Preload();
260
[email protected]be7995f12013-07-18 18:49:14261 // Try to trim the cache memory used by the database. If |aggressively| is
262 // true, this function will try to free all of the cache memory it can. If
263 // |aggressively| is false, this function will try to cut cache memory
264 // usage by half.
265 void TrimMemory(bool aggressively);
266
[email protected]8e0c01282012-04-06 19:36:49267 // Raze the database to the ground. This approximates creating a
268 // fresh database from scratch, within the constraints of SQLite's
269 // locking protocol (locks and open handles can make doing this with
270 // filesystem operations problematic). Returns true if the database
271 // was razed.
272 //
273 // false is returned if the database is locked by some other
274 // process. RazeWithTimeout() may be used if appropriate.
275 //
276 // NOTE(shess): Raze() will DCHECK in the following situations:
277 // - database is not open.
278 // - the connection has a transaction open.
279 // - a SQLite issue occurs which is structural in nature (like the
280 // statements used are broken).
281 // Since Raze() is expected to be called in unexpected situations,
282 // these all return false, since it is unlikely that the caller
283 // could fix them.
[email protected]6d42f152012-11-10 00:38:24284 //
285 // The database's page size is taken from |page_size_|. The
286 // existing database's |auto_vacuum| setting is lost (the
287 // possibility of corruption makes it unreliable to pull it from the
288 // existing database). To re-enable on the empty database requires
289 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
290 //
291 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
292 // so Raze() sets auto_vacuum to 1.
293 //
294 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
295 // TODO(shess): Bake auto_vacuum into Connection's API so it can
296 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49297 bool Raze();
298 bool RazeWithTimout(base::TimeDelta timeout);
299
[email protected]41a97c812013-02-07 02:35:38300 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30301 // BeginTransaction()), closes the SQLite database, and poisons the
302 // object so that all future operations against the Connection (or
303 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38304 //
[email protected]8d409412013-07-19 18:25:30305 // This is intended as an alternative to Close() in error callbacks.
306 // Close() should still be called at some point.
307 void Poison();
308
309 // Raze() the database and Poison() the handle. Returns the return
310 // value from Raze().
311 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38312 bool RazeAndClose();
313
[email protected]8d2e39e2013-06-24 05:55:08314 // Delete the underlying database files associated with |path|.
315 // This should be used on a database which has no existing
316 // connections. If any other connections are open to the same
317 // database, this could cause odd results or corruption (for
318 // instance if a hot journal is deleted but the associated database
319 // is not).
320 //
321 // Returns true if the database file and associated journals no
322 // longer exist, false otherwise. If the database has never
323 // existed, this will return true.
324 static bool Delete(const base::FilePath& path);
325
[email protected]e5ffd0e42009-09-11 21:30:56326 // Transactions --------------------------------------------------------------
327
328 // Transaction management. We maintain a virtual transaction stack to emulate
329 // nested transactions since sqlite can't do nested transactions. The
330 // limitation is you can't roll back a sub transaction: if any transaction
331 // fails, all transactions open will also be rolled back. Any nested
332 // transactions after one has rolled back will return fail for Begin(). If
333 // Begin() fails, you must not call Commit or Rollback().
334 //
335 // Normally you should use sql::Transaction to manage a transaction, which
336 // will scope it to a C++ context.
337 bool BeginTransaction();
338 void RollbackTransaction();
339 bool CommitTransaction();
340
[email protected]8d409412013-07-19 18:25:30341 // Rollback all outstanding transactions. Use with care, there may
342 // be scoped transactions on the stack.
343 void RollbackAllTransactions();
344
[email protected]e5ffd0e42009-09-11 21:30:56345 // Returns the current transaction nesting, which will be 0 if there are
346 // no open transactions.
347 int transaction_nesting() const { return transaction_nesting_; }
348
[email protected]8d409412013-07-19 18:25:30349 // Attached databases---------------------------------------------------------
350
351 // SQLite supports attaching multiple database files to a single
352 // handle. Attach the database in |other_db_path| to the current
353 // handle under |attachment_point|. |attachment_point| should only
354 // contain characters from [a-zA-Z0-9_].
355 //
356 // Note that calling attach or detach with an open transaction is an
357 // error.
358 bool AttachDatabase(const base::FilePath& other_db_path,
359 const char* attachment_point);
360 bool DetachDatabase(const char* attachment_point);
361
[email protected]e5ffd0e42009-09-11 21:30:56362 // Statements ----------------------------------------------------------------
363
364 // Executes the given SQL string, returning true on success. This is
365 // normally used for simple, 1-off statements that don't take any bound
366 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20367 //
[email protected]eff1fa522011-12-12 23:50:59368 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20369 //
370 // Do not use ignore_result() to ignore all errors. Use
371 // ExecuteAndReturnErrorCode() and ignore only specific errors.
372 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56373
[email protected]eff1fa522011-12-12 23:50:59374 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20375 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59376
[email protected]e5ffd0e42009-09-11 21:30:56377 // Returns true if we have a statement with the given identifier already
378 // cached. This is normally not necessary to call, but can be useful if the
379 // caller has to dynamically build up SQL to avoid doing so if it's already
380 // cached.
381 bool HasCachedStatement(const StatementID& id) const;
382
383 // Returns a statement for the given SQL using the statement cache. It can
384 // take a nontrivial amount of work to parse and compile a statement, so
385 // keeping commonly-used ones around for future use is important for
386 // performance.
387 //
[email protected]eff1fa522011-12-12 23:50:59388 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
389 // the code will crash in debug). The caller must deal with this eventuality,
390 // either by checking validity of the |sql| before calling, by correctly
391 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56392 //
393 // The StatementID and the SQL must always correspond to one-another. The
394 // ID is the lookup into the cache, so crazy things will happen if you use
395 // different SQL with the same ID.
396 //
397 // You will normally use the SQL_FROM_HERE macro to generate a statement
398 // ID associated with the current line of code. This gives uniqueness without
399 // you having to manage unique names. See StatementID above for more.
400 //
401 // Example:
[email protected]3273dce2010-01-27 16:08:08402 // sql::Statement stmt(connection_.GetCachedStatement(
403 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56404 // if (!stmt)
405 // return false; // Error creating statement.
406 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
407 const char* sql);
408
[email protected]eff1fa522011-12-12 23:50:59409 // Used to check a |sql| statement for syntactic validity. If the statement is
410 // valid SQL, returns true.
411 bool IsSQLValid(const char* sql);
412
[email protected]e5ffd0e42009-09-11 21:30:56413 // Returns a non-cached statement for the given SQL. Use this for SQL that
414 // is only executed once or only rarely (there is overhead associated with
415 // keeping a statement cached).
416 //
417 // See GetCachedStatement above for examples and error information.
418 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
419
420 // Info querying -------------------------------------------------------------
421
shess92a2ab12015-04-09 01:59:47422 // Returns true if the given table (or index) exists. Instead of
423 // test-then-create, callers should almost always prefer "CREATE TABLE IF NOT
424 // EXISTS" or "CREATE INDEX IF NOT EXISTS".
[email protected]765b44502009-10-02 05:01:42425 bool DoesTableExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53426 bool DoesIndexExist(const char* index_name) const;
427
[email protected]e5ffd0e42009-09-11 21:30:56428 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17429 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56430
431 // Returns sqlite's internal ID for the last inserted row. Valid only
432 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26433 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56434
[email protected]1ed78a32009-09-15 20:24:17435 // Returns sqlite's count of the number of rows modified by the last
436 // statement executed. Will be 0 if no statement has executed or the database
437 // is closed.
438 int GetLastChangeCount() const;
439
[email protected]e5ffd0e42009-09-11 21:30:56440 // Errors --------------------------------------------------------------------
441
442 // Returns the error code associated with the last sqlite operation.
443 int GetErrorCode() const;
444
[email protected]767718e52010-09-21 23:18:49445 // Returns the errno associated with GetErrorCode(). See
446 // SQLITE_LAST_ERRNO in SQLite documentation.
447 int GetLastErrno() const;
448
[email protected]e5ffd0e42009-09-11 21:30:56449 // Returns a pointer to a statically allocated string associated with the
450 // last sqlite operation.
451 const char* GetErrorMessage() const;
452
[email protected]92cd00a2013-08-16 11:09:58453 // Return a reproducible representation of the schema equivalent to
454 // running the following statement at a sqlite3 command-line:
455 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
456 std::string GetSchema() const;
457
[email protected]74cdede2013-09-25 05:39:57458 // Clients which provide an error_callback don't see the
459 // error-handling at the end of OnSqliteError(). Expose to allow
460 // those clients to work appropriately with ScopedErrorIgnorer in
461 // tests.
462 static bool ShouldIgnoreSqliteError(int error);
463
[email protected]e5ffd0e42009-09-11 21:30:56464 private:
[email protected]8d409412013-07-19 18:25:30465 // For recovery module.
466 friend class Recovery;
467
[email protected]4350e322013-06-18 22:18:10468 // Allow test-support code to set/reset error ignorer.
469 friend class ScopedErrorIgnorer;
470
[email protected]eff1fa522011-12-12 23:50:59471 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56472 // (they should go through Statement).
473 friend class Statement;
474
shess58b8df82015-06-03 00:19:32475 friend class test::ScopedCommitHook;
476 friend class test::ScopedScalarFunction;
477 friend class test::ScopedMockTimeSource;
478
[email protected]765b44502009-10-02 05:01:42479 // Internal initialize function used by both Init and InitInMemory. The file
480 // name is always 8 bits since we want to use the 8-bit version of
481 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13482 //
483 // |retry_flag| controls retrying the open if the error callback
484 // addressed errors using RazeAndClose().
485 enum Retry {
486 NO_RETRY = 0,
487 RETRY_ON_POISON
488 };
489 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42490
[email protected]41a97c812013-02-07 02:35:38491 // Internal close function used by Close() and RazeAndClose().
492 // |forced| indicates that orderly-shutdown checks should not apply.
493 void CloseInternal(bool forced);
494
[email protected]35f7e5392012-07-27 19:54:50495 // Check whether the current thread is allowed to make IO calls, but only
496 // if database wasn't open in memory. Function is inlined to be a no-op in
497 // official build.
498 void AssertIOAllowed() {
499 if (!in_memory_)
500 base::ThreadRestrictions::AssertIOAllowed();
501 }
502
[email protected]e2cadec82011-12-13 02:00:53503 // Internal helper for DoesTableExist and DoesIndexExist.
504 bool DoesTableOrIndexExist(const char* name, const char* type) const;
505
[email protected]4350e322013-06-18 22:18:10506 // Accessors for global error-ignorer, for injecting behavior during tests.
507 // See test/scoped_error_ignorer.h.
508 typedef base::Callback<bool(int)> ErrorIgnorerCallback;
509 static ErrorIgnorerCallback* current_ignorer_cb_;
[email protected]4350e322013-06-18 22:18:10510 static void SetErrorIgnorer(ErrorIgnorerCallback* ignorer);
511 static void ResetErrorIgnorer();
512
[email protected]e5ffd0e42009-09-11 21:30:56513 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
514 // Refcounting allows us to give these statements out to sql::Statement
515 // objects while also optionally maintaining a cache of compiled statements
516 // by just keeping a refptr to these objects.
517 //
518 // A statement ref can be valid, in which case it can be used, or invalid to
519 // indicate that the statement hasn't been created yet, has an error, or has
520 // been destroyed.
521 //
522 // The Connection may revoke a StatementRef in some error cases, so callers
523 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23524 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56525 public:
[email protected]41a97c812013-02-07 02:35:38526 // |connection| is the sql::Connection instance associated with
527 // the statement, and is used for tracking outstanding statements
528 // and for error handling. Set to NULL for invalid or untracked
529 // refs. |stmt| is the actual statement, and should only be NULL
530 // to create an invalid ref. |was_valid| indicates whether the
531 // statement should be considered valid for diagnistic purposes.
532 // |was_valid| can be true for NULL |stmt| if the connection has
533 // been forcibly closed by an error handler.
534 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56535
536 // When true, the statement can be used.
537 bool is_valid() const { return !!stmt_; }
538
[email protected]41a97c812013-02-07 02:35:38539 // When true, the statement is either currently valid, or was
540 // previously valid but the connection was forcibly closed. Used
541 // for diagnostic checks.
542 bool was_valid() const { return was_valid_; }
543
[email protected]b4c363b2013-01-17 13:11:17544 // If we've not been linked to a connection, this will be NULL.
545 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
546 // which prevents Statement::OnError() from forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56547 Connection* connection() const { return connection_; }
548
549 // Returns the sqlite statement if any. If the statement is not active,
550 // this will return NULL.
551 sqlite3_stmt* stmt() const { return stmt_; }
552
553 // Destroys the compiled statement and marks it NULL. The statement will
[email protected]41a97c812013-02-07 02:35:38554 // no longer be active. |forced| is used to indicate if orderly-shutdown
555 // checks should apply (see Connection::RazeAndClose()).
556 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56557
[email protected]35f7e5392012-07-27 19:54:50558 // Check whether the current thread is allowed to make IO calls, but only
559 // if database wasn't open in memory.
560 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
561
[email protected]e5ffd0e42009-09-11 21:30:56562 private:
[email protected]877d55d2009-11-05 21:53:08563 friend class base::RefCounted<StatementRef>;
564
565 ~StatementRef();
566
[email protected]e5ffd0e42009-09-11 21:30:56567 Connection* connection_;
568 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38569 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56570
571 DISALLOW_COPY_AND_ASSIGN(StatementRef);
572 };
573 friend class StatementRef;
574
575 // Executes a rollback statement, ignoring all transaction state. Used
576 // internally in the transaction management code.
577 void DoRollback();
578
579 // Called by a StatementRef when it's being created or destroyed. See
580 // open_statements_ below.
581 void StatementRefCreated(StatementRef* ref);
582 void StatementRefDeleted(StatementRef* ref);
583
[email protected]2f496b42013-09-26 18:36:58584 // Called when a sqlite function returns an error, which is passed
585 // as |err|. The return value is the error code to be reflected
586 // back to client code. |stmt| is non-NULL if the error relates to
587 // an sql::Statement instance. |sql| is non-NULL if the error
588 // relates to non-statement sql code (Execute, for instance). Both
589 // can be NULL, but both should never be set.
590 // NOTE(shess): Originally, the return value was intended to allow
591 // error handlers to transparently convert errors into success.
592 // Unfortunately, transactions are not generally restartable, so
593 // this did not work out.
594 int OnSqliteError(int err, Statement* stmt, const char* sql);
[email protected]faa604e2009-09-25 22:38:59595
[email protected]5b96f3772010-09-28 16:30:57596 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20597 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
598 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57599
[email protected]2eec0a22012-07-24 01:59:58600 // Internal helper for const functions. Like GetUniqueStatement(),
601 // except the statement is not entered into open_statements_,
602 // allowing this function to be const. Open statements can block
603 // closing the database, so only use in cases where the last ref is
604 // released before close could be called (which should always be the
605 // case for const functions).
606 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
607
[email protected]579446c2013-12-16 18:36:52608 bool IntegrityCheckHelper(
609 const char* pragma_sql,
610 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
611
shess58b8df82015-06-03 00:19:32612 // Record time spent executing explicit COMMIT statements.
613 void RecordCommitTime(const base::TimeDelta& delta);
614
615 // Record time in DML (Data Manipulation Language) statements such as INSERT
616 // or UPDATE outside of an explicit transaction. Due to implementation
617 // limitations time spent on DDL (Data Definition Language) statements such as
618 // ALTER and CREATE is not included.
619 void RecordAutoCommitTime(const base::TimeDelta& delta);
620
621 // Record all time spent on updating the database. This includes CommitTime()
622 // and AutoCommitTime(), plus any time spent spilling to the journal if
623 // transactions do not fit in cache.
624 void RecordUpdateTime(const base::TimeDelta& delta);
625
626 // Record all time spent running statements, including time spent doing
627 // updates and time spent on read-only queries.
628 void RecordQueryTime(const base::TimeDelta& delta);
629
630 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
631 // true, autocommit time if the database is not in a transaction, or update
632 // time if the database is in a transaction. Also records change count to
633 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
634 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
635
636 // Helper to return the current time from the time source.
637 base::TimeTicks Now() {
638 return clock_->Now();
639 }
640
[email protected]e5ffd0e42009-09-11 21:30:56641 // The actual sqlite database. Will be NULL before Init has been called or if
642 // Init resulted in an error.
643 sqlite3* db_;
644
645 // Parameters we'll configure in sqlite before doing anything else. Zero means
646 // use the default value.
647 int page_size_;
648 int cache_size_;
649 bool exclusive_locking_;
[email protected]81a2a602013-07-17 19:10:36650 bool restrict_to_user_;
[email protected]e5ffd0e42009-09-11 21:30:56651
652 // All cached statements. Keeping a reference to these statements means that
653 // they'll remain active.
654 typedef std::map<StatementID, scoped_refptr<StatementRef> >
655 CachedStatementMap;
656 CachedStatementMap statement_cache_;
657
658 // A list of all StatementRefs we've given out. Each ref must register with
659 // us when it's created or destroyed. This allows us to potentially close
660 // any open statements when we encounter an error.
661 typedef std::set<StatementRef*> StatementRefSet;
662 StatementRefSet open_statements_;
663
664 // Number of currently-nested transactions.
665 int transaction_nesting_;
666
667 // True if any of the currently nested transactions have been rolled back.
668 // When we get to the outermost transaction, this will determine if we do
669 // a rollback instead of a commit.
670 bool needs_rollback_;
671
[email protected]35f7e5392012-07-27 19:54:50672 // True if database is open with OpenInMemory(), False if database is open
673 // with Open().
674 bool in_memory_;
675
[email protected]41a97c812013-02-07 02:35:38676 // |true| if the connection was closed using RazeAndClose(). Used
677 // to enable diagnostics to distinguish calls to never-opened
678 // databases (incorrect use of the API) from calls to once-valid
679 // databases.
680 bool poisoned_;
681
[email protected]c3881b372013-05-17 08:39:46682 ErrorCallback error_callback_;
683
[email protected]210ce0af2013-05-15 09:10:39684 // Tag for auxiliary histograms.
685 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14686
shess58b8df82015-06-03 00:19:32687 // Linear histogram for RecordEvent().
688 base::HistogramBase* stats_histogram_;
689
690 // Histogram for tracking time taken in commit.
691 base::HistogramBase* commit_time_histogram_;
692
693 // Histogram for tracking time taken in autocommit updates.
694 base::HistogramBase* autocommit_time_histogram_;
695
696 // Histogram for tracking time taken in updates (including commit and
697 // autocommit).
698 base::HistogramBase* update_time_histogram_;
699
700 // Histogram for tracking time taken in all queries.
701 base::HistogramBase* query_time_histogram_;
702
703 // Source for timing information, provided to allow tests to inject time
704 // changes.
705 scoped_ptr<TimeSource> clock_;
706
[email protected]e5ffd0e42009-09-11 21:30:56707 DISALLOW_COPY_AND_ASSIGN(Connection);
708};
709
710} // namespace sql
711
[email protected]f0a54b22011-07-19 18:40:21712#endif // SQL_CONNECTION_H_