[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 | |
| 8 | #include <map> |
| 9 | #include <set> |
[email protected] | 7d6aee4e | 2009-09-12 01:12:33 | [diff] [blame] | 10 | #include <string> |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 11 | #include <vector> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 12 | |
| 13 | #include "base/basictypes.h" |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 14 | #include "base/callback.h" |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 15 | #include "base/compiler_specific.h" |
[email protected] | 3b63f8f4 | 2011-03-28 01:54:15 | [diff] [blame] | 16 | #include "base/memory/ref_counted.h" |
[email protected] | 49dc4f2 | 2012-10-17 17:41:16 | [diff] [blame] | 17 | #include "base/memory/scoped_ptr.h" |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 18 | #include "base/threading/thread_restrictions.h" |
[email protected] | 2b59d68 | 2013-06-28 15:22:03 | [diff] [blame] | 19 | #include "base/time/time.h" |
[email protected] | d452696 | 2011-11-10 21:40:28 | [diff] [blame] | 20 | #include "sql/sql_export.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 21 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 22 | struct sqlite3; |
| 23 | struct sqlite3_stmt; |
| 24 | |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 25 | namespace base { |
| 26 | class FilePath; |
| 27 | } |
| 28 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 29 | namespace sql { |
| 30 | |
| 31 | class Statement; |
| 32 | |
| 33 | // Uniquely identifies a statement. There are two modes of operation: |
| 34 | // |
| 35 | // - In the most common mode, you will use the source file and line number to |
| 36 | // identify your statement. This is a convienient way to get uniqueness for |
| 37 | // a statement that is only used in one place. Use the SQL_FROM_HERE macro |
| 38 | // to generate a StatementID. |
| 39 | // |
| 40 | // - In the "custom" mode you may use the statement from different places or |
| 41 | // need to manage it yourself for whatever reason. In this case, you should |
| 42 | // make up your own unique name and pass it to the StatementID. This name |
| 43 | // must be a static string, since this object only deals with pointers and |
| 44 | // assumes the underlying string doesn't change or get deleted. |
| 45 | // |
| 46 | // This object is copyable and assignable using the compiler-generated |
| 47 | // operator= and copy constructor. |
| 48 | class StatementID { |
| 49 | public: |
| 50 | // Creates a uniquely named statement with the given file ane line number. |
| 51 | // Normally you will use SQL_FROM_HERE instead of calling yourself. |
| 52 | StatementID(const char* file, int line) |
| 53 | : number_(line), |
| 54 | str_(file) { |
| 55 | } |
| 56 | |
| 57 | // Creates a uniquely named statement with the given user-defined name. |
| 58 | explicit StatementID(const char* unique_name) |
| 59 | : number_(-1), |
| 60 | str_(unique_name) { |
| 61 | } |
| 62 | |
| 63 | // This constructor is unimplemented and will generate a linker error if |
| 64 | // called. It is intended to try to catch people dynamically generating |
| 65 | // a statement name that will be deallocated and will cause a crash later. |
| 66 | // All strings must be static and unchanging! |
| 67 | explicit StatementID(const std::string& dont_ever_do_this); |
| 68 | |
| 69 | // We need this to insert into our map. |
| 70 | bool operator<(const StatementID& other) const; |
| 71 | |
| 72 | private: |
| 73 | int number_; |
| 74 | const char* str_; |
| 75 | }; |
| 76 | |
| 77 | #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__) |
| 78 | |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 79 | class Connection; |
| 80 | |
[email protected] | d452696 | 2011-11-10 21:40:28 | [diff] [blame] | 81 | class SQL_EXPORT Connection { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 82 | private: |
| 83 | class StatementRef; // Forward declaration, see real one below. |
| 84 | |
| 85 | public: |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 86 | // The database is opened by calling Open[InMemory](). Any uncommitted |
| 87 | // transactions will be rolled back when this object is deleted. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 88 | Connection(); |
| 89 | ~Connection(); |
| 90 | |
| 91 | // Pre-init configuration ---------------------------------------------------- |
| 92 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 93 | // 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] | 94 | // must be called before Init(), and will only have an effect on new |
| 95 | // databases. |
| 96 | // |
| 97 | // From sqlite.org: "The page size must be a power of two greater than or |
| 98 | // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum |
| 99 | // value for SQLITE_MAX_PAGE_SIZE is 32768." |
| 100 | void set_page_size(int page_size) { page_size_ = page_size; } |
| 101 | |
| 102 | // Sets the number of pages that will be cached in memory by sqlite. The |
| 103 | // 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] | 104 | // called before Open() to have an effect. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 105 | void set_cache_size(int cache_size) { cache_size_ = cache_size; } |
| 106 | |
| 107 | // Call to put the database in exclusive locking mode. There is no "back to |
| 108 | // normal" flag because of some additional requirements sqlite puts on this |
| 109 | // transaition (requires another access to the DB) and because we don't |
| 110 | // actually need it. |
| 111 | // |
| 112 | // Exclusive mode means that the database is not unlocked at the end of each |
| 113 | // transaction, which means there may be less time spent initializing the |
| 114 | // next transaction because it doesn't have to re-aquire locks. |
| 115 | // |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 116 | // This must be called before Open() to have an effect. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 117 | void set_exclusive_locking() { exclusive_locking_ = true; } |
| 118 | |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame^] | 119 | // Call to cause Open() to restrict access permissions of the |
| 120 | // database file to only the owner. |
| 121 | // TODO(shess): Currently only supported on OS_POSIX, is a noop on |
| 122 | // other platforms. |
| 123 | void set_restrict_to_user() { restrict_to_user_ = true; } |
| 124 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 125 | // Set an error-handling callback. On errors, the error number (and |
| 126 | // statement, if available) will be passed to the callback. |
| 127 | // |
| 128 | // If no callback is set, the default action is to crash in debug |
| 129 | // mode or return failure in release mode. |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 130 | typedef base::Callback<void(int, Statement*)> ErrorCallback; |
| 131 | void set_error_callback(const ErrorCallback& callback) { |
| 132 | error_callback_ = callback; |
| 133 | } |
[email protected] | 98cf300 | 2013-07-12 01:38:56 | [diff] [blame] | 134 | bool has_error_callback() const { |
| 135 | return !error_callback_.is_null(); |
| 136 | } |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 137 | void reset_error_callback() { |
| 138 | error_callback_.Reset(); |
| 139 | } |
| 140 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 141 | // Set this tag to enable additional connection-type histogramming |
| 142 | // for SQLite error codes and database version numbers. |
| 143 | void set_histogram_tag(const std::string& tag) { |
| 144 | histogram_tag_ = tag; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 145 | } |
| 146 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 147 | // Record a sparse UMA histogram sample under |
| 148 | // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no |
| 149 | // histogram is recorded. |
| 150 | void AddTaggedHistogram(const std::string& name, size_t sample) const; |
| 151 | |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 152 | // Run "PRAGMA integrity_check" and post each line of results into |
| 153 | // |messages|. Returns the success of running the statement - per |
| 154 | // the SQLite documentation, if no errors are found the call should |
| 155 | // succeed, and a single value "ok" should be in messages. |
| 156 | bool IntegrityCheck(std::vector<std::string>* messages); |
| 157 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 158 | // Initialization ------------------------------------------------------------ |
| 159 | |
| 160 | // Initializes the SQL connection for the given file, returning true if the |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 161 | // file could be opened. You can call this or OpenInMemory. |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 162 | bool Open(const base::FilePath& path) WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 163 | |
| 164 | // Initializes the SQL connection for a temporary in-memory database. There |
| 165 | // will be no associated file on disk, and the initial database will be |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 166 | // empty. You can call this or Open. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 167 | bool OpenInMemory() WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 168 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 169 | // Returns true if the database has been successfully opened. |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 170 | bool is_open() const { return !!db_; } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 171 | |
| 172 | // Closes the database. This is automatically performed on destruction for |
| 173 | // you, but this allows you to close the database early. You must not call |
| 174 | // any other functions after closing it. It is permissable to call Close on |
| 175 | // an uninitialized or already-closed database. |
| 176 | void Close(); |
| 177 | |
| 178 | // Pre-loads the first <cache-size> pages into the cache from the file. |
| 179 | // If you expect to soon use a substantial portion of the database, this |
| 180 | // is much more efficient than allowing the pages to be populated organically |
| 181 | // since there is no per-page hard drive seeking. If the file is larger than |
| 182 | // the cache, the last part that doesn't fit in the cache will be brought in |
| 183 | // organically. |
| 184 | // |
| 185 | // This function assumes your class is using a meta table on the current |
| 186 | // database, as it openes a transaction on the meta table to force the |
| 187 | // database to be initialized. You should feel free to initialize the meta |
| 188 | // table after calling preload since the meta table will already be in the |
| 189 | // database if it exists, and if it doesn't exist, the database won't |
| 190 | // generally exist either. |
| 191 | void Preload(); |
| 192 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 193 | // Raze the database to the ground. This approximates creating a |
| 194 | // fresh database from scratch, within the constraints of SQLite's |
| 195 | // locking protocol (locks and open handles can make doing this with |
| 196 | // filesystem operations problematic). Returns true if the database |
| 197 | // was razed. |
| 198 | // |
| 199 | // false is returned if the database is locked by some other |
| 200 | // process. RazeWithTimeout() may be used if appropriate. |
| 201 | // |
| 202 | // NOTE(shess): Raze() will DCHECK in the following situations: |
| 203 | // - database is not open. |
| 204 | // - the connection has a transaction open. |
| 205 | // - a SQLite issue occurs which is structural in nature (like the |
| 206 | // statements used are broken). |
| 207 | // Since Raze() is expected to be called in unexpected situations, |
| 208 | // these all return false, since it is unlikely that the caller |
| 209 | // could fix them. |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 210 | // |
| 211 | // The database's page size is taken from |page_size_|. The |
| 212 | // existing database's |auto_vacuum| setting is lost (the |
| 213 | // possibility of corruption makes it unreliable to pull it from the |
| 214 | // existing database). To re-enable on the empty database requires |
| 215 | // running "PRAGMA auto_vacuum = 1;" then "VACUUM". |
| 216 | // |
| 217 | // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1, |
| 218 | // so Raze() sets auto_vacuum to 1. |
| 219 | // |
| 220 | // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB. |
| 221 | // TODO(shess): Bake auto_vacuum into Connection's API so it can |
| 222 | // just pick up the default. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 223 | bool Raze(); |
| 224 | bool RazeWithTimout(base::TimeDelta timeout); |
| 225 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 226 | // Breaks all outstanding transactions (as initiated by |
| 227 | // BeginTransaction()), calls Raze() to destroy the database, then |
| 228 | // closes the database. After this is called, any operations |
| 229 | // against the connections (or statements prepared by the |
| 230 | // connection) should fail safely. |
| 231 | // |
| 232 | // The value from Raze() is returned, with Close() called in all |
| 233 | // cases. |
| 234 | bool RazeAndClose(); |
| 235 | |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 236 | // Delete the underlying database files associated with |path|. |
| 237 | // This should be used on a database which has no existing |
| 238 | // connections. If any other connections are open to the same |
| 239 | // database, this could cause odd results or corruption (for |
| 240 | // instance if a hot journal is deleted but the associated database |
| 241 | // is not). |
| 242 | // |
| 243 | // Returns true if the database file and associated journals no |
| 244 | // longer exist, false otherwise. If the database has never |
| 245 | // existed, this will return true. |
| 246 | static bool Delete(const base::FilePath& path); |
| 247 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 248 | // Transactions -------------------------------------------------------------- |
| 249 | |
| 250 | // Transaction management. We maintain a virtual transaction stack to emulate |
| 251 | // nested transactions since sqlite can't do nested transactions. The |
| 252 | // limitation is you can't roll back a sub transaction: if any transaction |
| 253 | // fails, all transactions open will also be rolled back. Any nested |
| 254 | // transactions after one has rolled back will return fail for Begin(). If |
| 255 | // Begin() fails, you must not call Commit or Rollback(). |
| 256 | // |
| 257 | // Normally you should use sql::Transaction to manage a transaction, which |
| 258 | // will scope it to a C++ context. |
| 259 | bool BeginTransaction(); |
| 260 | void RollbackTransaction(); |
| 261 | bool CommitTransaction(); |
| 262 | |
| 263 | // Returns the current transaction nesting, which will be 0 if there are |
| 264 | // no open transactions. |
| 265 | int transaction_nesting() const { return transaction_nesting_; } |
| 266 | |
| 267 | // Statements ---------------------------------------------------------------- |
| 268 | |
| 269 | // Executes the given SQL string, returning true on success. This is |
| 270 | // normally used for simple, 1-off statements that don't take any bound |
| 271 | // parameters and don't return any data (e.g. CREATE TABLE). |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 272 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 273 | // This will DCHECK if the |sql| contains errors. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 274 | // |
| 275 | // Do not use ignore_result() to ignore all errors. Use |
| 276 | // ExecuteAndReturnErrorCode() and ignore only specific errors. |
| 277 | bool Execute(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 278 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 279 | // Like Execute(), but returns the error code given by SQLite. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 280 | int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 281 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 282 | // Returns true if we have a statement with the given identifier already |
| 283 | // cached. This is normally not necessary to call, but can be useful if the |
| 284 | // caller has to dynamically build up SQL to avoid doing so if it's already |
| 285 | // cached. |
| 286 | bool HasCachedStatement(const StatementID& id) const; |
| 287 | |
| 288 | // Returns a statement for the given SQL using the statement cache. It can |
| 289 | // take a nontrivial amount of work to parse and compile a statement, so |
| 290 | // keeping commonly-used ones around for future use is important for |
| 291 | // performance. |
| 292 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 293 | // If the |sql| has an error, an invalid, inert StatementRef is returned (and |
| 294 | // the code will crash in debug). The caller must deal with this eventuality, |
| 295 | // either by checking validity of the |sql| before calling, by correctly |
| 296 | // handling the return of an inert statement, or both. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 297 | // |
| 298 | // The StatementID and the SQL must always correspond to one-another. The |
| 299 | // ID is the lookup into the cache, so crazy things will happen if you use |
| 300 | // different SQL with the same ID. |
| 301 | // |
| 302 | // You will normally use the SQL_FROM_HERE macro to generate a statement |
| 303 | // ID associated with the current line of code. This gives uniqueness without |
| 304 | // you having to manage unique names. See StatementID above for more. |
| 305 | // |
| 306 | // Example: |
[email protected] | 3273dce | 2010-01-27 16:08:08 | [diff] [blame] | 307 | // sql::Statement stmt(connection_.GetCachedStatement( |
| 308 | // SQL_FROM_HERE, "SELECT * FROM foo")); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 309 | // if (!stmt) |
| 310 | // return false; // Error creating statement. |
| 311 | scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id, |
| 312 | const char* sql); |
| 313 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 314 | // Used to check a |sql| statement for syntactic validity. If the statement is |
| 315 | // valid SQL, returns true. |
| 316 | bool IsSQLValid(const char* sql); |
| 317 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 318 | // Returns a non-cached statement for the given SQL. Use this for SQL that |
| 319 | // is only executed once or only rarely (there is overhead associated with |
| 320 | // keeping a statement cached). |
| 321 | // |
| 322 | // See GetCachedStatement above for examples and error information. |
| 323 | scoped_refptr<StatementRef> GetUniqueStatement(const char* sql); |
| 324 | |
| 325 | // Info querying ------------------------------------------------------------- |
| 326 | |
| 327 | // Returns true if the given table exists. |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 328 | bool DoesTableExist(const char* table_name) const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 329 | |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 330 | // Returns true if the given index exists. |
| 331 | bool DoesIndexExist(const char* index_name) const; |
| 332 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 333 | // 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] | 334 | bool DoesColumnExist(const char* table_name, const char* column_name) const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 335 | |
| 336 | // Returns sqlite's internal ID for the last inserted row. Valid only |
| 337 | // immediately after an insert. |
| 338 | int64 GetLastInsertRowId() const; |
| 339 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 340 | // Returns sqlite's count of the number of rows modified by the last |
| 341 | // statement executed. Will be 0 if no statement has executed or the database |
| 342 | // is closed. |
| 343 | int GetLastChangeCount() const; |
| 344 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 345 | // Errors -------------------------------------------------------------------- |
| 346 | |
| 347 | // Returns the error code associated with the last sqlite operation. |
| 348 | int GetErrorCode() const; |
| 349 | |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 350 | // Returns the errno associated with GetErrorCode(). See |
| 351 | // SQLITE_LAST_ERRNO in SQLite documentation. |
| 352 | int GetLastErrno() const; |
| 353 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 354 | // Returns a pointer to a statically allocated string associated with the |
| 355 | // last sqlite operation. |
| 356 | const char* GetErrorMessage() const; |
| 357 | |
| 358 | private: |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 359 | // Allow test-support code to set/reset error ignorer. |
| 360 | friend class ScopedErrorIgnorer; |
| 361 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 362 | // Statement accesses StatementRef which we don't want to expose to everybody |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 363 | // (they should go through Statement). |
| 364 | friend class Statement; |
| 365 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 366 | // Internal initialize function used by both Init and InitInMemory. The file |
| 367 | // name is always 8 bits since we want to use the 8-bit version of |
| 368 | // sqlite3_open. The string can also be sqlite's special ":memory:" string. |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 369 | // |
| 370 | // |retry_flag| controls retrying the open if the error callback |
| 371 | // addressed errors using RazeAndClose(). |
| 372 | enum Retry { |
| 373 | NO_RETRY = 0, |
| 374 | RETRY_ON_POISON |
| 375 | }; |
| 376 | bool OpenInternal(const std::string& file_name, Retry retry_flag); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 377 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 378 | // Internal close function used by Close() and RazeAndClose(). |
| 379 | // |forced| indicates that orderly-shutdown checks should not apply. |
| 380 | void CloseInternal(bool forced); |
| 381 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 382 | // Check whether the current thread is allowed to make IO calls, but only |
| 383 | // if database wasn't open in memory. Function is inlined to be a no-op in |
| 384 | // official build. |
| 385 | void AssertIOAllowed() { |
| 386 | if (!in_memory_) |
| 387 | base::ThreadRestrictions::AssertIOAllowed(); |
| 388 | } |
| 389 | |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 390 | // Internal helper for DoesTableExist and DoesIndexExist. |
| 391 | bool DoesTableOrIndexExist(const char* name, const char* type) const; |
| 392 | |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 393 | // Accessors for global error-ignorer, for injecting behavior during tests. |
| 394 | // See test/scoped_error_ignorer.h. |
| 395 | typedef base::Callback<bool(int)> ErrorIgnorerCallback; |
| 396 | static ErrorIgnorerCallback* current_ignorer_cb_; |
| 397 | static bool ShouldIgnore(int error); |
| 398 | static void SetErrorIgnorer(ErrorIgnorerCallback* ignorer); |
| 399 | static void ResetErrorIgnorer(); |
| 400 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 401 | // A StatementRef is a refcounted wrapper around a sqlite statement pointer. |
| 402 | // Refcounting allows us to give these statements out to sql::Statement |
| 403 | // objects while also optionally maintaining a cache of compiled statements |
| 404 | // by just keeping a refptr to these objects. |
| 405 | // |
| 406 | // A statement ref can be valid, in which case it can be used, or invalid to |
| 407 | // indicate that the statement hasn't been created yet, has an error, or has |
| 408 | // been destroyed. |
| 409 | // |
| 410 | // The Connection may revoke a StatementRef in some error cases, so callers |
| 411 | // should always check validity before using. |
[email protected] | 601dc6a | 2011-11-12 01:14:23 | [diff] [blame] | 412 | class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 413 | public: |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 414 | // |connection| is the sql::Connection instance associated with |
| 415 | // the statement, and is used for tracking outstanding statements |
| 416 | // and for error handling. Set to NULL for invalid or untracked |
| 417 | // refs. |stmt| is the actual statement, and should only be NULL |
| 418 | // to create an invalid ref. |was_valid| indicates whether the |
| 419 | // statement should be considered valid for diagnistic purposes. |
| 420 | // |was_valid| can be true for NULL |stmt| if the connection has |
| 421 | // been forcibly closed by an error handler. |
| 422 | StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 423 | |
| 424 | // When true, the statement can be used. |
| 425 | bool is_valid() const { return !!stmt_; } |
| 426 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 427 | // When true, the statement is either currently valid, or was |
| 428 | // previously valid but the connection was forcibly closed. Used |
| 429 | // for diagnostic checks. |
| 430 | bool was_valid() const { return was_valid_; } |
| 431 | |
[email protected] | b4c363b | 2013-01-17 13:11:17 | [diff] [blame] | 432 | // If we've not been linked to a connection, this will be NULL. |
| 433 | // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(), |
| 434 | // which prevents Statement::OnError() from forwarding errors. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 435 | Connection* connection() const { return connection_; } |
| 436 | |
| 437 | // Returns the sqlite statement if any. If the statement is not active, |
| 438 | // this will return NULL. |
| 439 | sqlite3_stmt* stmt() const { return stmt_; } |
| 440 | |
| 441 | // Destroys the compiled statement and marks it NULL. The statement will |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 442 | // no longer be active. |forced| is used to indicate if orderly-shutdown |
| 443 | // checks should apply (see Connection::RazeAndClose()). |
| 444 | void Close(bool forced); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 445 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 446 | // Check whether the current thread is allowed to make IO calls, but only |
| 447 | // if database wasn't open in memory. |
| 448 | void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); } |
| 449 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 450 | private: |
[email protected] | 877d55d | 2009-11-05 21:53:08 | [diff] [blame] | 451 | friend class base::RefCounted<StatementRef>; |
| 452 | |
| 453 | ~StatementRef(); |
| 454 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 455 | Connection* connection_; |
| 456 | sqlite3_stmt* stmt_; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 457 | bool was_valid_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 458 | |
| 459 | DISALLOW_COPY_AND_ASSIGN(StatementRef); |
| 460 | }; |
| 461 | friend class StatementRef; |
| 462 | |
| 463 | // Executes a rollback statement, ignoring all transaction state. Used |
| 464 | // internally in the transaction management code. |
| 465 | void DoRollback(); |
| 466 | |
| 467 | // Called by a StatementRef when it's being created or destroyed. See |
| 468 | // open_statements_ below. |
| 469 | void StatementRefCreated(StatementRef* ref); |
| 470 | void StatementRefDeleted(StatementRef* ref); |
| 471 | |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 472 | // Called by Statement objects when an sqlite function returns an error. |
| 473 | // The return value is the error code reflected back to client code. |
| 474 | int OnSqliteError(int err, Statement* stmt); |
| 475 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 476 | // Like |Execute()|, but retries if the database is locked. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 477 | bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout) |
| 478 | WARN_UNUSED_RESULT; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 479 | |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 480 | // Internal helper for const functions. Like GetUniqueStatement(), |
| 481 | // except the statement is not entered into open_statements_, |
| 482 | // allowing this function to be const. Open statements can block |
| 483 | // closing the database, so only use in cases where the last ref is |
| 484 | // released before close could be called (which should always be the |
| 485 | // case for const functions). |
| 486 | scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const; |
| 487 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 488 | // The actual sqlite database. Will be NULL before Init has been called or if |
| 489 | // Init resulted in an error. |
| 490 | sqlite3* db_; |
| 491 | |
| 492 | // Parameters we'll configure in sqlite before doing anything else. Zero means |
| 493 | // use the default value. |
| 494 | int page_size_; |
| 495 | int cache_size_; |
| 496 | bool exclusive_locking_; |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame^] | 497 | bool restrict_to_user_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 498 | |
| 499 | // All cached statements. Keeping a reference to these statements means that |
| 500 | // they'll remain active. |
| 501 | typedef std::map<StatementID, scoped_refptr<StatementRef> > |
| 502 | CachedStatementMap; |
| 503 | CachedStatementMap statement_cache_; |
| 504 | |
| 505 | // A list of all StatementRefs we've given out. Each ref must register with |
| 506 | // us when it's created or destroyed. This allows us to potentially close |
| 507 | // any open statements when we encounter an error. |
| 508 | typedef std::set<StatementRef*> StatementRefSet; |
| 509 | StatementRefSet open_statements_; |
| 510 | |
| 511 | // Number of currently-nested transactions. |
| 512 | int transaction_nesting_; |
| 513 | |
| 514 | // True if any of the currently nested transactions have been rolled back. |
| 515 | // When we get to the outermost transaction, this will determine if we do |
| 516 | // a rollback instead of a commit. |
| 517 | bool needs_rollback_; |
| 518 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 519 | // True if database is open with OpenInMemory(), False if database is open |
| 520 | // with Open(). |
| 521 | bool in_memory_; |
| 522 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 523 | // |true| if the connection was closed using RazeAndClose(). Used |
| 524 | // to enable diagnostics to distinguish calls to never-opened |
| 525 | // databases (incorrect use of the API) from calls to once-valid |
| 526 | // databases. |
| 527 | bool poisoned_; |
| 528 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 529 | ErrorCallback error_callback_; |
| 530 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 531 | // Tag for auxiliary histograms. |
| 532 | std::string histogram_tag_; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 533 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 534 | DISALLOW_COPY_AND_ASSIGN(Connection); |
| 535 | }; |
| 536 | |
| 537 | } // namespace sql |
| 538 | |
[email protected] | f0a54b2 | 2011-07-19 18:40:21 | [diff] [blame] | 539 | #endif // SQL_CONNECTION_H_ |