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_
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/threading/thread_restrictions.h"
17 #include "base/time.h"
18 #include "sql/sql_export.h"
28 // Uniquely identifies a statement. There are two modes of operation:
30 // - In the most common mode, you will use the source file and line number to
31 // identify your statement. This is a convienient way to get uniqueness for
32 // a statement that is only used in one place. Use the SQL_FROM_HERE macro
33 // to generate a StatementID.
35 // - In the "custom" mode you may use the statement from different places or
36 // need to manage it yourself for whatever reason. In this case, you should
37 // make up your own unique name and pass it to the StatementID. This name
38 // must be a static string, since this object only deals with pointers and
39 // assumes the underlying string doesn't change or get deleted.
41 // This object is copyable and assignable using the compiler-generated
42 // operator= and copy constructor.
45 // Creates a uniquely named statement with the given file ane line number.
46 // Normally you will use SQL_FROM_HERE instead of calling yourself.
47 StatementID(const char* file
, int line
)
52 // Creates a uniquely named statement with the given user-defined name.
53 explicit StatementID(const char* unique_name
)
58 // This constructor is unimplemented and will generate a linker error if
59 // called. It is intended to try to catch people dynamically generating
60 // a statement name that will be deallocated and will cause a crash later.
61 // All strings must be static and unchanging!
62 explicit StatementID(const std::string
& dont_ever_do_this
);
64 // We need this to insert into our map.
65 bool operator<(const StatementID
& other
) const;
72 #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
76 // ErrorDelegate defines the interface to implement error handling and recovery
77 // for sqlite operations. This allows the rest of the classes to return true or
78 // false while the actual error code and causing statement are delivered using
79 // the OnError() callback.
80 // The tipical usage is to centralize the code designed to handle database
81 // corruption, low-level IO errors or locking violations.
82 class SQL_EXPORT ErrorDelegate
{
84 virtual ~ErrorDelegate();
86 // |error| is an sqlite result code as seen in sqlite3.h. |connection| is the
87 // db connection where the error happened and |stmt| is our best guess at the
88 // statement that triggered the error. Do not store these pointers.
90 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
93 // If the error condition has been fixed and the original statement succesfuly
94 // re-tried then returning SQLITE_OK is appropriate; otherwise it is
95 // recommended that you return the original |error| or the appropriate error
97 virtual int OnError(int error
, Connection
* connection
, Statement
* stmt
) = 0;
100 class SQL_EXPORT Connection
{
102 class StatementRef
; // Forward declaration, see real one below.
105 // The database is opened by calling Open[InMemory](). Any uncommitted
106 // transactions will be rolled back when this object is deleted.
110 // Pre-init configuration ----------------------------------------------------
112 // Sets the page size that will be used when creating a new database. This
113 // must be called before Init(), and will only have an effect on new
116 // From sqlite.org: "The page size must be a power of two greater than or
117 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
118 // value for SQLITE_MAX_PAGE_SIZE is 32768."
119 void set_page_size(int page_size
) { page_size_
= page_size
; }
121 // Sets the number of pages that will be cached in memory by sqlite. The
122 // total cache size in bytes will be page_size * cache_size. This must be
123 // called before Open() to have an effect.
124 void set_cache_size(int cache_size
) { cache_size_
= cache_size
; }
126 // Call to put the database in exclusive locking mode. There is no "back to
127 // normal" flag because of some additional requirements sqlite puts on this
128 // transaition (requires another access to the DB) and because we don't
131 // Exclusive mode means that the database is not unlocked at the end of each
132 // transaction, which means there may be less time spent initializing the
133 // next transaction because it doesn't have to re-aquire locks.
135 // This must be called before Open() to have an effect.
136 void set_exclusive_locking() { exclusive_locking_
= true; }
138 // Sets the object that will handle errors. Recomended that it should be set
139 // before calling Open(). If not set, the default is to ignore errors on
140 // release and assert on debug builds.
141 // Takes ownership of |delegate|.
142 void set_error_delegate(ErrorDelegate
* delegate
) {
143 error_delegate_
.reset(delegate
);
146 // SQLite error codes for errors on all connections are logged to
147 // enum histogram "Sqlite.Error". Setting this additionally logs
148 // errors to the histogram |name|.
149 void set_error_histogram_name(const std::string
& name
) {
150 error_histogram_name_
= name
;
153 // Initialization ------------------------------------------------------------
155 // Initializes the SQL connection for the given file, returning true if the
156 // file could be opened. You can call this or OpenInMemory.
157 bool Open(const FilePath
& path
) WARN_UNUSED_RESULT
;
159 // Initializes the SQL connection for a temporary in-memory database. There
160 // will be no associated file on disk, and the initial database will be
161 // empty. You can call this or Open.
162 bool OpenInMemory() WARN_UNUSED_RESULT
;
164 // Returns trie if the database has been successfully opened.
165 bool is_open() const { return !!db_
; }
167 // Closes the database. This is automatically performed on destruction for
168 // you, but this allows you to close the database early. You must not call
169 // any other functions after closing it. It is permissable to call Close on
170 // an uninitialized or already-closed database.
173 // Pre-loads the first <cache-size> pages into the cache from the file.
174 // If you expect to soon use a substantial portion of the database, this
175 // is much more efficient than allowing the pages to be populated organically
176 // since there is no per-page hard drive seeking. If the file is larger than
177 // the cache, the last part that doesn't fit in the cache will be brought in
180 // This function assumes your class is using a meta table on the current
181 // database, as it openes a transaction on the meta table to force the
182 // database to be initialized. You should feel free to initialize the meta
183 // table after calling preload since the meta table will already be in the
184 // database if it exists, and if it doesn't exist, the database won't
185 // generally exist either.
188 // Raze the database to the ground. This approximates creating a
189 // fresh database from scratch, within the constraints of SQLite's
190 // locking protocol (locks and open handles can make doing this with
191 // filesystem operations problematic). Returns true if the database
194 // false is returned if the database is locked by some other
195 // process. RazeWithTimeout() may be used if appropriate.
197 // NOTE(shess): Raze() will DCHECK in the following situations:
198 // - database is not open.
199 // - the connection has a transaction open.
200 // - a SQLite issue occurs which is structural in nature (like the
201 // statements used are broken).
202 // Since Raze() is expected to be called in unexpected situations,
203 // these all return false, since it is unlikely that the caller
206 // The database's page size is taken from |page_size_|. The
207 // existing database's |auto_vacuum| setting is lost (the
208 // possibility of corruption makes it unreliable to pull it from the
209 // existing database). To re-enable on the empty database requires
210 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
212 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
213 // so Raze() sets auto_vacuum to 1.
215 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
216 // TODO(shess): Bake auto_vacuum into Connection's API so it can
217 // just pick up the default.
219 bool RazeWithTimout(base::TimeDelta timeout
);
221 // Transactions --------------------------------------------------------------
223 // Transaction management. We maintain a virtual transaction stack to emulate
224 // nested transactions since sqlite can't do nested transactions. The
225 // limitation is you can't roll back a sub transaction: if any transaction
226 // fails, all transactions open will also be rolled back. Any nested
227 // transactions after one has rolled back will return fail for Begin(). If
228 // Begin() fails, you must not call Commit or Rollback().
230 // Normally you should use sql::Transaction to manage a transaction, which
231 // will scope it to a C++ context.
232 bool BeginTransaction();
233 void RollbackTransaction();
234 bool CommitTransaction();
236 // Returns the current transaction nesting, which will be 0 if there are
237 // no open transactions.
238 int transaction_nesting() const { return transaction_nesting_
; }
240 // Statements ----------------------------------------------------------------
242 // Executes the given SQL string, returning true on success. This is
243 // normally used for simple, 1-off statements that don't take any bound
244 // parameters and don't return any data (e.g. CREATE TABLE).
246 // This will DCHECK if the |sql| contains errors.
248 // Do not use ignore_result() to ignore all errors. Use
249 // ExecuteAndReturnErrorCode() and ignore only specific errors.
250 bool Execute(const char* sql
) WARN_UNUSED_RESULT
;
252 // Like Execute(), but returns the error code given by SQLite.
253 int ExecuteAndReturnErrorCode(const char* sql
) WARN_UNUSED_RESULT
;
255 // Returns true if we have a statement with the given identifier already
256 // cached. This is normally not necessary to call, but can be useful if the
257 // caller has to dynamically build up SQL to avoid doing so if it's already
259 bool HasCachedStatement(const StatementID
& id
) const;
261 // Returns a statement for the given SQL using the statement cache. It can
262 // take a nontrivial amount of work to parse and compile a statement, so
263 // keeping commonly-used ones around for future use is important for
266 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
267 // the code will crash in debug). The caller must deal with this eventuality,
268 // either by checking validity of the |sql| before calling, by correctly
269 // handling the return of an inert statement, or both.
271 // The StatementID and the SQL must always correspond to one-another. The
272 // ID is the lookup into the cache, so crazy things will happen if you use
273 // different SQL with the same ID.
275 // You will normally use the SQL_FROM_HERE macro to generate a statement
276 // ID associated with the current line of code. This gives uniqueness without
277 // you having to manage unique names. See StatementID above for more.
280 // sql::Statement stmt(connection_.GetCachedStatement(
281 // SQL_FROM_HERE, "SELECT * FROM foo"));
283 // return false; // Error creating statement.
284 scoped_refptr
<StatementRef
> GetCachedStatement(const StatementID
& id
,
287 // Used to check a |sql| statement for syntactic validity. If the statement is
288 // valid SQL, returns true.
289 bool IsSQLValid(const char* sql
);
291 // Returns a non-cached statement for the given SQL. Use this for SQL that
292 // is only executed once or only rarely (there is overhead associated with
293 // keeping a statement cached).
295 // See GetCachedStatement above for examples and error information.
296 scoped_refptr
<StatementRef
> GetUniqueStatement(const char* sql
);
298 // Info querying -------------------------------------------------------------
300 // Returns true if the given table exists.
301 bool DoesTableExist(const char* table_name
) const;
303 // Returns true if the given index exists.
304 bool DoesIndexExist(const char* index_name
) const;
306 // Returns true if a column with the given name exists in the given table.
307 bool DoesColumnExist(const char* table_name
, const char* column_name
) const;
309 // Returns sqlite's internal ID for the last inserted row. Valid only
310 // immediately after an insert.
311 int64
GetLastInsertRowId() const;
313 // Returns sqlite's count of the number of rows modified by the last
314 // statement executed. Will be 0 if no statement has executed or the database
316 int GetLastChangeCount() const;
318 // Errors --------------------------------------------------------------------
320 // Returns the error code associated with the last sqlite operation.
321 int GetErrorCode() const;
323 // Returns the errno associated with GetErrorCode(). See
324 // SQLITE_LAST_ERRNO in SQLite documentation.
325 int GetLastErrno() const;
327 // Returns a pointer to a statically allocated string associated with the
328 // last sqlite operation.
329 const char* GetErrorMessage() const;
332 // Statement accesses StatementRef which we don't want to expose to everybody
333 // (they should go through Statement).
334 friend class Statement
;
336 // Internal initialize function used by both Init and InitInMemory. The file
337 // name is always 8 bits since we want to use the 8-bit version of
338 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
339 bool OpenInternal(const std::string
& file_name
);
341 // Check whether the current thread is allowed to make IO calls, but only
342 // if database wasn't open in memory. Function is inlined to be a no-op in
344 void AssertIOAllowed() {
346 base::ThreadRestrictions::AssertIOAllowed();
349 // Internal helper for DoesTableExist and DoesIndexExist.
350 bool DoesTableOrIndexExist(const char* name
, const char* type
) const;
352 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
353 // Refcounting allows us to give these statements out to sql::Statement
354 // objects while also optionally maintaining a cache of compiled statements
355 // by just keeping a refptr to these objects.
357 // A statement ref can be valid, in which case it can be used, or invalid to
358 // indicate that the statement hasn't been created yet, has an error, or has
361 // The Connection may revoke a StatementRef in some error cases, so callers
362 // should always check validity before using.
363 class SQL_EXPORT StatementRef
: public base::RefCounted
<StatementRef
> {
365 // Default constructor initializes to an invalid statement.
367 explicit StatementRef(sqlite3_stmt
* stmt
);
368 StatementRef(Connection
* connection
, sqlite3_stmt
* stmt
);
370 // When true, the statement can be used.
371 bool is_valid() const { return !!stmt_
; }
373 // If we've not been linked to a connection, this will be NULL.
374 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
375 // which prevents Statement::OnError() from forwarding errors.
376 Connection
* connection() const { return connection_
; }
378 // Returns the sqlite statement if any. If the statement is not active,
379 // this will return NULL.
380 sqlite3_stmt
* stmt() const { return stmt_
; }
382 // Destroys the compiled statement and marks it NULL. The statement will
383 // no longer be active.
386 // Check whether the current thread is allowed to make IO calls, but only
387 // if database wasn't open in memory.
388 void AssertIOAllowed() { if (connection_
) connection_
->AssertIOAllowed(); }
391 friend class base::RefCounted
<StatementRef
>;
395 Connection
* connection_
;
398 DISALLOW_COPY_AND_ASSIGN(StatementRef
);
400 friend class StatementRef
;
402 // Executes a rollback statement, ignoring all transaction state. Used
403 // internally in the transaction management code.
406 // Called by a StatementRef when it's being created or destroyed. See
407 // open_statements_ below.
408 void StatementRefCreated(StatementRef
* ref
);
409 void StatementRefDeleted(StatementRef
* ref
);
411 // Frees all cached statements from statement_cache_.
414 // Called by Statement objects when an sqlite function returns an error.
415 // The return value is the error code reflected back to client code.
416 int OnSqliteError(int err
, Statement
* stmt
);
418 // Like |Execute()|, but retries if the database is locked.
419 bool ExecuteWithTimeout(const char* sql
, base::TimeDelta ms_timeout
)
422 // Internal helper for const functions. Like GetUniqueStatement(),
423 // except the statement is not entered into open_statements_,
424 // allowing this function to be const. Open statements can block
425 // closing the database, so only use in cases where the last ref is
426 // released before close could be called (which should always be the
427 // case for const functions).
428 scoped_refptr
<StatementRef
> GetUntrackedStatement(const char* sql
) const;
430 // The actual sqlite database. Will be NULL before Init has been called or if
431 // Init resulted in an error.
434 // Parameters we'll configure in sqlite before doing anything else. Zero means
435 // use the default value.
438 bool exclusive_locking_
;
440 // All cached statements. Keeping a reference to these statements means that
441 // they'll remain active.
442 typedef std::map
<StatementID
, scoped_refptr
<StatementRef
> >
444 CachedStatementMap statement_cache_
;
446 // A list of all StatementRefs we've given out. Each ref must register with
447 // us when it's created or destroyed. This allows us to potentially close
448 // any open statements when we encounter an error.
449 typedef std::set
<StatementRef
*> StatementRefSet
;
450 StatementRefSet open_statements_
;
452 // Number of currently-nested transactions.
453 int transaction_nesting_
;
455 // True if any of the currently nested transactions have been rolled back.
456 // When we get to the outermost transaction, this will determine if we do
457 // a rollback instead of a commit.
458 bool needs_rollback_
;
460 // True if database is open with OpenInMemory(), False if database is open
464 // This object handles errors resulting from all forms of executing sqlite
465 // commands or statements. It can be null which means default handling.
466 scoped_ptr
<ErrorDelegate
> error_delegate_
;
468 // Auxiliary error-code histogram.
469 std::string error_histogram_name_
;
471 DISALLOW_COPY_AND_ASSIGN(Connection
);
476 #endif // SQL_CONNECTION_H_