blob: 20ea3cd5101b199f20be8c143403bec9fd42f3dd [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;
dskibab4199f82016-11-21 20:16:1331namespace trace_event {
32class MemoryAllocatorDump;
33}
[email protected]a3ef4832013-02-02 05:12:3334}
35
[email protected]e5ffd0e42009-09-11 21:30:5636namespace sql {
37
ssid3be5b1ec2016-01-13 14:21:5738class ConnectionMemoryDumpProvider;
[email protected]8d409412013-07-19 18:25:3039class Recovery;
[email protected]e5ffd0e42009-09-11 21:30:5640class Statement;
41
shess58b8df82015-06-03 00:19:3242// To allow some test classes to be friended.
43namespace test {
44class ScopedCommitHook;
shess976814402016-06-21 06:56:2545class ScopedErrorExpecter;
shess58b8df82015-06-03 00:19:3246class ScopedScalarFunction;
47class ScopedMockTimeSource;
48}
49
[email protected]e5ffd0e42009-09-11 21:30:5650// Uniquely identifies a statement. There are two modes of operation:
51//
52// - In the most common mode, you will use the source file and line number to
53// identify your statement. This is a convienient way to get uniqueness for
54// a statement that is only used in one place. Use the SQL_FROM_HERE macro
55// to generate a StatementID.
56//
57// - In the "custom" mode you may use the statement from different places or
58// need to manage it yourself for whatever reason. In this case, you should
59// make up your own unique name and pass it to the StatementID. This name
60// must be a static string, since this object only deals with pointers and
61// assumes the underlying string doesn't change or get deleted.
62//
63// This object is copyable and assignable using the compiler-generated
64// operator= and copy constructor.
65class StatementID {
66 public:
67 // Creates a uniquely named statement with the given file ane line number.
68 // Normally you will use SQL_FROM_HERE instead of calling yourself.
69 StatementID(const char* file, int line)
70 : number_(line),
71 str_(file) {
72 }
73
74 // Creates a uniquely named statement with the given user-defined name.
75 explicit StatementID(const char* unique_name)
76 : number_(-1),
77 str_(unique_name) {
78 }
79
80 // This constructor is unimplemented and will generate a linker error if
81 // called. It is intended to try to catch people dynamically generating
82 // a statement name that will be deallocated and will cause a crash later.
83 // All strings must be static and unchanging!
84 explicit StatementID(const std::string& dont_ever_do_this);
85
86 // We need this to insert into our map.
87 bool operator<(const StatementID& other) const;
88
89 private:
90 int number_;
91 const char* str_;
92};
93
94#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
95
[email protected]faa604e2009-09-25 22:38:5996class Connection;
97
shess58b8df82015-06-03 00:19:3298// Abstract the source of timing information for metrics (RecordCommitTime, etc)
99// to allow testing control.
100class SQL_EXPORT TimeSource {
101 public:
102 TimeSource() {}
103 virtual ~TimeSource() {}
104
105 // Return the current time (by default base::TimeTicks::Now()).
106 virtual base::TimeTicks Now();
107
108 private:
109 DISALLOW_COPY_AND_ASSIGN(TimeSource);
110};
111
ssid3be5b1ec2016-01-13 14:21:57112class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56113 private:
114 class StatementRef; // Forward declaration, see real one below.
115
116 public:
[email protected]765b44502009-10-02 05:01:42117 // The database is opened by calling Open[InMemory](). Any uncommitted
118 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56119 Connection();
ssid3be5b1ec2016-01-13 14:21:57120 ~Connection();
[email protected]e5ffd0e42009-09-11 21:30:56121
122 // Pre-init configuration ----------------------------------------------------
123
[email protected]765b44502009-10-02 05:01:42124 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56125 // must be called before Init(), and will only have an effect on new
126 // databases.
127 //
128 // From sqlite.org: "The page size must be a power of two greater than or
129 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
130 // value for SQLITE_MAX_PAGE_SIZE is 32768."
131 void set_page_size(int page_size) { page_size_ = page_size; }
132
133 // Sets the number of pages that will be cached in memory by sqlite. The
134 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42135 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56136 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
137
138 // Call to put the database in exclusive locking mode. There is no "back to
139 // normal" flag because of some additional requirements sqlite puts on this
[email protected]4ab952f2014-04-01 20:18:16140 // transaction (requires another access to the DB) and because we don't
[email protected]e5ffd0e42009-09-11 21:30:56141 // actually need it.
142 //
143 // Exclusive mode means that the database is not unlocked at the end of each
144 // transaction, which means there may be less time spent initializing the
145 // next transaction because it doesn't have to re-aquire locks.
146 //
[email protected]765b44502009-10-02 05:01:42147 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56148 void set_exclusive_locking() { exclusive_locking_ = true; }
149
[email protected]81a2a602013-07-17 19:10:36150 // Call to cause Open() to restrict access permissions of the
151 // database file to only the owner.
152 // TODO(shess): Currently only supported on OS_POSIX, is a noop on
153 // other platforms.
154 void set_restrict_to_user() { restrict_to_user_ = true; }
155
shessa62504d2016-11-07 19:26:12156 // Call to use alternative status-tracking for mmap. Usually this is tracked
157 // in the meta table, but some databases have no meta table.
158 // TODO(shess): Maybe just have all databases use the alt option?
159 void set_mmap_alt_status() { mmap_alt_status_ = true; }
160
kerz42ff2a012016-04-27 04:50:06161 // Call to opt out of memory-mapped file I/O.
shess7dbd4dee2015-10-06 17:39:16162 void set_mmap_disabled() { mmap_disabled_ = true; }
163
[email protected]c3881b372013-05-17 08:39:46164 // Set an error-handling callback. On errors, the error number (and
165 // statement, if available) will be passed to the callback.
166 //
167 // If no callback is set, the default action is to crash in debug
168 // mode or return failure in release mode.
[email protected]c3881b372013-05-17 08:39:46169 typedef base::Callback<void(int, Statement*)> ErrorCallback;
170 void set_error_callback(const ErrorCallback& callback) {
171 error_callback_ = callback;
172 }
[email protected]98cf3002013-07-12 01:38:56173 bool has_error_callback() const {
174 return !error_callback_.is_null();
175 }
[email protected]c3881b372013-05-17 08:39:46176 void reset_error_callback() {
177 error_callback_.Reset();
178 }
179
shess58b8df82015-06-03 00:19:32180 // Set this to enable additional per-connection histogramming. Must be called
181 // before Open().
182 void set_histogram_tag(const std::string& tag);
[email protected]c088e3a32013-01-03 23:59:14183
[email protected]210ce0af2013-05-15 09:10:39184 // Record a sparse UMA histogram sample under
185 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
186 // histogram is recorded.
187 void AddTaggedHistogram(const std::string& name, size_t sample) const;
188
shess58b8df82015-06-03 00:19:32189 // Track various API calls and results. Values corrospond to UMA
190 // histograms, do not modify, or add or delete other than directly
191 // before EVENT_MAX_VALUE.
192 enum Events {
193 // Number of statements run, either with sql::Statement or Execute*().
194 EVENT_STATEMENT_RUN = 0,
195
196 // Number of rows returned by statements run.
197 EVENT_STATEMENT_ROWS,
198
199 // Number of statements successfully run (all steps returned SQLITE_DONE or
200 // SQLITE_ROW).
201 EVENT_STATEMENT_SUCCESS,
202
203 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
204 EVENT_EXECUTE,
205
206 // Number of rows changed by autocommit statements.
207 EVENT_CHANGES_AUTOCOMMIT,
208
209 // Number of rows changed by statements in transactions.
210 EVENT_CHANGES,
211
212 // Count actual SQLite transaction statements (not including nesting).
213 EVENT_BEGIN,
214 EVENT_COMMIT,
215 EVENT_ROLLBACK,
216
shessd90aeea82015-11-13 02:24:31217 // Track success and failure in GetAppropriateMmapSize().
218 // GetAppropriateMmapSize() should record at most one of these per run. The
219 // case of mapping everything is not recorded.
220 EVENT_MMAP_META_MISSING, // No meta table present.
221 EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table.
222 EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table.
223 EVENT_MMAP_VFS_FAILURE, // Failed to access VFS.
224 EVENT_MMAP_FAILED, // Failure from past run.
225 EVENT_MMAP_FAILED_NEW, // Read error in this run.
226 EVENT_MMAP_SUCCESS_NEW, // Read to EOF in this run.
227 EVENT_MMAP_SUCCESS_PARTIAL, // Read but did not reach EOF.
228 EVENT_MMAP_SUCCESS_NO_PROGRESS, // Read quota exhausted.
229
shessa62504d2016-11-07 19:26:12230 EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view.
231 EVENT_MMAP_STATUS_FAILURE_UPDATE,// Failure updating MmapStatus view.
232
shess58b8df82015-06-03 00:19:32233 // Leave this at the end.
234 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
235 EVENT_MAX_VALUE
236 };
237 void RecordEvent(Events event, size_t count);
238 void RecordOneEvent(Events event) {
239 RecordEvent(event, 1);
240 }
241
[email protected]579446c2013-12-16 18:36:52242 // Run "PRAGMA integrity_check" and post each line of
243 // results into |messages|. Returns the success of running the
244 // statement - per the SQLite documentation, if no errors are found the
245 // call should succeed, and a single value "ok" should be in messages.
246 bool FullIntegrityCheck(std::vector<std::string>* messages);
247
248 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
249 // interprets the results returning true if the the statement executes
250 // without error and results in a single "ok" value.
251 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42252
afakhry7c9abe72016-08-05 17:33:19253 // Meant to be called from a client error callback so that it's able to
254 // get diagnostic information about the database.
255 std::string GetDiagnosticInfo(int extended_error, Statement* statement);
256
dskibab4199f82016-11-21 20:16:13257 // Reports memory usage into provided memory dump.
258 bool ReportMemoryUsage(base::trace_event::MemoryAllocatorDump* mad);
259
[email protected]e5ffd0e42009-09-11 21:30:56260 // Initialization ------------------------------------------------------------
261
262 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55263 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33264 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42265
266 // Initializes the SQL connection for a temporary in-memory database. There
267 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55268 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20269 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42270
[email protected]8d409412013-07-19 18:25:30271 // Create a temporary on-disk database. The database will be
272 // deleted after close. This kind of database is similar to
273 // OpenInMemory() for small databases, but can page to disk if the
274 // database becomes large.
275 bool OpenTemporary() WARN_UNUSED_RESULT;
276
[email protected]41a97c812013-02-07 02:35:38277 // Returns true if the database has been successfully opened.
[email protected]765b44502009-10-02 05:01:42278 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56279
280 // Closes the database. This is automatically performed on destruction for
281 // you, but this allows you to close the database early. You must not call
282 // any other functions after closing it. It is permissable to call Close on
283 // an uninitialized or already-closed database.
284 void Close();
285
[email protected]8ada10f2013-12-21 00:42:34286 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
287 // filesystem cache. This can be more efficient than faulting pages
288 // individually. Since this involves blocking I/O, it should only be used if
289 // the caller will immediately read a substantial amount of data from the
290 // database.
[email protected]e5ffd0e42009-09-11 21:30:56291 //
[email protected]8ada10f2013-12-21 00:42:34292 // TODO(shess): Design a set of histograms or an experiment to inform this
293 // decision. Preloading should almost always improve later performance
294 // numbers for this database simply because it pulls operations forward, but
295 // if the data isn't actually used soon then preloading just slows down
296 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56297 void Preload();
298
[email protected]be7995f12013-07-18 18:49:14299 // Try to trim the cache memory used by the database. If |aggressively| is
300 // true, this function will try to free all of the cache memory it can. If
301 // |aggressively| is false, this function will try to cut cache memory
302 // usage by half.
303 void TrimMemory(bool aggressively);
304
[email protected]8e0c01282012-04-06 19:36:49305 // Raze the database to the ground. This approximates creating a
306 // fresh database from scratch, within the constraints of SQLite's
307 // locking protocol (locks and open handles can make doing this with
308 // filesystem operations problematic). Returns true if the database
309 // was razed.
310 //
311 // false is returned if the database is locked by some other
312 // process. RazeWithTimeout() may be used if appropriate.
313 //
314 // NOTE(shess): Raze() will DCHECK in the following situations:
315 // - database is not open.
316 // - the connection has a transaction open.
317 // - a SQLite issue occurs which is structural in nature (like the
318 // statements used are broken).
319 // Since Raze() is expected to be called in unexpected situations,
320 // these all return false, since it is unlikely that the caller
321 // could fix them.
[email protected]6d42f152012-11-10 00:38:24322 //
323 // The database's page size is taken from |page_size_|. The
324 // existing database's |auto_vacuum| setting is lost (the
325 // possibility of corruption makes it unreliable to pull it from the
326 // existing database). To re-enable on the empty database requires
327 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
328 //
329 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
330 // so Raze() sets auto_vacuum to 1.
331 //
332 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
333 // TODO(shess): Bake auto_vacuum into Connection's API so it can
334 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49335 bool Raze();
336 bool RazeWithTimout(base::TimeDelta timeout);
337
[email protected]41a97c812013-02-07 02:35:38338 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30339 // BeginTransaction()), closes the SQLite database, and poisons the
340 // object so that all future operations against the Connection (or
341 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38342 //
[email protected]8d409412013-07-19 18:25:30343 // This is intended as an alternative to Close() in error callbacks.
344 // Close() should still be called at some point.
345 void Poison();
346
347 // Raze() the database and Poison() the handle. Returns the return
348 // value from Raze().
349 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38350 bool RazeAndClose();
351
[email protected]8d2e39e2013-06-24 05:55:08352 // Delete the underlying database files associated with |path|.
353 // This should be used on a database which has no existing
354 // connections. If any other connections are open to the same
355 // database, this could cause odd results or corruption (for
356 // instance if a hot journal is deleted but the associated database
357 // is not).
358 //
359 // Returns true if the database file and associated journals no
360 // longer exist, false otherwise. If the database has never
361 // existed, this will return true.
362 static bool Delete(const base::FilePath& path);
363
[email protected]e5ffd0e42009-09-11 21:30:56364 // Transactions --------------------------------------------------------------
365
366 // Transaction management. We maintain a virtual transaction stack to emulate
367 // nested transactions since sqlite can't do nested transactions. The
368 // limitation is you can't roll back a sub transaction: if any transaction
369 // fails, all transactions open will also be rolled back. Any nested
370 // transactions after one has rolled back will return fail for Begin(). If
371 // Begin() fails, you must not call Commit or Rollback().
372 //
373 // Normally you should use sql::Transaction to manage a transaction, which
374 // will scope it to a C++ context.
375 bool BeginTransaction();
376 void RollbackTransaction();
377 bool CommitTransaction();
378
[email protected]8d409412013-07-19 18:25:30379 // Rollback all outstanding transactions. Use with care, there may
380 // be scoped transactions on the stack.
381 void RollbackAllTransactions();
382
[email protected]e5ffd0e42009-09-11 21:30:56383 // Returns the current transaction nesting, which will be 0 if there are
384 // no open transactions.
385 int transaction_nesting() const { return transaction_nesting_; }
386
[email protected]8d409412013-07-19 18:25:30387 // Attached databases---------------------------------------------------------
388
389 // SQLite supports attaching multiple database files to a single
390 // handle. Attach the database in |other_db_path| to the current
391 // handle under |attachment_point|. |attachment_point| should only
392 // contain characters from [a-zA-Z0-9_].
393 //
394 // Note that calling attach or detach with an open transaction is an
395 // error.
396 bool AttachDatabase(const base::FilePath& other_db_path,
397 const char* attachment_point);
398 bool DetachDatabase(const char* attachment_point);
399
[email protected]e5ffd0e42009-09-11 21:30:56400 // Statements ----------------------------------------------------------------
401
402 // Executes the given SQL string, returning true on success. This is
403 // normally used for simple, 1-off statements that don't take any bound
404 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20405 //
[email protected]eff1fa522011-12-12 23:50:59406 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20407 //
408 // Do not use ignore_result() to ignore all errors. Use
409 // ExecuteAndReturnErrorCode() and ignore only specific errors.
410 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56411
[email protected]eff1fa522011-12-12 23:50:59412 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20413 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59414
[email protected]e5ffd0e42009-09-11 21:30:56415 // Returns true if we have a statement with the given identifier already
416 // cached. This is normally not necessary to call, but can be useful if the
417 // caller has to dynamically build up SQL to avoid doing so if it's already
418 // cached.
419 bool HasCachedStatement(const StatementID& id) const;
420
421 // Returns a statement for the given SQL using the statement cache. It can
422 // take a nontrivial amount of work to parse and compile a statement, so
423 // keeping commonly-used ones around for future use is important for
424 // performance.
425 //
[email protected]eff1fa522011-12-12 23:50:59426 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
427 // the code will crash in debug). The caller must deal with this eventuality,
428 // either by checking validity of the |sql| before calling, by correctly
429 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56430 //
431 // The StatementID and the SQL must always correspond to one-another. The
432 // ID is the lookup into the cache, so crazy things will happen if you use
433 // different SQL with the same ID.
434 //
435 // You will normally use the SQL_FROM_HERE macro to generate a statement
436 // ID associated with the current line of code. This gives uniqueness without
437 // you having to manage unique names. See StatementID above for more.
438 //
439 // Example:
[email protected]3273dce2010-01-27 16:08:08440 // sql::Statement stmt(connection_.GetCachedStatement(
441 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56442 // if (!stmt)
443 // return false; // Error creating statement.
444 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
445 const char* sql);
446
[email protected]eff1fa522011-12-12 23:50:59447 // Used to check a |sql| statement for syntactic validity. If the statement is
448 // valid SQL, returns true.
449 bool IsSQLValid(const char* sql);
450
[email protected]e5ffd0e42009-09-11 21:30:56451 // Returns a non-cached statement for the given SQL. Use this for SQL that
452 // is only executed once or only rarely (there is overhead associated with
453 // keeping a statement cached).
454 //
455 // See GetCachedStatement above for examples and error information.
456 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
457
458 // Info querying -------------------------------------------------------------
459
shessa62504d2016-11-07 19:26:12460 // Returns true if the given structure exists. Instead of test-then-create,
461 // callers should almost always prefer the "IF NOT EXISTS" version of the
462 // CREATE statement.
[email protected]e2cadec82011-12-13 02:00:53463 bool DoesIndexExist(const char* index_name) const;
shessa62504d2016-11-07 19:26:12464 bool DoesTableExist(const char* table_name) const;
465 bool DoesViewExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53466
[email protected]e5ffd0e42009-09-11 21:30:56467 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17468 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56469
470 // Returns sqlite's internal ID for the last inserted row. Valid only
471 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26472 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56473
[email protected]1ed78a32009-09-15 20:24:17474 // Returns sqlite's count of the number of rows modified by the last
475 // statement executed. Will be 0 if no statement has executed or the database
476 // is closed.
477 int GetLastChangeCount() const;
478
[email protected]e5ffd0e42009-09-11 21:30:56479 // Errors --------------------------------------------------------------------
480
481 // Returns the error code associated with the last sqlite operation.
482 int GetErrorCode() const;
483
[email protected]767718e52010-09-21 23:18:49484 // Returns the errno associated with GetErrorCode(). See
485 // SQLITE_LAST_ERRNO in SQLite documentation.
486 int GetLastErrno() const;
487
[email protected]e5ffd0e42009-09-11 21:30:56488 // Returns a pointer to a statically allocated string associated with the
489 // last sqlite operation.
490 const char* GetErrorMessage() const;
491
[email protected]92cd00a2013-08-16 11:09:58492 // Return a reproducible representation of the schema equivalent to
493 // running the following statement at a sqlite3 command-line:
494 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
495 std::string GetSchema() const;
496
shess976814402016-06-21 06:56:25497 // Returns |true| if there is an error expecter (see SetErrorExpecter), and
498 // that expecter returns |true| when passed |error|. Clients which provide an
499 // |error_callback| should use IsExpectedSqliteError() to check for unexpected
500 // errors; if one is detected, DLOG(FATAL) is generally appropriate (see
501 // OnSqliteError implementation).
502 static bool IsExpectedSqliteError(int error);
[email protected]74cdede2013-09-25 05:39:57503
shessc8cd2a162015-10-22 20:30:46504 // Collect various diagnostic information and post a crash dump to aid
505 // debugging. Dump rate per database is limited to prevent overwhelming the
506 // crash server.
507 void ReportDiagnosticInfo(int extended_error, Statement* stmt);
508
[email protected]e5ffd0e42009-09-11 21:30:56509 private:
[email protected]8d409412013-07-19 18:25:30510 // For recovery module.
511 friend class Recovery;
512
shess976814402016-06-21 06:56:25513 // Allow test-support code to set/reset error expecter.
514 friend class test::ScopedErrorExpecter;
[email protected]4350e322013-06-18 22:18:10515
[email protected]eff1fa522011-12-12 23:50:59516 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56517 // (they should go through Statement).
518 friend class Statement;
519
shess58b8df82015-06-03 00:19:32520 friend class test::ScopedCommitHook;
521 friend class test::ScopedScalarFunction;
522 friend class test::ScopedMockTimeSource;
523
shessc8cd2a162015-10-22 20:30:46524 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, CollectDiagnosticInfo);
shess9bf2c672015-12-18 01:18:08525 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSize);
shessa62504d2016-11-07 19:26:12526 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSizeAltStatus);
ssid3be5b1ec2016-01-13 14:21:57527 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, OnMemoryDump);
shessc8cd2a162015-10-22 20:30:46528 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, RegisterIntentToUpload);
529
[email protected]765b44502009-10-02 05:01:42530 // Internal initialize function used by both Init and InitInMemory. The file
531 // name is always 8 bits since we want to use the 8-bit version of
532 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13533 //
534 // |retry_flag| controls retrying the open if the error callback
535 // addressed errors using RazeAndClose().
536 enum Retry {
537 NO_RETRY = 0,
538 RETRY_ON_POISON
539 };
540 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42541
[email protected]41a97c812013-02-07 02:35:38542 // Internal close function used by Close() and RazeAndClose().
543 // |forced| indicates that orderly-shutdown checks should not apply.
544 void CloseInternal(bool forced);
545
[email protected]35f7e5392012-07-27 19:54:50546 // Check whether the current thread is allowed to make IO calls, but only
547 // if database wasn't open in memory. Function is inlined to be a no-op in
548 // official build.
shessc8cd2a162015-10-22 20:30:46549 void AssertIOAllowed() const {
[email protected]35f7e5392012-07-27 19:54:50550 if (!in_memory_)
551 base::ThreadRestrictions::AssertIOAllowed();
552 }
553
shessa62504d2016-11-07 19:26:12554 // Internal helper for Does*Exist() functions.
555 bool DoesSchemaItemExist(const char* name, const char* type) const;
[email protected]e2cadec82011-12-13 02:00:53556
shess976814402016-06-21 06:56:25557 // Accessors for global error-expecter, for injecting behavior during tests.
558 // See test/scoped_error_expecter.h.
559 typedef base::Callback<bool(int)> ErrorExpecterCallback;
560 static ErrorExpecterCallback* current_expecter_cb_;
561 static void SetErrorExpecter(ErrorExpecterCallback* expecter);
562 static void ResetErrorExpecter();
[email protected]4350e322013-06-18 22:18:10563
[email protected]e5ffd0e42009-09-11 21:30:56564 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
565 // Refcounting allows us to give these statements out to sql::Statement
566 // objects while also optionally maintaining a cache of compiled statements
567 // by just keeping a refptr to these objects.
568 //
569 // A statement ref can be valid, in which case it can be used, or invalid to
570 // indicate that the statement hasn't been created yet, has an error, or has
571 // been destroyed.
572 //
573 // The Connection may revoke a StatementRef in some error cases, so callers
574 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23575 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56576 public:
[email protected]41a97c812013-02-07 02:35:38577 // |connection| is the sql::Connection instance associated with
578 // the statement, and is used for tracking outstanding statements
579 // and for error handling. Set to NULL for invalid or untracked
580 // refs. |stmt| is the actual statement, and should only be NULL
581 // to create an invalid ref. |was_valid| indicates whether the
582 // statement should be considered valid for diagnistic purposes.
583 // |was_valid| can be true for NULL |stmt| if the connection has
584 // been forcibly closed by an error handler.
585 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56586
587 // When true, the statement can be used.
588 bool is_valid() const { return !!stmt_; }
589
[email protected]41a97c812013-02-07 02:35:38590 // When true, the statement is either currently valid, or was
591 // previously valid but the connection was forcibly closed. Used
592 // for diagnostic checks.
593 bool was_valid() const { return was_valid_; }
594
[email protected]b4c363b2013-01-17 13:11:17595 // If we've not been linked to a connection, this will be NULL.
596 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
597 // which prevents Statement::OnError() from forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56598 Connection* connection() const { return connection_; }
599
600 // Returns the sqlite statement if any. If the statement is not active,
601 // this will return NULL.
602 sqlite3_stmt* stmt() const { return stmt_; }
603
604 // Destroys the compiled statement and marks it NULL. The statement will
[email protected]41a97c812013-02-07 02:35:38605 // no longer be active. |forced| is used to indicate if orderly-shutdown
606 // checks should apply (see Connection::RazeAndClose()).
607 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56608
[email protected]35f7e5392012-07-27 19:54:50609 // Check whether the current thread is allowed to make IO calls, but only
610 // if database wasn't open in memory.
611 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
612
[email protected]e5ffd0e42009-09-11 21:30:56613 private:
[email protected]877d55d2009-11-05 21:53:08614 friend class base::RefCounted<StatementRef>;
615
616 ~StatementRef();
617
[email protected]e5ffd0e42009-09-11 21:30:56618 Connection* connection_;
619 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38620 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56621
622 DISALLOW_COPY_AND_ASSIGN(StatementRef);
623 };
624 friend class StatementRef;
625
626 // Executes a rollback statement, ignoring all transaction state. Used
627 // internally in the transaction management code.
628 void DoRollback();
629
630 // Called by a StatementRef when it's being created or destroyed. See
631 // open_statements_ below.
632 void StatementRefCreated(StatementRef* ref);
633 void StatementRefDeleted(StatementRef* ref);
634
[email protected]2f496b42013-09-26 18:36:58635 // Called when a sqlite function returns an error, which is passed
636 // as |err|. The return value is the error code to be reflected
637 // back to client code. |stmt| is non-NULL if the error relates to
638 // an sql::Statement instance. |sql| is non-NULL if the error
639 // relates to non-statement sql code (Execute, for instance). Both
640 // can be NULL, but both should never be set.
641 // NOTE(shess): Originally, the return value was intended to allow
642 // error handlers to transparently convert errors into success.
643 // Unfortunately, transactions are not generally restartable, so
644 // this did not work out.
shess9e77283d2016-06-13 23:53:20645 int OnSqliteError(int err, Statement* stmt, const char* sql) const;
[email protected]faa604e2009-09-25 22:38:59646
[email protected]5b96f3772010-09-28 16:30:57647 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20648 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
649 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57650
shess9e77283d2016-06-13 23:53:20651 // Implementation helper for GetUniqueStatement() and GetUntrackedStatement().
652 // |tracking_db| is the db the resulting ref should register with for
653 // outstanding statement tracking, which should be |this| to track or NULL to
654 // not track.
655 scoped_refptr<StatementRef> GetStatementImpl(
656 sql::Connection* tracking_db, const char* sql) const;
657
658 // Helper for implementing const member functions. Like GetUniqueStatement(),
659 // except the StatementRef is not entered into |open_statements_|, so an
660 // outstanding StatementRef from this function can block closing the database.
661 // The StatementRef will not call OnSqliteError(), because that can call
662 // |error_callback_| which can close the database.
[email protected]2eec0a22012-07-24 01:59:58663 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
664
[email protected]579446c2013-12-16 18:36:52665 bool IntegrityCheckHelper(
666 const char* pragma_sql,
667 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
668
shess58b8df82015-06-03 00:19:32669 // Record time spent executing explicit COMMIT statements.
670 void RecordCommitTime(const base::TimeDelta& delta);
671
672 // Record time in DML (Data Manipulation Language) statements such as INSERT
673 // or UPDATE outside of an explicit transaction. Due to implementation
674 // limitations time spent on DDL (Data Definition Language) statements such as
675 // ALTER and CREATE is not included.
676 void RecordAutoCommitTime(const base::TimeDelta& delta);
677
678 // Record all time spent on updating the database. This includes CommitTime()
679 // and AutoCommitTime(), plus any time spent spilling to the journal if
680 // transactions do not fit in cache.
681 void RecordUpdateTime(const base::TimeDelta& delta);
682
683 // Record all time spent running statements, including time spent doing
684 // updates and time spent on read-only queries.
685 void RecordQueryTime(const base::TimeDelta& delta);
686
687 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
688 // true, autocommit time if the database is not in a transaction, or update
689 // time if the database is in a transaction. Also records change count to
690 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
691 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
692
693 // Helper to return the current time from the time source.
694 base::TimeTicks Now() {
695 return clock_->Now();
696 }
697
shess7dbd4dee2015-10-06 17:39:16698 // Release page-cache memory if memory-mapped I/O is enabled and the database
699 // was changed. Passing true for |implicit_change_performed| allows
700 // overriding the change detection for cases like DDL (CREATE, DROP, etc),
701 // which do not participate in the total-rows-changed tracking.
702 void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
703
shessc8cd2a162015-10-22 20:30:46704 // Returns the results of sqlite3_db_filename(), which should match the path
705 // passed to Open().
706 base::FilePath DbPath() const;
707
708 // Helper to prevent uploading too many diagnostic dumps for a given database,
709 // since every dump will likely show the same problem. Returns |true| if this
710 // function was not previously called for this database, and the persistent
711 // storage which tracks state was updated.
712 //
713 // |false| is returned if the function was previously called for this
714 // database, even across restarts. |false| is also returned if the persistent
715 // storage cannot be updated, possibly indicating problems requiring user or
716 // admin intervention, such as filesystem corruption or disk full. |false| is
717 // also returned if the persistent storage contains invalid data or is not
718 // readable.
719 //
720 // TODO(shess): It would make sense to reset the persistent state if the
721 // database is razed or recovered, or if the diagnostic code adds new
722 // capabilities.
723 bool RegisterIntentToUpload() const;
724
725 // Helper to collect diagnostic info for a corrupt database.
726 std::string CollectCorruptionInfo();
727
728 // Helper to collect diagnostic info for errors.
729 std::string CollectErrorInfo(int error, Statement* stmt) const;
730
shessd90aeea82015-11-13 02:24:31731 // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors
732 // can make it unsafe to map a file, so the file is read using regular I/O,
733 // with any errors causing 0 (don't map anything) to be returned. If the
734 // entire file is read without error, a large value is returned which will
735 // allow the entire file to be mapped in most cases.
736 //
737 // Results are recorded in the database's meta table for future reference, so
738 // the file should only be read through once.
739 size_t GetAppropriateMmapSize();
740
shessa62504d2016-11-07 19:26:12741 // Helpers for GetAppropriateMmapSize().
742 bool GetMmapAltStatus(int64_t* status);
743 bool SetMmapAltStatus(int64_t status);
744
[email protected]e5ffd0e42009-09-11 21:30:56745 // The actual sqlite database. Will be NULL before Init has been called or if
746 // Init resulted in an error.
747 sqlite3* db_;
748
749 // Parameters we'll configure in sqlite before doing anything else. Zero means
750 // use the default value.
751 int page_size_;
752 int cache_size_;
753 bool exclusive_locking_;
[email protected]81a2a602013-07-17 19:10:36754 bool restrict_to_user_;
[email protected]e5ffd0e42009-09-11 21:30:56755
756 // All cached statements. Keeping a reference to these statements means that
757 // they'll remain active.
758 typedef std::map<StatementID, scoped_refptr<StatementRef> >
759 CachedStatementMap;
760 CachedStatementMap statement_cache_;
761
762 // A list of all StatementRefs we've given out. Each ref must register with
763 // us when it's created or destroyed. This allows us to potentially close
764 // any open statements when we encounter an error.
765 typedef std::set<StatementRef*> StatementRefSet;
766 StatementRefSet open_statements_;
767
768 // Number of currently-nested transactions.
769 int transaction_nesting_;
770
771 // True if any of the currently nested transactions have been rolled back.
772 // When we get to the outermost transaction, this will determine if we do
773 // a rollback instead of a commit.
774 bool needs_rollback_;
775
[email protected]35f7e5392012-07-27 19:54:50776 // True if database is open with OpenInMemory(), False if database is open
777 // with Open().
778 bool in_memory_;
779
[email protected]41a97c812013-02-07 02:35:38780 // |true| if the connection was closed using RazeAndClose(). Used
781 // to enable diagnostics to distinguish calls to never-opened
782 // databases (incorrect use of the API) from calls to once-valid
783 // databases.
784 bool poisoned_;
785
shessa62504d2016-11-07 19:26:12786 // |true| to use alternate storage for tracking mmap status.
787 bool mmap_alt_status_;
788
shess7dbd4dee2015-10-06 17:39:16789 // |true| if SQLite memory-mapped I/O is not desired for this connection.
790 bool mmap_disabled_;
791
792 // |true| if SQLite memory-mapped I/O was enabled for this connection.
793 // Used by ReleaseCacheMemoryIfNeeded().
794 bool mmap_enabled_;
795
796 // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
797 // since memory was last released.
798 int total_changes_at_last_release_;
799
[email protected]c3881b372013-05-17 08:39:46800 ErrorCallback error_callback_;
801
[email protected]210ce0af2013-05-15 09:10:39802 // Tag for auxiliary histograms.
803 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14804
shess58b8df82015-06-03 00:19:32805 // Linear histogram for RecordEvent().
806 base::HistogramBase* stats_histogram_;
807
808 // Histogram for tracking time taken in commit.
809 base::HistogramBase* commit_time_histogram_;
810
811 // Histogram for tracking time taken in autocommit updates.
812 base::HistogramBase* autocommit_time_histogram_;
813
814 // Histogram for tracking time taken in updates (including commit and
815 // autocommit).
816 base::HistogramBase* update_time_histogram_;
817
818 // Histogram for tracking time taken in all queries.
819 base::HistogramBase* query_time_histogram_;
820
821 // Source for timing information, provided to allow tests to inject time
822 // changes.
mostynbd82cd9952016-04-11 20:05:34823 std::unique_ptr<TimeSource> clock_;
shess58b8df82015-06-03 00:19:32824
ssid3be5b1ec2016-01-13 14:21:57825 // Stores the dump provider object when db is open.
mostynbd82cd9952016-04-11 20:05:34826 std::unique_ptr<ConnectionMemoryDumpProvider> memory_dump_provider_;
ssid3be5b1ec2016-01-13 14:21:57827
[email protected]e5ffd0e42009-09-11 21:30:56828 DISALLOW_COPY_AND_ASSIGN(Connection);
829};
830
831} // namespace sql
832
[email protected]f0a54b22011-07-19 18:40:21833#endif // SQL_CONNECTION_H_