1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef SQL_CONNECTION_H_
6 #define SQL_CONNECTION_H_
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/macros.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/time/time.h"
21 #include "sql/sql_export.h"
35 // Uniquely identifies a statement. There are two modes of operation:
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.
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.
48 // This object is copyable and assignable using the compiler-generated
49 // operator= and copy constructor.
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
)
59 // Creates a uniquely named statement with the given user-defined name.
60 explicit StatementID(const char* unique_name
)
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
);
71 // We need this to insert into our map.
72 bool operator<(const StatementID
& other
) const;
79 #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
83 class SQL_EXPORT Connection
{
85 class StatementRef
; // Forward declaration, see real one below.
88 // The database is opened by calling Open[InMemory](). Any uncommitted
89 // transactions will be rolled back when this object is deleted.
93 // Pre-init configuration ----------------------------------------------------
95 // Sets the page size that will be used when creating a new database. This
96 // must be called before Init(), and will only have an effect on new
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
; }
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
106 // called before Open() to have an effect.
107 void set_cache_size(int cache_size
) { cache_size_
= cache_size
; }
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
111 // transaction (requires another access to the DB) and because we don't
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.
118 // This must be called before Open() to have an effect.
119 void set_exclusive_locking() { exclusive_locking_
= true; }
121 // 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
125 void set_restrict_to_user() { restrict_to_user_
= true; }
127 // Set an error-handling callback. On errors, the error number (and
128 // statement, if available) will be passed to the callback.
130 // If no callback is set, the default action is to crash in debug
131 // mode or return failure in release mode.
132 typedef base::Callback
<void(int, Statement
*)> ErrorCallback
;
133 void set_error_callback(const ErrorCallback
& callback
) {
134 error_callback_
= callback
;
136 bool has_error_callback() const {
137 return !error_callback_
.is_null();
139 void reset_error_callback() {
140 error_callback_
.Reset();
143 // 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
;
149 // 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;
154 // 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
);
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
;
165 // Initialization ------------------------------------------------------------
167 // Initializes the SQL connection for the given file, returning true if the
168 // file could be opened. You can call this or OpenInMemory.
169 bool Open(const base::FilePath
& path
) WARN_UNUSED_RESULT
;
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
173 // empty. You can call this or Open.
174 bool OpenInMemory() WARN_UNUSED_RESULT
;
176 // 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
;
182 // Returns true if the database has been successfully opened.
183 bool is_open() const { return !!db_
; }
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.
191 // 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
197 // 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
204 // 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
208 void TrimMemory(bool aggressively
);
210 // 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
216 // false is returned if the database is locked by some other
217 // process. RazeWithTimeout() may be used if appropriate.
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
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".
234 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
235 // so Raze() sets auto_vacuum to 1.
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.
241 bool RazeWithTimout(base::TimeDelta timeout
);
243 // Breaks all outstanding transactions (as initiated by
244 // 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.
248 // This is intended as an alternative to Close() in error callbacks.
249 // Close() should still be called at some point.
252 // Raze() the database and Poison() the handle. Returns the return
253 // value from Raze().
254 // TODO(shess): Rename to RazeAndPoison().
257 // 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
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
);
269 // Transactions --------------------------------------------------------------
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().
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();
284 // Rollback all outstanding transactions. Use with care, there may
285 // be scoped transactions on the stack.
286 void RollbackAllTransactions();
288 // Returns the current transaction nesting, which will be 0 if there are
289 // no open transactions.
290 int transaction_nesting() const { return transaction_nesting_
; }
292 // Attached databases---------------------------------------------------------
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_].
299 // Note that calling attach or detach with an open transaction is an
301 bool AttachDatabase(const base::FilePath
& other_db_path
,
302 const char* attachment_point
);
303 bool DetachDatabase(const char* attachment_point
);
305 // Statements ----------------------------------------------------------------
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).
311 // This will DCHECK if the |sql| contains errors.
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
;
317 // Like Execute(), but returns the error code given by SQLite.
318 int ExecuteAndReturnErrorCode(const char* sql
) WARN_UNUSED_RESULT
;
320 // 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
324 bool HasCachedStatement(const StatementID
& id
) const;
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
331 // 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.
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.
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.
345 // sql::Statement stmt(connection_.GetCachedStatement(
346 // SQL_FROM_HERE, "SELECT * FROM foo"));
348 // return false; // Error creating statement.
349 scoped_refptr
<StatementRef
> GetCachedStatement(const StatementID
& id
,
352 // Used to check a |sql| statement for syntactic validity. If the statement is
353 // valid SQL, returns true.
354 bool IsSQLValid(const char* sql
);
356 // 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).
360 // See GetCachedStatement above for examples and error information.
361 scoped_refptr
<StatementRef
> GetUniqueStatement(const char* sql
);
363 // Info querying -------------------------------------------------------------
365 // 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".
368 bool DoesTableExist(const char* table_name
) const;
369 bool DoesIndexExist(const char* index_name
) const;
371 // Returns true if a column with the given name exists in the given table.
372 bool DoesColumnExist(const char* table_name
, const char* column_name
) const;
374 // Returns sqlite's internal ID for the last inserted row. Valid only
375 // immediately after an insert.
376 int64_t GetLastInsertRowId() const;
378 // 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
381 int GetLastChangeCount() const;
383 // Errors --------------------------------------------------------------------
385 // Returns the error code associated with the last sqlite operation.
386 int GetErrorCode() const;
388 // Returns the errno associated with GetErrorCode(). See
389 // SQLITE_LAST_ERRNO in SQLite documentation.
390 int GetLastErrno() const;
392 // Returns a pointer to a statically allocated string associated with the
393 // last sqlite operation.
394 const char* GetErrorMessage() const;
396 // 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;
401 // 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
405 static bool ShouldIgnoreSqliteError(int error
);
408 // For recovery module.
409 friend class Recovery
;
411 // Allow test-support code to set/reset error ignorer.
412 friend class ScopedErrorIgnorer
;
414 // Statement accesses StatementRef which we don't want to expose to everybody
415 // (they should go through Statement).
416 friend class Statement
;
418 // 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.
422 // |retry_flag| controls retrying the open if the error callback
423 // addressed errors using RazeAndClose().
428 bool OpenInternal(const std::string
& file_name
, Retry retry_flag
);
430 // Internal close function used by Close() and RazeAndClose().
431 // |forced| indicates that orderly-shutdown checks should not apply.
432 void CloseInternal(bool forced
);
434 // 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
437 void AssertIOAllowed() {
439 base::ThreadRestrictions::AssertIOAllowed();
442 // Internal helper for DoesTableExist and DoesIndexExist.
443 bool DoesTableOrIndexExist(const char* name
, const char* type
) const;
445 // 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_
;
449 static void SetErrorIgnorer(ErrorIgnorerCallback
* ignorer
);
450 static void ResetErrorIgnorer();
452 // 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.
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
461 // The Connection may revoke a StatementRef in some error cases, so callers
462 // should always check validity before using.
463 class SQL_EXPORT StatementRef
: public base::RefCounted
<StatementRef
> {
465 // |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
);
475 // When true, the statement can be used.
476 bool is_valid() const { return !!stmt_
; }
478 // 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_
; }
483 // 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.
486 Connection
* connection() const { return connection_
; }
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_
; }
492 // Destroys the compiled statement and marks it NULL. The statement will
493 // no longer be active. |forced| is used to indicate if orderly-shutdown
494 // checks should apply (see Connection::RazeAndClose()).
495 void Close(bool forced
);
497 // 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(); }
502 friend class base::RefCounted
<StatementRef
>;
506 Connection
* connection_
;
510 DISALLOW_COPY_AND_ASSIGN(StatementRef
);
512 friend class StatementRef
;
514 // Executes a rollback statement, ignoring all transaction state. Used
515 // internally in the transaction management code.
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
);
523 // 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
);
535 // Like |Execute()|, but retries if the database is locked.
536 bool ExecuteWithTimeout(const char* sql
, base::TimeDelta ms_timeout
)
539 // 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;
547 bool IntegrityCheckHelper(
548 const char* pragma_sql
,
549 std::vector
<std::string
>* messages
) WARN_UNUSED_RESULT
;
551 // The actual sqlite database. Will be NULL before Init has been called or if
552 // Init resulted in an error.
555 // Parameters we'll configure in sqlite before doing anything else. Zero means
556 // use the default value.
559 bool exclusive_locking_
;
560 bool restrict_to_user_
;
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
> >
566 CachedStatementMap statement_cache_
;
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_
;
574 // Number of currently-nested transactions.
575 int transaction_nesting_
;
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_
;
582 // True if database is open with OpenInMemory(), False if database is open
586 // |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
592 ErrorCallback error_callback_
;
594 // Tag for auxiliary histograms.
595 std::string histogram_tag_
;
597 DISALLOW_COPY_AND_ASSIGN(Connection
);
602 #endif // SQL_CONNECTION_H_