blob: 17d11914ae082ad3cfc7effb8cb4e9dbb2268c69 [file] [log] [blame]
[email protected]2eec0a22012-07-24 01:59:581// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f0a54b22011-07-19 18:40:215#ifndef SQL_CONNECTION_H_
6#define SQL_CONNECTION_H_
[email protected]e5ffd0e42009-09-11 21:30:567
tfarina720d4f32015-05-11 22:31:268#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:569#include <map>
10#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3311#include <string>
[email protected]80abf152013-05-22 12:42:4212#include <vector>
[email protected]e5ffd0e42009-09-11 21:30:5613
[email protected]c3881b372013-05-17 08:39:4614#include "base/callback.h"
[email protected]9fe37552011-12-23 17:07:2015#include "base/compiler_specific.h"
tfarina720d4f32015-05-11 22:31:2616#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1517#include "base/memory/ref_counted.h"
[email protected]49dc4f22012-10-17 17:41:1618#include "base/memory/scoped_ptr.h"
[email protected]35f7e5392012-07-27 19:54:5019#include "base/threading/thread_restrictions.h"
[email protected]2b59d682013-06-28 15:22:0320#include "base/time/time.h"
[email protected]d4526962011-11-10 21:40:2821#include "sql/sql_export.h"
[email protected]e5ffd0e42009-09-11 21:30:5622
[email protected]e5ffd0e42009-09-11 21:30:5623struct sqlite3;
24struct sqlite3_stmt;
25
[email protected]a3ef4832013-02-02 05:12:3326namespace base {
27class FilePath;
28}
29
[email protected]e5ffd0e42009-09-11 21:30:5630namespace sql {
31
[email protected]8d409412013-07-19 18:25:3032class Recovery;
[email protected]e5ffd0e42009-09-11 21:30:5633class Statement;
34
35// Uniquely identifies a statement. There are two modes of operation:
36//
37// - In the most common mode, you will use the source file and line number to
38// identify your statement. This is a convienient way to get uniqueness for
39// a statement that is only used in one place. Use the SQL_FROM_HERE macro
40// to generate a StatementID.
41//
42// - In the "custom" mode you may use the statement from different places or
43// need to manage it yourself for whatever reason. In this case, you should
44// make up your own unique name and pass it to the StatementID. This name
45// must be a static string, since this object only deals with pointers and
46// assumes the underlying string doesn't change or get deleted.
47//
48// This object is copyable and assignable using the compiler-generated
49// operator= and copy constructor.
50class StatementID {
51 public:
52 // Creates a uniquely named statement with the given file ane line number.
53 // Normally you will use SQL_FROM_HERE instead of calling yourself.
54 StatementID(const char* file, int line)
55 : number_(line),
56 str_(file) {
57 }
58
59 // Creates a uniquely named statement with the given user-defined name.
60 explicit StatementID(const char* unique_name)
61 : number_(-1),
62 str_(unique_name) {
63 }
64
65 // This constructor is unimplemented and will generate a linker error if
66 // called. It is intended to try to catch people dynamically generating
67 // a statement name that will be deallocated and will cause a crash later.
68 // All strings must be static and unchanging!
69 explicit StatementID(const std::string& dont_ever_do_this);
70
71 // We need this to insert into our map.
72 bool operator<(const StatementID& other) const;
73
74 private:
75 int number_;
76 const char* str_;
77};
78
79#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
80
[email protected]faa604e2009-09-25 22:38:5981class Connection;
82
[email protected]d4526962011-11-10 21:40:2883class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:5684 private:
85 class StatementRef; // Forward declaration, see real one below.
86
87 public:
[email protected]765b44502009-10-02 05:01:4288 // The database is opened by calling Open[InMemory](). Any uncommitted
89 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:5690 Connection();
91 ~Connection();
92
93 // Pre-init configuration ----------------------------------------------------
94
[email protected]765b44502009-10-02 05:01:4295 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:5696 // must be called before Init(), and will only have an effect on new
97 // databases.
98 //
99 // From sqlite.org: "The page size must be a power of two greater than or
100 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
101 // value for SQLITE_MAX_PAGE_SIZE is 32768."
102 void set_page_size(int page_size) { page_size_ = page_size; }
103
104 // Sets the number of pages that will be cached in memory by sqlite. The
105 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42106 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56107 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
108
109 // Call to put the database in exclusive locking mode. There is no "back to
110 // normal" flag because of some additional requirements sqlite puts on this
[email protected]4ab952f2014-04-01 20:18:16111 // transaction (requires another access to the DB) and because we don't
[email protected]e5ffd0e42009-09-11 21:30:56112 // actually need it.
113 //
114 // Exclusive mode means that the database is not unlocked at the end of each
115 // transaction, which means there may be less time spent initializing the
116 // next transaction because it doesn't have to re-aquire locks.
117 //
[email protected]765b44502009-10-02 05:01:42118 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56119 void set_exclusive_locking() { exclusive_locking_ = true; }
120
[email protected]81a2a602013-07-17 19:10:36121 // Call to cause Open() to restrict access permissions of the
122 // database file to only the owner.
123 // TODO(shess): Currently only supported on OS_POSIX, is a noop on
124 // other platforms.
125 void set_restrict_to_user() { restrict_to_user_ = true; }
126
[email protected]c3881b372013-05-17 08:39:46127 // Set an error-handling callback. On errors, the error number (and
128 // statement, if available) will be passed to the callback.
129 //
130 // If no callback is set, the default action is to crash in debug
131 // mode or return failure in release mode.
[email protected]c3881b372013-05-17 08:39:46132 typedef base::Callback<void(int, Statement*)> ErrorCallback;
133 void set_error_callback(const ErrorCallback& callback) {
134 error_callback_ = callback;
135 }
[email protected]98cf3002013-07-12 01:38:56136 bool has_error_callback() const {
137 return !error_callback_.is_null();
138 }
[email protected]c3881b372013-05-17 08:39:46139 void reset_error_callback() {
140 error_callback_.Reset();
141 }
142
[email protected]210ce0af2013-05-15 09:10:39143 // Set this tag to enable additional connection-type histogramming
144 // for SQLite error codes and database version numbers.
145 void set_histogram_tag(const std::string& tag) {
146 histogram_tag_ = tag;
[email protected]c088e3a32013-01-03 23:59:14147 }
148
[email protected]210ce0af2013-05-15 09:10:39149 // Record a sparse UMA histogram sample under
150 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
151 // histogram is recorded.
152 void AddTaggedHistogram(const std::string& name, size_t sample) const;
153
[email protected]579446c2013-12-16 18:36:52154 // Run "PRAGMA integrity_check" and post each line of
155 // results into |messages|. Returns the success of running the
156 // statement - per the SQLite documentation, if no errors are found the
157 // call should succeed, and a single value "ok" should be in messages.
158 bool FullIntegrityCheck(std::vector<std::string>* messages);
159
160 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
161 // interprets the results returning true if the the statement executes
162 // without error and results in a single "ok" value.
163 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42164
[email protected]e5ffd0e42009-09-11 21:30:56165 // Initialization ------------------------------------------------------------
166
167 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55168 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33169 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42170
171 // Initializes the SQL connection for a temporary in-memory database. There
172 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55173 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20174 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42175
[email protected]8d409412013-07-19 18:25:30176 // Create a temporary on-disk database. The database will be
177 // deleted after close. This kind of database is similar to
178 // OpenInMemory() for small databases, but can page to disk if the
179 // database becomes large.
180 bool OpenTemporary() WARN_UNUSED_RESULT;
181
[email protected]41a97c812013-02-07 02:35:38182 // Returns true if the database has been successfully opened.
[email protected]765b44502009-10-02 05:01:42183 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56184
185 // Closes the database. This is automatically performed on destruction for
186 // you, but this allows you to close the database early. You must not call
187 // any other functions after closing it. It is permissable to call Close on
188 // an uninitialized or already-closed database.
189 void Close();
190
[email protected]8ada10f2013-12-21 00:42:34191 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
192 // filesystem cache. This can be more efficient than faulting pages
193 // individually. Since this involves blocking I/O, it should only be used if
194 // the caller will immediately read a substantial amount of data from the
195 // database.
[email protected]e5ffd0e42009-09-11 21:30:56196 //
[email protected]8ada10f2013-12-21 00:42:34197 // TODO(shess): Design a set of histograms or an experiment to inform this
198 // decision. Preloading should almost always improve later performance
199 // numbers for this database simply because it pulls operations forward, but
200 // if the data isn't actually used soon then preloading just slows down
201 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56202 void Preload();
203
[email protected]be7995f12013-07-18 18:49:14204 // Try to trim the cache memory used by the database. If |aggressively| is
205 // true, this function will try to free all of the cache memory it can. If
206 // |aggressively| is false, this function will try to cut cache memory
207 // usage by half.
208 void TrimMemory(bool aggressively);
209
[email protected]8e0c01282012-04-06 19:36:49210 // Raze the database to the ground. This approximates creating a
211 // fresh database from scratch, within the constraints of SQLite's
212 // locking protocol (locks and open handles can make doing this with
213 // filesystem operations problematic). Returns true if the database
214 // was razed.
215 //
216 // false is returned if the database is locked by some other
217 // process. RazeWithTimeout() may be used if appropriate.
218 //
219 // NOTE(shess): Raze() will DCHECK in the following situations:
220 // - database is not open.
221 // - the connection has a transaction open.
222 // - a SQLite issue occurs which is structural in nature (like the
223 // statements used are broken).
224 // Since Raze() is expected to be called in unexpected situations,
225 // these all return false, since it is unlikely that the caller
226 // could fix them.
[email protected]6d42f152012-11-10 00:38:24227 //
228 // The database's page size is taken from |page_size_|. The
229 // existing database's |auto_vacuum| setting is lost (the
230 // possibility of corruption makes it unreliable to pull it from the
231 // existing database). To re-enable on the empty database requires
232 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
233 //
234 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
235 // so Raze() sets auto_vacuum to 1.
236 //
237 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
238 // TODO(shess): Bake auto_vacuum into Connection's API so it can
239 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49240 bool Raze();
241 bool RazeWithTimout(base::TimeDelta timeout);
242
[email protected]41a97c812013-02-07 02:35:38243 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30244 // BeginTransaction()), closes the SQLite database, and poisons the
245 // object so that all future operations against the Connection (or
246 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38247 //
[email protected]8d409412013-07-19 18:25:30248 // This is intended as an alternative to Close() in error callbacks.
249 // Close() should still be called at some point.
250 void Poison();
251
252 // Raze() the database and Poison() the handle. Returns the return
253 // value from Raze().
254 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38255 bool RazeAndClose();
256
[email protected]8d2e39e2013-06-24 05:55:08257 // Delete the underlying database files associated with |path|.
258 // This should be used on a database which has no existing
259 // connections. If any other connections are open to the same
260 // database, this could cause odd results or corruption (for
261 // instance if a hot journal is deleted but the associated database
262 // is not).
263 //
264 // Returns true if the database file and associated journals no
265 // longer exist, false otherwise. If the database has never
266 // existed, this will return true.
267 static bool Delete(const base::FilePath& path);
268
[email protected]e5ffd0e42009-09-11 21:30:56269 // Transactions --------------------------------------------------------------
270
271 // Transaction management. We maintain a virtual transaction stack to emulate
272 // nested transactions since sqlite can't do nested transactions. The
273 // limitation is you can't roll back a sub transaction: if any transaction
274 // fails, all transactions open will also be rolled back. Any nested
275 // transactions after one has rolled back will return fail for Begin(). If
276 // Begin() fails, you must not call Commit or Rollback().
277 //
278 // Normally you should use sql::Transaction to manage a transaction, which
279 // will scope it to a C++ context.
280 bool BeginTransaction();
281 void RollbackTransaction();
282 bool CommitTransaction();
283
[email protected]8d409412013-07-19 18:25:30284 // Rollback all outstanding transactions. Use with care, there may
285 // be scoped transactions on the stack.
286 void RollbackAllTransactions();
287
[email protected]e5ffd0e42009-09-11 21:30:56288 // Returns the current transaction nesting, which will be 0 if there are
289 // no open transactions.
290 int transaction_nesting() const { return transaction_nesting_; }
291
[email protected]8d409412013-07-19 18:25:30292 // Attached databases---------------------------------------------------------
293
294 // SQLite supports attaching multiple database files to a single
295 // handle. Attach the database in |other_db_path| to the current
296 // handle under |attachment_point|. |attachment_point| should only
297 // contain characters from [a-zA-Z0-9_].
298 //
299 // Note that calling attach or detach with an open transaction is an
300 // error.
301 bool AttachDatabase(const base::FilePath& other_db_path,
302 const char* attachment_point);
303 bool DetachDatabase(const char* attachment_point);
304
[email protected]e5ffd0e42009-09-11 21:30:56305 // Statements ----------------------------------------------------------------
306
307 // Executes the given SQL string, returning true on success. This is
308 // normally used for simple, 1-off statements that don't take any bound
309 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20310 //
[email protected]eff1fa522011-12-12 23:50:59311 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20312 //
313 // Do not use ignore_result() to ignore all errors. Use
314 // ExecuteAndReturnErrorCode() and ignore only specific errors.
315 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56316
[email protected]eff1fa522011-12-12 23:50:59317 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20318 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59319
[email protected]e5ffd0e42009-09-11 21:30:56320 // Returns true if we have a statement with the given identifier already
321 // cached. This is normally not necessary to call, but can be useful if the
322 // caller has to dynamically build up SQL to avoid doing so if it's already
323 // cached.
324 bool HasCachedStatement(const StatementID& id) const;
325
326 // Returns a statement for the given SQL using the statement cache. It can
327 // take a nontrivial amount of work to parse and compile a statement, so
328 // keeping commonly-used ones around for future use is important for
329 // performance.
330 //
[email protected]eff1fa522011-12-12 23:50:59331 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
332 // the code will crash in debug). The caller must deal with this eventuality,
333 // either by checking validity of the |sql| before calling, by correctly
334 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56335 //
336 // The StatementID and the SQL must always correspond to one-another. The
337 // ID is the lookup into the cache, so crazy things will happen if you use
338 // different SQL with the same ID.
339 //
340 // You will normally use the SQL_FROM_HERE macro to generate a statement
341 // ID associated with the current line of code. This gives uniqueness without
342 // you having to manage unique names. See StatementID above for more.
343 //
344 // Example:
[email protected]3273dce2010-01-27 16:08:08345 // sql::Statement stmt(connection_.GetCachedStatement(
346 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56347 // if (!stmt)
348 // return false; // Error creating statement.
349 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
350 const char* sql);
351
[email protected]eff1fa522011-12-12 23:50:59352 // Used to check a |sql| statement for syntactic validity. If the statement is
353 // valid SQL, returns true.
354 bool IsSQLValid(const char* sql);
355
[email protected]e5ffd0e42009-09-11 21:30:56356 // Returns a non-cached statement for the given SQL. Use this for SQL that
357 // is only executed once or only rarely (there is overhead associated with
358 // keeping a statement cached).
359 //
360 // See GetCachedStatement above for examples and error information.
361 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
362
363 // Info querying -------------------------------------------------------------
364
shess92a2ab12015-04-09 01:59:47365 // Returns true if the given table (or index) exists. Instead of
366 // test-then-create, callers should almost always prefer "CREATE TABLE IF NOT
367 // EXISTS" or "CREATE INDEX IF NOT EXISTS".
[email protected]765b44502009-10-02 05:01:42368 bool DoesTableExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53369 bool DoesIndexExist(const char* index_name) const;
370
[email protected]e5ffd0e42009-09-11 21:30:56371 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17372 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56373
374 // Returns sqlite's internal ID for the last inserted row. Valid only
375 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26376 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56377
[email protected]1ed78a32009-09-15 20:24:17378 // Returns sqlite's count of the number of rows modified by the last
379 // statement executed. Will be 0 if no statement has executed or the database
380 // is closed.
381 int GetLastChangeCount() const;
382
[email protected]e5ffd0e42009-09-11 21:30:56383 // Errors --------------------------------------------------------------------
384
385 // Returns the error code associated with the last sqlite operation.
386 int GetErrorCode() const;
387
[email protected]767718e52010-09-21 23:18:49388 // Returns the errno associated with GetErrorCode(). See
389 // SQLITE_LAST_ERRNO in SQLite documentation.
390 int GetLastErrno() const;
391
[email protected]e5ffd0e42009-09-11 21:30:56392 // Returns a pointer to a statically allocated string associated with the
393 // last sqlite operation.
394 const char* GetErrorMessage() const;
395
[email protected]92cd00a2013-08-16 11:09:58396 // Return a reproducible representation of the schema equivalent to
397 // running the following statement at a sqlite3 command-line:
398 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
399 std::string GetSchema() const;
400
[email protected]74cdede2013-09-25 05:39:57401 // Clients which provide an error_callback don't see the
402 // error-handling at the end of OnSqliteError(). Expose to allow
403 // those clients to work appropriately with ScopedErrorIgnorer in
404 // tests.
405 static bool ShouldIgnoreSqliteError(int error);
406
[email protected]e5ffd0e42009-09-11 21:30:56407 private:
[email protected]8d409412013-07-19 18:25:30408 // For recovery module.
409 friend class Recovery;
410
[email protected]4350e322013-06-18 22:18:10411 // Allow test-support code to set/reset error ignorer.
412 friend class ScopedErrorIgnorer;
413
[email protected]eff1fa522011-12-12 23:50:59414 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56415 // (they should go through Statement).
416 friend class Statement;
417
[email protected]765b44502009-10-02 05:01:42418 // Internal initialize function used by both Init and InitInMemory. The file
419 // name is always 8 bits since we want to use the 8-bit version of
420 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13421 //
422 // |retry_flag| controls retrying the open if the error callback
423 // addressed errors using RazeAndClose().
424 enum Retry {
425 NO_RETRY = 0,
426 RETRY_ON_POISON
427 };
428 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42429
[email protected]41a97c812013-02-07 02:35:38430 // Internal close function used by Close() and RazeAndClose().
431 // |forced| indicates that orderly-shutdown checks should not apply.
432 void CloseInternal(bool forced);
433
[email protected]35f7e5392012-07-27 19:54:50434 // Check whether the current thread is allowed to make IO calls, but only
435 // if database wasn't open in memory. Function is inlined to be a no-op in
436 // official build.
437 void AssertIOAllowed() {
438 if (!in_memory_)
439 base::ThreadRestrictions::AssertIOAllowed();
440 }
441
[email protected]e2cadec82011-12-13 02:00:53442 // Internal helper for DoesTableExist and DoesIndexExist.
443 bool DoesTableOrIndexExist(const char* name, const char* type) const;
444
[email protected]4350e322013-06-18 22:18:10445 // Accessors for global error-ignorer, for injecting behavior during tests.
446 // See test/scoped_error_ignorer.h.
447 typedef base::Callback<bool(int)> ErrorIgnorerCallback;
448 static ErrorIgnorerCallback* current_ignorer_cb_;
[email protected]4350e322013-06-18 22:18:10449 static void SetErrorIgnorer(ErrorIgnorerCallback* ignorer);
450 static void ResetErrorIgnorer();
451
[email protected]e5ffd0e42009-09-11 21:30:56452 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
453 // Refcounting allows us to give these statements out to sql::Statement
454 // objects while also optionally maintaining a cache of compiled statements
455 // by just keeping a refptr to these objects.
456 //
457 // A statement ref can be valid, in which case it can be used, or invalid to
458 // indicate that the statement hasn't been created yet, has an error, or has
459 // been destroyed.
460 //
461 // The Connection may revoke a StatementRef in some error cases, so callers
462 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23463 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56464 public:
[email protected]41a97c812013-02-07 02:35:38465 // |connection| is the sql::Connection instance associated with
466 // the statement, and is used for tracking outstanding statements
467 // and for error handling. Set to NULL for invalid or untracked
468 // refs. |stmt| is the actual statement, and should only be NULL
469 // to create an invalid ref. |was_valid| indicates whether the
470 // statement should be considered valid for diagnistic purposes.
471 // |was_valid| can be true for NULL |stmt| if the connection has
472 // been forcibly closed by an error handler.
473 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56474
475 // When true, the statement can be used.
476 bool is_valid() const { return !!stmt_; }
477
[email protected]41a97c812013-02-07 02:35:38478 // When true, the statement is either currently valid, or was
479 // previously valid but the connection was forcibly closed. Used
480 // for diagnostic checks.
481 bool was_valid() const { return was_valid_; }
482
[email protected]b4c363b2013-01-17 13:11:17483 // If we've not been linked to a connection, this will be NULL.
484 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
485 // which prevents Statement::OnError() from forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56486 Connection* connection() const { return connection_; }
487
488 // Returns the sqlite statement if any. If the statement is not active,
489 // this will return NULL.
490 sqlite3_stmt* stmt() const { return stmt_; }
491
492 // Destroys the compiled statement and marks it NULL. The statement will
[email protected]41a97c812013-02-07 02:35:38493 // no longer be active. |forced| is used to indicate if orderly-shutdown
494 // checks should apply (see Connection::RazeAndClose()).
495 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56496
[email protected]35f7e5392012-07-27 19:54:50497 // Check whether the current thread is allowed to make IO calls, but only
498 // if database wasn't open in memory.
499 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
500
[email protected]e5ffd0e42009-09-11 21:30:56501 private:
[email protected]877d55d2009-11-05 21:53:08502 friend class base::RefCounted<StatementRef>;
503
504 ~StatementRef();
505
[email protected]e5ffd0e42009-09-11 21:30:56506 Connection* connection_;
507 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38508 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56509
510 DISALLOW_COPY_AND_ASSIGN(StatementRef);
511 };
512 friend class StatementRef;
513
514 // Executes a rollback statement, ignoring all transaction state. Used
515 // internally in the transaction management code.
516 void DoRollback();
517
518 // Called by a StatementRef when it's being created or destroyed. See
519 // open_statements_ below.
520 void StatementRefCreated(StatementRef* ref);
521 void StatementRefDeleted(StatementRef* ref);
522
[email protected]2f496b42013-09-26 18:36:58523 // Called when a sqlite function returns an error, which is passed
524 // as |err|. The return value is the error code to be reflected
525 // back to client code. |stmt| is non-NULL if the error relates to
526 // an sql::Statement instance. |sql| is non-NULL if the error
527 // relates to non-statement sql code (Execute, for instance). Both
528 // can be NULL, but both should never be set.
529 // NOTE(shess): Originally, the return value was intended to allow
530 // error handlers to transparently convert errors into success.
531 // Unfortunately, transactions are not generally restartable, so
532 // this did not work out.
533 int OnSqliteError(int err, Statement* stmt, const char* sql);
[email protected]faa604e2009-09-25 22:38:59534
[email protected]5b96f3772010-09-28 16:30:57535 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20536 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
537 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57538
[email protected]2eec0a22012-07-24 01:59:58539 // Internal helper for const functions. Like GetUniqueStatement(),
540 // except the statement is not entered into open_statements_,
541 // allowing this function to be const. Open statements can block
542 // closing the database, so only use in cases where the last ref is
543 // released before close could be called (which should always be the
544 // case for const functions).
545 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
546
[email protected]579446c2013-12-16 18:36:52547 bool IntegrityCheckHelper(
548 const char* pragma_sql,
549 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
550
[email protected]e5ffd0e42009-09-11 21:30:56551 // The actual sqlite database. Will be NULL before Init has been called or if
552 // Init resulted in an error.
553 sqlite3* db_;
554
555 // Parameters we'll configure in sqlite before doing anything else. Zero means
556 // use the default value.
557 int page_size_;
558 int cache_size_;
559 bool exclusive_locking_;
[email protected]81a2a602013-07-17 19:10:36560 bool restrict_to_user_;
[email protected]e5ffd0e42009-09-11 21:30:56561
562 // All cached statements. Keeping a reference to these statements means that
563 // they'll remain active.
564 typedef std::map<StatementID, scoped_refptr<StatementRef> >
565 CachedStatementMap;
566 CachedStatementMap statement_cache_;
567
568 // A list of all StatementRefs we've given out. Each ref must register with
569 // us when it's created or destroyed. This allows us to potentially close
570 // any open statements when we encounter an error.
571 typedef std::set<StatementRef*> StatementRefSet;
572 StatementRefSet open_statements_;
573
574 // Number of currently-nested transactions.
575 int transaction_nesting_;
576
577 // True if any of the currently nested transactions have been rolled back.
578 // When we get to the outermost transaction, this will determine if we do
579 // a rollback instead of a commit.
580 bool needs_rollback_;
581
[email protected]35f7e5392012-07-27 19:54:50582 // True if database is open with OpenInMemory(), False if database is open
583 // with Open().
584 bool in_memory_;
585
[email protected]41a97c812013-02-07 02:35:38586 // |true| if the connection was closed using RazeAndClose(). Used
587 // to enable diagnostics to distinguish calls to never-opened
588 // databases (incorrect use of the API) from calls to once-valid
589 // databases.
590 bool poisoned_;
591
[email protected]c3881b372013-05-17 08:39:46592 ErrorCallback error_callback_;
593
[email protected]210ce0af2013-05-15 09:10:39594 // Tag for auxiliary histograms.
595 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14596
[email protected]e5ffd0e42009-09-11 21:30:56597 DISALLOW_COPY_AND_ASSIGN(Connection);
598};
599
600} // namespace sql
601
[email protected]f0a54b22011-07-19 18:40:21602#endif // SQL_CONNECTION_H_