1 // Copyright (c) 2011 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_
13 #include "base/basictypes.h"
14 #include "base/compiler_specific.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/time.h"
17 #include "sql/sql_export.h"
27 // Uniquely identifies a statement. There are two modes of operation:
29 // - In the most common mode, you will use the source file and line number to
30 // identify your statement. This is a convienient way to get uniqueness for
31 // a statement that is only used in one place. Use the SQL_FROM_HERE macro
32 // to generate a StatementID.
34 // - In the "custom" mode you may use the statement from different places or
35 // need to manage it yourself for whatever reason. In this case, you should
36 // make up your own unique name and pass it to the StatementID. This name
37 // must be a static string, since this object only deals with pointers and
38 // assumes the underlying string doesn't change or get deleted.
40 // This object is copyable and assignable using the compiler-generated
41 // operator= and copy constructor.
44 // Creates a uniquely named statement with the given file ane line number.
45 // Normally you will use SQL_FROM_HERE instead of calling yourself.
46 StatementID(const char* file
, int line
)
51 // Creates a uniquely named statement with the given user-defined name.
52 explicit StatementID(const char* unique_name
)
57 // This constructor is unimplemented and will generate a linker error if
58 // called. It is intended to try to catch people dynamically generating
59 // a statement name that will be deallocated and will cause a crash later.
60 // All strings must be static and unchanging!
61 explicit StatementID(const std::string
& dont_ever_do_this
);
63 // We need this to insert into our map.
64 bool operator<(const StatementID
& other
) const;
71 #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
75 // ErrorDelegate defines the interface to implement error handling and recovery
76 // for sqlite operations. This allows the rest of the classes to return true or
77 // false while the actual error code and causing statement are delivered using
78 // the OnError() callback.
79 // The tipical usage is to centralize the code designed to handle database
80 // corruption, low-level IO errors or locking violations.
81 class SQL_EXPORT ErrorDelegate
: public base::RefCounted
<ErrorDelegate
> {
85 // |error| is an sqlite result code as seen in sqlite\preprocessed\sqlite3.h
86 // |connection| is db connection where the error happened and |stmt| is
87 // our best guess at the statement that triggered the error. Do not store
90 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
93 // If the error condition has been fixed an the original statement succesfuly
94 // re-tried then returning SQLITE_OK is appropiate; otherwise is recomended
95 // that you return the original |error| or the appropiae error code.
96 virtual int OnError(int error
, Connection
* connection
, Statement
* stmt
) = 0;
99 friend class base::RefCounted
<ErrorDelegate
>;
101 virtual ~ErrorDelegate();
104 class SQL_EXPORT Connection
{
106 class StatementRef
; // Forward declaration, see real one below.
109 // The database is opened by calling Open[InMemory](). Any uncommitted
110 // transactions will be rolled back when this object is deleted.
114 // Pre-init configuration ----------------------------------------------------
116 // Sets the page size that will be used when creating a new database. This
117 // must be called before Init(), and will only have an effect on new
120 // From sqlite.org: "The page size must be a power of two greater than or
121 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
122 // value for SQLITE_MAX_PAGE_SIZE is 32768."
123 void set_page_size(int page_size
) { page_size_
= page_size
; }
125 // Sets the number of pages that will be cached in memory by sqlite. The
126 // total cache size in bytes will be page_size * cache_size. This must be
127 // called before Open() to have an effect.
128 void set_cache_size(int cache_size
) { cache_size_
= cache_size
; }
130 // Call to put the database in exclusive locking mode. There is no "back to
131 // normal" flag because of some additional requirements sqlite puts on this
132 // transaition (requires another access to the DB) and because we don't
135 // Exclusive mode means that the database is not unlocked at the end of each
136 // transaction, which means there may be less time spent initializing the
137 // next transaction because it doesn't have to re-aquire locks.
139 // This must be called before Open() to have an effect.
140 void set_exclusive_locking() { exclusive_locking_
= true; }
142 // Sets the object that will handle errors. Recomended that it should be set
143 // before calling Open(). If not set, the default is to ignore errors on
144 // release and assert on debug builds.
145 void set_error_delegate(ErrorDelegate
* delegate
) {
146 error_delegate_
= delegate
;
149 // Initialization ------------------------------------------------------------
151 // Initializes the SQL connection for the given file, returning true if the
152 // file could be opened. You can call this or OpenInMemory.
153 bool Open(const FilePath
& path
) WARN_UNUSED_RESULT
;
155 // Initializes the SQL connection for a temporary in-memory database. There
156 // will be no associated file on disk, and the initial database will be
157 // empty. You can call this or Open.
158 bool OpenInMemory() WARN_UNUSED_RESULT
;
160 // Returns trie if the database has been successfully opened.
161 bool is_open() const { return !!db_
; }
163 // Closes the database. This is automatically performed on destruction for
164 // you, but this allows you to close the database early. You must not call
165 // any other functions after closing it. It is permissable to call Close on
166 // an uninitialized or already-closed database.
169 // Pre-loads the first <cache-size> pages into the cache from the file.
170 // If you expect to soon use a substantial portion of the database, this
171 // is much more efficient than allowing the pages to be populated organically
172 // since there is no per-page hard drive seeking. If the file is larger than
173 // the cache, the last part that doesn't fit in the cache will be brought in
176 // This function assumes your class is using a meta table on the current
177 // database, as it openes a transaction on the meta table to force the
178 // database to be initialized. You should feel free to initialize the meta
179 // table after calling preload since the meta table will already be in the
180 // database if it exists, and if it doesn't exist, the database won't
181 // generally exist either.
184 // Raze the database to the ground. This approximates creating a
185 // fresh database from scratch, within the constraints of SQLite's
186 // locking protocol (locks and open handles can make doing this with
187 // filesystem operations problematic). Returns true if the database
190 // false is returned if the database is locked by some other
191 // process. RazeWithTimeout() may be used if appropriate.
193 // NOTE(shess): Raze() will DCHECK in the following situations:
194 // - database is not open.
195 // - the connection has a transaction open.
196 // - a SQLite issue occurs which is structural in nature (like the
197 // statements used are broken).
198 // Since Raze() is expected to be called in unexpected situations,
199 // these all return false, since it is unlikely that the caller
202 bool RazeWithTimout(base::TimeDelta timeout
);
204 // Transactions --------------------------------------------------------------
206 // Transaction management. We maintain a virtual transaction stack to emulate
207 // nested transactions since sqlite can't do nested transactions. The
208 // limitation is you can't roll back a sub transaction: if any transaction
209 // fails, all transactions open will also be rolled back. Any nested
210 // transactions after one has rolled back will return fail for Begin(). If
211 // Begin() fails, you must not call Commit or Rollback().
213 // Normally you should use sql::Transaction to manage a transaction, which
214 // will scope it to a C++ context.
215 bool BeginTransaction();
216 void RollbackTransaction();
217 bool CommitTransaction();
219 // Returns the current transaction nesting, which will be 0 if there are
220 // no open transactions.
221 int transaction_nesting() const { return transaction_nesting_
; }
223 // Statements ----------------------------------------------------------------
225 // Executes the given SQL string, returning true on success. This is
226 // normally used for simple, 1-off statements that don't take any bound
227 // parameters and don't return any data (e.g. CREATE TABLE).
229 // This will DCHECK if the |sql| contains errors.
231 // Do not use ignore_result() to ignore all errors. Use
232 // ExecuteAndReturnErrorCode() and ignore only specific errors.
233 bool Execute(const char* sql
) WARN_UNUSED_RESULT
;
235 // Like Execute(), but returns the error code given by SQLite.
236 int ExecuteAndReturnErrorCode(const char* sql
) WARN_UNUSED_RESULT
;
238 // Returns true if we have a statement with the given identifier already
239 // cached. This is normally not necessary to call, but can be useful if the
240 // caller has to dynamically build up SQL to avoid doing so if it's already
242 bool HasCachedStatement(const StatementID
& id
) const;
244 // Returns a statement for the given SQL using the statement cache. It can
245 // take a nontrivial amount of work to parse and compile a statement, so
246 // keeping commonly-used ones around for future use is important for
249 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
250 // the code will crash in debug). The caller must deal with this eventuality,
251 // either by checking validity of the |sql| before calling, by correctly
252 // handling the return of an inert statement, or both.
254 // The StatementID and the SQL must always correspond to one-another. The
255 // ID is the lookup into the cache, so crazy things will happen if you use
256 // different SQL with the same ID.
258 // You will normally use the SQL_FROM_HERE macro to generate a statement
259 // ID associated with the current line of code. This gives uniqueness without
260 // you having to manage unique names. See StatementID above for more.
263 // sql::Statement stmt(connection_.GetCachedStatement(
264 // SQL_FROM_HERE, "SELECT * FROM foo"));
266 // return false; // Error creating statement.
267 scoped_refptr
<StatementRef
> GetCachedStatement(const StatementID
& id
,
270 // Used to check a |sql| statement for syntactic validity. If the statement is
271 // valid SQL, returns true.
272 bool IsSQLValid(const char* sql
);
274 // Returns a non-cached statement for the given SQL. Use this for SQL that
275 // is only executed once or only rarely (there is overhead associated with
276 // keeping a statement cached).
278 // See GetCachedStatement above for examples and error information.
279 scoped_refptr
<StatementRef
> GetUniqueStatement(const char* sql
);
281 // Info querying -------------------------------------------------------------
283 // Returns true if the given table exists.
284 bool DoesTableExist(const char* table_name
) const;
286 // Returns true if the given index exists.
287 bool DoesIndexExist(const char* index_name
) const;
289 // Returns true if a column with the given name exists in the given table.
290 bool DoesColumnExist(const char* table_name
, const char* column_name
) const;
292 // Returns sqlite's internal ID for the last inserted row. Valid only
293 // immediately after an insert.
294 int64
GetLastInsertRowId() const;
296 // Returns sqlite's count of the number of rows modified by the last
297 // statement executed. Will be 0 if no statement has executed or the database
299 int GetLastChangeCount() const;
301 // Errors --------------------------------------------------------------------
303 // Returns the error code associated with the last sqlite operation.
304 int GetErrorCode() const;
306 // Returns the errno associated with GetErrorCode(). See
307 // SQLITE_LAST_ERRNO in SQLite documentation.
308 int GetLastErrno() const;
310 // Returns a pointer to a statically allocated string associated with the
311 // last sqlite operation.
312 const char* GetErrorMessage() const;
315 // Statement accesses StatementRef which we don't want to expose to everybody
316 // (they should go through Statement).
317 friend class Statement
;
319 // Internal initialize function used by both Init and InitInMemory. The file
320 // name is always 8 bits since we want to use the 8-bit version of
321 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
322 bool OpenInternal(const std::string
& file_name
);
324 // Internal helper for DoesTableExist and DoesIndexExist.
325 bool DoesTableOrIndexExist(const char* name
, const char* type
) const;
327 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
328 // Refcounting allows us to give these statements out to sql::Statement
329 // objects while also optionally maintaining a cache of compiled statements
330 // by just keeping a refptr to these objects.
332 // A statement ref can be valid, in which case it can be used, or invalid to
333 // indicate that the statement hasn't been created yet, has an error, or has
336 // The Connection may revoke a StatementRef in some error cases, so callers
337 // should always check validity before using.
338 class SQL_EXPORT StatementRef
: public base::RefCounted
<StatementRef
> {
340 // Default constructor initializes to an invalid statement.
342 StatementRef(Connection
* connection
, sqlite3_stmt
* stmt
);
344 // When true, the statement can be used.
345 bool is_valid() const { return !!stmt_
; }
347 // If we've not been linked to a connection, this will be NULL. Guaranteed
348 // non-NULL when is_valid().
349 Connection
* connection() const { return connection_
; }
351 // Returns the sqlite statement if any. If the statement is not active,
352 // this will return NULL.
353 sqlite3_stmt
* stmt() const { return stmt_
; }
355 // Destroys the compiled statement and marks it NULL. The statement will
356 // no longer be active.
360 friend class base::RefCounted
<StatementRef
>;
364 Connection
* connection_
;
367 DISALLOW_COPY_AND_ASSIGN(StatementRef
);
369 friend class StatementRef
;
371 // Executes a rollback statement, ignoring all transaction state. Used
372 // internally in the transaction management code.
375 // Called by a StatementRef when it's being created or destroyed. See
376 // open_statements_ below.
377 void StatementRefCreated(StatementRef
* ref
);
378 void StatementRefDeleted(StatementRef
* ref
);
380 // Frees all cached statements from statement_cache_.
383 // Called by Statement objects when an sqlite function returns an error.
384 // The return value is the error code reflected back to client code.
385 int OnSqliteError(int err
, Statement
* stmt
);
387 // Like |Execute()|, but retries if the database is locked.
388 bool ExecuteWithTimeout(const char* sql
, base::TimeDelta ms_timeout
)
391 // The actual sqlite database. Will be NULL before Init has been called or if
392 // Init resulted in an error.
395 // Parameters we'll configure in sqlite before doing anything else. Zero means
396 // use the default value.
399 bool exclusive_locking_
;
401 // All cached statements. Keeping a reference to these statements means that
402 // they'll remain active.
403 typedef std::map
<StatementID
, scoped_refptr
<StatementRef
> >
405 CachedStatementMap statement_cache_
;
407 // A list of all StatementRefs we've given out. Each ref must register with
408 // us when it's created or destroyed. This allows us to potentially close
409 // any open statements when we encounter an error.
410 typedef std::set
<StatementRef
*> StatementRefSet
;
411 StatementRefSet open_statements_
;
413 // Number of currently-nested transactions.
414 int transaction_nesting_
;
416 // True if any of the currently nested transactions have been rolled back.
417 // When we get to the outermost transaction, this will determine if we do
418 // a rollback instead of a commit.
419 bool needs_rollback_
;
421 // This object handles errors resulting from all forms of executing sqlite
422 // commands or statements. It can be null which means default handling.
423 scoped_refptr
<ErrorDelegate
> error_delegate_
;
425 DISALLOW_COPY_AND_ASSIGN(Connection
);
430 #endif // SQL_CONNECTION_H_