[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
[email protected] | f0a54b2 | 2011-07-19 18:40:21 | [diff] [blame] | 5 | #ifndef SQL_CONNECTION_H_ |
| 6 | #define SQL_CONNECTION_H_ |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 7 | |
avi | 0b51920 | 2015-12-21 07:25:19 | [diff] [blame] | 8 | #include <stddef.h> |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 9 | #include <stdint.h> |
mostynb | d82cd995 | 2016-04-11 20:05:34 | [diff] [blame] | 10 | #include <memory> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 11 | #include <set> |
[email protected] | 7d6aee4e | 2009-09-12 01:12:33 | [diff] [blame] | 12 | #include <string> |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 13 | #include <vector> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 14 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 15 | #include "base/callback.h" |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 16 | #include "base/compiler_specific.h" |
Dmitry Skiba | a9ad8fe4 | 2017-08-16 21:02:48 | [diff] [blame] | 17 | #include "base/containers/flat_map.h" |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 18 | #include "base/gtest_prod_util.h" |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 19 | #include "base/macros.h" |
[email protected] | 3b63f8f4 | 2011-03-28 01:54:15 | [diff] [blame] | 20 | #include "base/memory/ref_counted.h" |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 21 | #include "base/threading/thread_restrictions.h" |
[email protected] | 2b59d68 | 2013-06-28 15:22:03 | [diff] [blame] | 22 | #include "base/time/time.h" |
[email protected] | d452696 | 2011-11-10 21:40:28 | [diff] [blame] | 23 | #include "sql/sql_export.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 24 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 25 | struct sqlite3; |
| 26 | struct sqlite3_stmt; |
| 27 | |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 28 | namespace base { |
| 29 | class FilePath; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 30 | class HistogramBase; |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 31 | namespace trace_event { |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 32 | class ProcessMemoryDump; |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 33 | } |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 34 | } |
| 35 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 36 | namespace sql { |
| 37 | |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 38 | class ConnectionMemoryDumpProvider; |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 39 | class Recovery; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 40 | class Statement; |
| 41 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 42 | // To allow some test classes to be friended. |
| 43 | namespace test { |
| 44 | class ScopedCommitHook; |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 45 | class ScopedErrorExpecter; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 46 | class ScopedScalarFunction; |
| 47 | class ScopedMockTimeSource; |
| 48 | } |
| 49 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 50 | // 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. |
| 65 | class 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] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 96 | class Connection; |
| 97 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 98 | // Abstract the source of timing information for metrics (RecordCommitTime, etc) |
| 99 | // to allow testing control. |
| 100 | class 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 | |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 112 | class SQL_EXPORT Connection { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 113 | private: |
| 114 | class StatementRef; // Forward declaration, see real one below. |
| 115 | |
| 116 | public: |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 117 | // The database is opened by calling Open[InMemory](). Any uncommitted |
| 118 | // transactions will be rolled back when this object is deleted. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 119 | Connection(); |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 120 | ~Connection(); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 121 | |
| 122 | // Pre-init configuration ---------------------------------------------------- |
| 123 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 124 | // Sets the page size that will be used when creating a new database. This |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 125 | // 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] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 135 | // called before Open() to have an effect. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 136 | 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] | 4ab952f | 2014-04-01 20:18:16 | [diff] [blame] | 140 | // transaction (requires another access to the DB) and because we don't |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 141 | // 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] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 147 | // This must be called before Open() to have an effect. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 148 | void set_exclusive_locking() { exclusive_locking_ = true; } |
| 149 | |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame] | 150 | // 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 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 156 | // 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 | |
kerz | 42ff2a01 | 2016-04-27 04:50:06 | [diff] [blame] | 161 | // Call to opt out of memory-mapped file I/O. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 162 | void set_mmap_disabled() { mmap_disabled_ = true; } |
| 163 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 164 | // 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] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 169 | typedef base::Callback<void(int, Statement*)> ErrorCallback; |
| 170 | void set_error_callback(const ErrorCallback& callback) { |
| 171 | error_callback_ = callback; |
| 172 | } |
[email protected] | 98cf300 | 2013-07-12 01:38:56 | [diff] [blame] | 173 | bool has_error_callback() const { |
| 174 | return !error_callback_.is_null(); |
| 175 | } |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 176 | void reset_error_callback() { |
| 177 | error_callback_.Reset(); |
| 178 | } |
| 179 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 180 | // 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] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 183 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 184 | // 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 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 189 | // 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 | |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 217 | // 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 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 230 | EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view. |
| 231 | EVENT_MMAP_STATUS_FAILURE_UPDATE,// Failure updating MmapStatus view. |
| 232 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 233 | // 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] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 242 | // 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] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 252 | |
afakhry | 7c9abe7 | 2016-08-05 17:33:19 | [diff] [blame] | 253 | // 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 | |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 257 | // Reports memory usage into provided memory dump with the given name. |
| 258 | bool ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd, |
| 259 | const std::string& dump_name); |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 260 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 261 | // Initialization ------------------------------------------------------------ |
| 262 | |
| 263 | // Initializes the SQL connection for the given file, returning true if the |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 264 | // file could be opened. You can call this or OpenInMemory. |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 265 | bool Open(const base::FilePath& path) WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 266 | |
| 267 | // Initializes the SQL connection for a temporary in-memory database. There |
| 268 | // will be no associated file on disk, and the initial database will be |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 269 | // empty. You can call this or Open. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 270 | bool OpenInMemory() WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 271 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 272 | // Create a temporary on-disk database. The database will be |
| 273 | // deleted after close. This kind of database is similar to |
| 274 | // OpenInMemory() for small databases, but can page to disk if the |
| 275 | // database becomes large. |
| 276 | bool OpenTemporary() WARN_UNUSED_RESULT; |
| 277 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 278 | // Returns true if the database has been successfully opened. |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 279 | bool is_open() const { return !!db_; } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 280 | |
| 281 | // Closes the database. This is automatically performed on destruction for |
| 282 | // you, but this allows you to close the database early. You must not call |
| 283 | // any other functions after closing it. It is permissable to call Close on |
| 284 | // an uninitialized or already-closed database. |
| 285 | void Close(); |
| 286 | |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 287 | // Reads the first <cache-size>*<page-size> bytes of the file to prime the |
| 288 | // filesystem cache. This can be more efficient than faulting pages |
| 289 | // individually. Since this involves blocking I/O, it should only be used if |
| 290 | // the caller will immediately read a substantial amount of data from the |
| 291 | // database. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 292 | // |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 293 | // TODO(shess): Design a set of histograms or an experiment to inform this |
| 294 | // decision. Preloading should almost always improve later performance |
| 295 | // numbers for this database simply because it pulls operations forward, but |
| 296 | // if the data isn't actually used soon then preloading just slows down |
| 297 | // everything else. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 298 | void Preload(); |
| 299 | |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 300 | // Try to trim the cache memory used by the database. If |aggressively| is |
| 301 | // true, this function will try to free all of the cache memory it can. If |
| 302 | // |aggressively| is false, this function will try to cut cache memory |
| 303 | // usage by half. |
| 304 | void TrimMemory(bool aggressively); |
| 305 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 306 | // Raze the database to the ground. This approximates creating a |
| 307 | // fresh database from scratch, within the constraints of SQLite's |
| 308 | // locking protocol (locks and open handles can make doing this with |
| 309 | // filesystem operations problematic). Returns true if the database |
| 310 | // was razed. |
| 311 | // |
| 312 | // false is returned if the database is locked by some other |
Carlos Knippschild | 46800c9f | 2017-09-02 02:21:43 | [diff] [blame] | 313 | // process. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 314 | // |
| 315 | // NOTE(shess): Raze() will DCHECK in the following situations: |
| 316 | // - database is not open. |
| 317 | // - the connection has a transaction open. |
| 318 | // - a SQLite issue occurs which is structural in nature (like the |
| 319 | // statements used are broken). |
| 320 | // Since Raze() is expected to be called in unexpected situations, |
| 321 | // these all return false, since it is unlikely that the caller |
| 322 | // could fix them. |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 323 | // |
| 324 | // The database's page size is taken from |page_size_|. The |
| 325 | // existing database's |auto_vacuum| setting is lost (the |
| 326 | // possibility of corruption makes it unreliable to pull it from the |
| 327 | // existing database). To re-enable on the empty database requires |
| 328 | // running "PRAGMA auto_vacuum = 1;" then "VACUUM". |
| 329 | // |
| 330 | // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1, |
| 331 | // so Raze() sets auto_vacuum to 1. |
| 332 | // |
| 333 | // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB. |
| 334 | // TODO(shess): Bake auto_vacuum into Connection's API so it can |
| 335 | // just pick up the default. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 336 | bool Raze(); |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 337 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 338 | // Breaks all outstanding transactions (as initiated by |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 339 | // 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] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 342 | // |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 343 | // 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] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 350 | bool RazeAndClose(); |
| 351 | |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 352 | // 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] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 364 | // 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] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 379 | // Rollback all outstanding transactions. Use with care, there may |
| 380 | // be scoped transactions on the stack. |
| 381 | void RollbackAllTransactions(); |
| 382 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 383 | // 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] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 387 | // 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 | // |
Victor Costan | 8a87f7e5 | 2017-11-10 01:29:30 | [diff] [blame^] | 394 | // Attaching a database while a transaction is open will have |
| 395 | // platform-dependent results, as explained below. |
| 396 | // |
| 397 | // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can |
| 398 | // be attached while a transaction is opened. However, these databases cannot |
| 399 | // be detached until the transaction is committed or aborted. On iOS, the |
| 400 | // built-in SQLite might not be older than 3.21. In that case, attaching a |
| 401 | // database while a transaction is open results in a error. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 402 | bool AttachDatabase(const base::FilePath& other_db_path, |
| 403 | const char* attachment_point); |
| 404 | bool DetachDatabase(const char* attachment_point); |
| 405 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 406 | // Statements ---------------------------------------------------------------- |
| 407 | |
| 408 | // Executes the given SQL string, returning true on success. This is |
| 409 | // normally used for simple, 1-off statements that don't take any bound |
| 410 | // parameters and don't return any data (e.g. CREATE TABLE). |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 411 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 412 | // This will DCHECK if the |sql| contains errors. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 413 | // |
| 414 | // Do not use ignore_result() to ignore all errors. Use |
| 415 | // ExecuteAndReturnErrorCode() and ignore only specific errors. |
| 416 | bool Execute(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 417 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 418 | // Like Execute(), but returns the error code given by SQLite. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 419 | int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 420 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 421 | // Returns true if we have a statement with the given identifier already |
| 422 | // cached. This is normally not necessary to call, but can be useful if the |
| 423 | // caller has to dynamically build up SQL to avoid doing so if it's already |
| 424 | // cached. |
| 425 | bool HasCachedStatement(const StatementID& id) const; |
| 426 | |
| 427 | // Returns a statement for the given SQL using the statement cache. It can |
| 428 | // take a nontrivial amount of work to parse and compile a statement, so |
| 429 | // keeping commonly-used ones around for future use is important for |
| 430 | // performance. |
| 431 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 432 | // If the |sql| has an error, an invalid, inert StatementRef is returned (and |
| 433 | // the code will crash in debug). The caller must deal with this eventuality, |
| 434 | // either by checking validity of the |sql| before calling, by correctly |
| 435 | // handling the return of an inert statement, or both. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 436 | // |
| 437 | // The StatementID and the SQL must always correspond to one-another. The |
| 438 | // ID is the lookup into the cache, so crazy things will happen if you use |
| 439 | // different SQL with the same ID. |
| 440 | // |
| 441 | // You will normally use the SQL_FROM_HERE macro to generate a statement |
| 442 | // ID associated with the current line of code. This gives uniqueness without |
| 443 | // you having to manage unique names. See StatementID above for more. |
| 444 | // |
| 445 | // Example: |
[email protected] | 3273dce | 2010-01-27 16:08:08 | [diff] [blame] | 446 | // sql::Statement stmt(connection_.GetCachedStatement( |
| 447 | // SQL_FROM_HERE, "SELECT * FROM foo")); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 448 | // if (!stmt) |
| 449 | // return false; // Error creating statement. |
| 450 | scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id, |
| 451 | const char* sql); |
| 452 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 453 | // Used to check a |sql| statement for syntactic validity. If the statement is |
| 454 | // valid SQL, returns true. |
| 455 | bool IsSQLValid(const char* sql); |
| 456 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 457 | // Returns a non-cached statement for the given SQL. Use this for SQL that |
| 458 | // is only executed once or only rarely (there is overhead associated with |
| 459 | // keeping a statement cached). |
| 460 | // |
| 461 | // See GetCachedStatement above for examples and error information. |
| 462 | scoped_refptr<StatementRef> GetUniqueStatement(const char* sql); |
| 463 | |
| 464 | // Info querying ------------------------------------------------------------- |
| 465 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 466 | // Returns true if the given structure exists. Instead of test-then-create, |
| 467 | // callers should almost always prefer the "IF NOT EXISTS" version of the |
| 468 | // CREATE statement. |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 469 | bool DoesIndexExist(const char* index_name) const; |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 470 | bool DoesTableExist(const char* table_name) const; |
| 471 | bool DoesViewExist(const char* table_name) const; |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 472 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 473 | // Returns true if a column with the given name exists in the given table. |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 474 | bool DoesColumnExist(const char* table_name, const char* column_name) const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 475 | |
| 476 | // Returns sqlite's internal ID for the last inserted row. Valid only |
| 477 | // immediately after an insert. |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 478 | int64_t GetLastInsertRowId() const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 479 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 480 | // Returns sqlite's count of the number of rows modified by the last |
| 481 | // statement executed. Will be 0 if no statement has executed or the database |
| 482 | // is closed. |
| 483 | int GetLastChangeCount() const; |
| 484 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 485 | // Errors -------------------------------------------------------------------- |
| 486 | |
| 487 | // Returns the error code associated with the last sqlite operation. |
| 488 | int GetErrorCode() const; |
| 489 | |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 490 | // Returns the errno associated with GetErrorCode(). See |
| 491 | // SQLITE_LAST_ERRNO in SQLite documentation. |
| 492 | int GetLastErrno() const; |
| 493 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 494 | // Returns a pointer to a statically allocated string associated with the |
| 495 | // last sqlite operation. |
| 496 | const char* GetErrorMessage() const; |
| 497 | |
[email protected] | 92cd00a | 2013-08-16 11:09:58 | [diff] [blame] | 498 | // Return a reproducible representation of the schema equivalent to |
| 499 | // running the following statement at a sqlite3 command-line: |
| 500 | // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4; |
| 501 | std::string GetSchema() const; |
| 502 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 503 | // Returns |true| if there is an error expecter (see SetErrorExpecter), and |
| 504 | // that expecter returns |true| when passed |error|. Clients which provide an |
| 505 | // |error_callback| should use IsExpectedSqliteError() to check for unexpected |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 506 | // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 507 | // OnSqliteError implementation). |
| 508 | static bool IsExpectedSqliteError(int error); |
[email protected] | 74cdede | 2013-09-25 05:39:57 | [diff] [blame] | 509 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 510 | // Collect various diagnostic information and post a crash dump to aid |
| 511 | // debugging. Dump rate per database is limited to prevent overwhelming the |
| 512 | // crash server. |
| 513 | void ReportDiagnosticInfo(int extended_error, Statement* stmt); |
| 514 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 515 | private: |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 516 | // For recovery module. |
| 517 | friend class Recovery; |
| 518 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 519 | // Allow test-support code to set/reset error expecter. |
| 520 | friend class test::ScopedErrorExpecter; |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 521 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 522 | // Statement accesses StatementRef which we don't want to expose to everybody |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 523 | // (they should go through Statement). |
| 524 | friend class Statement; |
| 525 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 526 | friend class test::ScopedCommitHook; |
| 527 | friend class test::ScopedScalarFunction; |
| 528 | friend class test::ScopedMockTimeSource; |
| 529 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 530 | FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, CollectDiagnosticInfo); |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 531 | FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSize); |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 532 | FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSizeAltStatus); |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 533 | FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, OnMemoryDump); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 534 | FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, RegisterIntentToUpload); |
shess | f7fcc45 | 2017-04-19 22:10:41 | [diff] [blame] | 535 | FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 536 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 537 | // Internal initialize function used by both Init and InitInMemory. The file |
| 538 | // name is always 8 bits since we want to use the 8-bit version of |
| 539 | // sqlite3_open. The string can also be sqlite's special ":memory:" string. |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 540 | // |
| 541 | // |retry_flag| controls retrying the open if the error callback |
| 542 | // addressed errors using RazeAndClose(). |
| 543 | enum Retry { |
| 544 | NO_RETRY = 0, |
| 545 | RETRY_ON_POISON |
| 546 | }; |
| 547 | bool OpenInternal(const std::string& file_name, Retry retry_flag); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 548 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 549 | // Internal close function used by Close() and RazeAndClose(). |
| 550 | // |forced| indicates that orderly-shutdown checks should not apply. |
| 551 | void CloseInternal(bool forced); |
| 552 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 553 | // Check whether the current thread is allowed to make IO calls, but only |
| 554 | // if database wasn't open in memory. Function is inlined to be a no-op in |
| 555 | // official build. |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 556 | void AssertIOAllowed() const { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 557 | if (!in_memory_) |
Francois Doray | 66bdfd8 | 2017-10-20 13:50:37 | [diff] [blame] | 558 | base::AssertBlockingAllowed(); |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 559 | } |
| 560 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 561 | // Internal helper for Does*Exist() functions. |
| 562 | bool DoesSchemaItemExist(const char* name, const char* type) const; |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 563 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 564 | // Accessors for global error-expecter, for injecting behavior during tests. |
| 565 | // See test/scoped_error_expecter.h. |
| 566 | typedef base::Callback<bool(int)> ErrorExpecterCallback; |
| 567 | static ErrorExpecterCallback* current_expecter_cb_; |
| 568 | static void SetErrorExpecter(ErrorExpecterCallback* expecter); |
| 569 | static void ResetErrorExpecter(); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 570 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 571 | // A StatementRef is a refcounted wrapper around a sqlite statement pointer. |
| 572 | // Refcounting allows us to give these statements out to sql::Statement |
| 573 | // objects while also optionally maintaining a cache of compiled statements |
| 574 | // by just keeping a refptr to these objects. |
| 575 | // |
| 576 | // A statement ref can be valid, in which case it can be used, or invalid to |
| 577 | // indicate that the statement hasn't been created yet, has an error, or has |
| 578 | // been destroyed. |
| 579 | // |
| 580 | // The Connection may revoke a StatementRef in some error cases, so callers |
| 581 | // should always check validity before using. |
[email protected] | 601dc6a | 2011-11-12 01:14:23 | [diff] [blame] | 582 | class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 583 | public: |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 584 | // |connection| is the sql::Connection instance associated with |
| 585 | // the statement, and is used for tracking outstanding statements |
| 586 | // and for error handling. Set to NULL for invalid or untracked |
| 587 | // refs. |stmt| is the actual statement, and should only be NULL |
| 588 | // to create an invalid ref. |was_valid| indicates whether the |
| 589 | // statement should be considered valid for diagnistic purposes. |
| 590 | // |was_valid| can be true for NULL |stmt| if the connection has |
| 591 | // been forcibly closed by an error handler. |
| 592 | StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 593 | |
| 594 | // When true, the statement can be used. |
| 595 | bool is_valid() const { return !!stmt_; } |
| 596 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 597 | // When true, the statement is either currently valid, or was |
| 598 | // previously valid but the connection was forcibly closed. Used |
| 599 | // for diagnostic checks. |
| 600 | bool was_valid() const { return was_valid_; } |
| 601 | |
[email protected] | b4c363b | 2013-01-17 13:11:17 | [diff] [blame] | 602 | // If we've not been linked to a connection, this will be NULL. |
| 603 | // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(), |
| 604 | // which prevents Statement::OnError() from forwarding errors. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 605 | Connection* connection() const { return connection_; } |
| 606 | |
| 607 | // Returns the sqlite statement if any. If the statement is not active, |
| 608 | // this will return NULL. |
| 609 | sqlite3_stmt* stmt() const { return stmt_; } |
| 610 | |
| 611 | // Destroys the compiled statement and marks it NULL. The statement will |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 612 | // no longer be active. |forced| is used to indicate if orderly-shutdown |
| 613 | // checks should apply (see Connection::RazeAndClose()). |
| 614 | void Close(bool forced); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 615 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 616 | // Check whether the current thread is allowed to make IO calls, but only |
| 617 | // if database wasn't open in memory. |
| 618 | void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); } |
| 619 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 620 | private: |
[email protected] | 877d55d | 2009-11-05 21:53:08 | [diff] [blame] | 621 | friend class base::RefCounted<StatementRef>; |
| 622 | |
| 623 | ~StatementRef(); |
| 624 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 625 | Connection* connection_; |
| 626 | sqlite3_stmt* stmt_; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 627 | bool was_valid_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 628 | |
| 629 | DISALLOW_COPY_AND_ASSIGN(StatementRef); |
| 630 | }; |
| 631 | friend class StatementRef; |
| 632 | |
| 633 | // Executes a rollback statement, ignoring all transaction state. Used |
| 634 | // internally in the transaction management code. |
| 635 | void DoRollback(); |
| 636 | |
| 637 | // Called by a StatementRef when it's being created or destroyed. See |
| 638 | // open_statements_ below. |
| 639 | void StatementRefCreated(StatementRef* ref); |
| 640 | void StatementRefDeleted(StatementRef* ref); |
| 641 | |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 642 | // Called when a sqlite function returns an error, which is passed |
| 643 | // as |err|. The return value is the error code to be reflected |
| 644 | // back to client code. |stmt| is non-NULL if the error relates to |
| 645 | // an sql::Statement instance. |sql| is non-NULL if the error |
| 646 | // relates to non-statement sql code (Execute, for instance). Both |
| 647 | // can be NULL, but both should never be set. |
| 648 | // NOTE(shess): Originally, the return value was intended to allow |
| 649 | // error handlers to transparently convert errors into success. |
| 650 | // Unfortunately, transactions are not generally restartable, so |
| 651 | // this did not work out. |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 652 | int OnSqliteError(int err, Statement* stmt, const char* sql) const; |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 653 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 654 | // Like |Execute()|, but retries if the database is locked. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 655 | bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout) |
| 656 | WARN_UNUSED_RESULT; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 657 | |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 658 | // Implementation helper for GetUniqueStatement() and GetUntrackedStatement(). |
| 659 | // |tracking_db| is the db the resulting ref should register with for |
| 660 | // outstanding statement tracking, which should be |this| to track or NULL to |
| 661 | // not track. |
| 662 | scoped_refptr<StatementRef> GetStatementImpl( |
| 663 | sql::Connection* tracking_db, const char* sql) const; |
| 664 | |
| 665 | // Helper for implementing const member functions. Like GetUniqueStatement(), |
| 666 | // except the StatementRef is not entered into |open_statements_|, so an |
| 667 | // outstanding StatementRef from this function can block closing the database. |
| 668 | // The StatementRef will not call OnSqliteError(), because that can call |
| 669 | // |error_callback_| which can close the database. |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 670 | scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const; |
| 671 | |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 672 | bool IntegrityCheckHelper( |
| 673 | const char* pragma_sql, |
| 674 | std::vector<std::string>* messages) WARN_UNUSED_RESULT; |
| 675 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 676 | // Record time spent executing explicit COMMIT statements. |
| 677 | void RecordCommitTime(const base::TimeDelta& delta); |
| 678 | |
| 679 | // Record time in DML (Data Manipulation Language) statements such as INSERT |
| 680 | // or UPDATE outside of an explicit transaction. Due to implementation |
| 681 | // limitations time spent on DDL (Data Definition Language) statements such as |
| 682 | // ALTER and CREATE is not included. |
| 683 | void RecordAutoCommitTime(const base::TimeDelta& delta); |
| 684 | |
| 685 | // Record all time spent on updating the database. This includes CommitTime() |
| 686 | // and AutoCommitTime(), plus any time spent spilling to the journal if |
| 687 | // transactions do not fit in cache. |
| 688 | void RecordUpdateTime(const base::TimeDelta& delta); |
| 689 | |
| 690 | // Record all time spent running statements, including time spent doing |
| 691 | // updates and time spent on read-only queries. |
| 692 | void RecordQueryTime(const base::TimeDelta& delta); |
| 693 | |
| 694 | // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is |
| 695 | // true, autocommit time if the database is not in a transaction, or update |
| 696 | // time if the database is in a transaction. Also records change count to |
| 697 | // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT. |
| 698 | void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only); |
| 699 | |
| 700 | // Helper to return the current time from the time source. |
| 701 | base::TimeTicks Now() { |
| 702 | return clock_->Now(); |
| 703 | } |
| 704 | |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 705 | // Release page-cache memory if memory-mapped I/O is enabled and the database |
| 706 | // was changed. Passing true for |implicit_change_performed| allows |
| 707 | // overriding the change detection for cases like DDL (CREATE, DROP, etc), |
| 708 | // which do not participate in the total-rows-changed tracking. |
| 709 | void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed); |
| 710 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 711 | // Returns the results of sqlite3_db_filename(), which should match the path |
| 712 | // passed to Open(). |
| 713 | base::FilePath DbPath() const; |
| 714 | |
| 715 | // Helper to prevent uploading too many diagnostic dumps for a given database, |
| 716 | // since every dump will likely show the same problem. Returns |true| if this |
| 717 | // function was not previously called for this database, and the persistent |
| 718 | // storage which tracks state was updated. |
| 719 | // |
| 720 | // |false| is returned if the function was previously called for this |
| 721 | // database, even across restarts. |false| is also returned if the persistent |
| 722 | // storage cannot be updated, possibly indicating problems requiring user or |
| 723 | // admin intervention, such as filesystem corruption or disk full. |false| is |
| 724 | // also returned if the persistent storage contains invalid data or is not |
| 725 | // readable. |
| 726 | // |
| 727 | // TODO(shess): It would make sense to reset the persistent state if the |
| 728 | // database is razed or recovered, or if the diagnostic code adds new |
| 729 | // capabilities. |
| 730 | bool RegisterIntentToUpload() const; |
| 731 | |
| 732 | // Helper to collect diagnostic info for a corrupt database. |
| 733 | std::string CollectCorruptionInfo(); |
| 734 | |
| 735 | // Helper to collect diagnostic info for errors. |
| 736 | std::string CollectErrorInfo(int error, Statement* stmt) const; |
| 737 | |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 738 | // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors |
| 739 | // can make it unsafe to map a file, so the file is read using regular I/O, |
| 740 | // with any errors causing 0 (don't map anything) to be returned. If the |
| 741 | // entire file is read without error, a large value is returned which will |
| 742 | // allow the entire file to be mapped in most cases. |
| 743 | // |
| 744 | // Results are recorded in the database's meta table for future reference, so |
| 745 | // the file should only be read through once. |
| 746 | size_t GetAppropriateMmapSize(); |
| 747 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 748 | // Helpers for GetAppropriateMmapSize(). |
| 749 | bool GetMmapAltStatus(int64_t* status); |
| 750 | bool SetMmapAltStatus(int64_t status); |
| 751 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 752 | // The actual sqlite database. Will be NULL before Init has been called or if |
| 753 | // Init resulted in an error. |
| 754 | sqlite3* db_; |
| 755 | |
| 756 | // Parameters we'll configure in sqlite before doing anything else. Zero means |
| 757 | // use the default value. |
| 758 | int page_size_; |
| 759 | int cache_size_; |
| 760 | bool exclusive_locking_; |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame] | 761 | bool restrict_to_user_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 762 | |
| 763 | // All cached statements. Keeping a reference to these statements means that |
Dmitry Skiba | a9ad8fe4 | 2017-08-16 21:02:48 | [diff] [blame] | 764 | // they'll remain active. Using flat_map here because number of cached |
| 765 | // statements is expected to be small, see //base/containers/README.md. |
| 766 | typedef base::flat_map<StatementID, scoped_refptr<StatementRef>> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 767 | CachedStatementMap; |
| 768 | CachedStatementMap statement_cache_; |
| 769 | |
| 770 | // A list of all StatementRefs we've given out. Each ref must register with |
| 771 | // us when it's created or destroyed. This allows us to potentially close |
| 772 | // any open statements when we encounter an error. |
| 773 | typedef std::set<StatementRef*> StatementRefSet; |
| 774 | StatementRefSet open_statements_; |
| 775 | |
| 776 | // Number of currently-nested transactions. |
| 777 | int transaction_nesting_; |
| 778 | |
| 779 | // True if any of the currently nested transactions have been rolled back. |
| 780 | // When we get to the outermost transaction, this will determine if we do |
| 781 | // a rollback instead of a commit. |
| 782 | bool needs_rollback_; |
| 783 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 784 | // True if database is open with OpenInMemory(), False if database is open |
| 785 | // with Open(). |
| 786 | bool in_memory_; |
| 787 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 788 | // |true| if the connection was closed using RazeAndClose(). Used |
| 789 | // to enable diagnostics to distinguish calls to never-opened |
| 790 | // databases (incorrect use of the API) from calls to once-valid |
| 791 | // databases. |
| 792 | bool poisoned_; |
| 793 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 794 | // |true| to use alternate storage for tracking mmap status. |
| 795 | bool mmap_alt_status_; |
| 796 | |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 797 | // |true| if SQLite memory-mapped I/O is not desired for this connection. |
| 798 | bool mmap_disabled_; |
| 799 | |
| 800 | // |true| if SQLite memory-mapped I/O was enabled for this connection. |
| 801 | // Used by ReleaseCacheMemoryIfNeeded(). |
| 802 | bool mmap_enabled_; |
| 803 | |
| 804 | // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened |
| 805 | // since memory was last released. |
| 806 | int total_changes_at_last_release_; |
| 807 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 808 | ErrorCallback error_callback_; |
| 809 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 810 | // Tag for auxiliary histograms. |
| 811 | std::string histogram_tag_; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 812 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 813 | // Linear histogram for RecordEvent(). |
| 814 | base::HistogramBase* stats_histogram_; |
| 815 | |
| 816 | // Histogram for tracking time taken in commit. |
| 817 | base::HistogramBase* commit_time_histogram_; |
| 818 | |
| 819 | // Histogram for tracking time taken in autocommit updates. |
| 820 | base::HistogramBase* autocommit_time_histogram_; |
| 821 | |
| 822 | // Histogram for tracking time taken in updates (including commit and |
| 823 | // autocommit). |
| 824 | base::HistogramBase* update_time_histogram_; |
| 825 | |
| 826 | // Histogram for tracking time taken in all queries. |
| 827 | base::HistogramBase* query_time_histogram_; |
| 828 | |
| 829 | // Source for timing information, provided to allow tests to inject time |
| 830 | // changes. |
mostynb | d82cd995 | 2016-04-11 20:05:34 | [diff] [blame] | 831 | std::unique_ptr<TimeSource> clock_; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 832 | |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 833 | // Stores the dump provider object when db is open. |
mostynb | d82cd995 | 2016-04-11 20:05:34 | [diff] [blame] | 834 | std::unique_ptr<ConnectionMemoryDumpProvider> memory_dump_provider_; |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 835 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 836 | DISALLOW_COPY_AND_ASSIGN(Connection); |
| 837 | }; |
| 838 | |
| 839 | } // namespace sql |
| 840 | |
[email protected] | f0a54b2 | 2011-07-19 18:40:21 | [diff] [blame] | 841 | #endif // SQL_CONNECTION_H_ |