blob: fa7c99da7c5eaee7f57769acaae0acbef8357522 [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
8#include <map>
9#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3310#include <string>
[email protected]e5ffd0e42009-09-11 21:30:5611
12#include "base/basictypes.h"
[email protected]9fe37552011-12-23 17:07:2013#include "base/compiler_specific.h"
[email protected]3b63f8f42011-03-28 01:54:1514#include "base/memory/ref_counted.h"
[email protected]49dc4f22012-10-17 17:41:1615#include "base/memory/scoped_ptr.h"
[email protected]35f7e5392012-07-27 19:54:5016#include "base/threading/thread_restrictions.h"
[email protected]5b96f3772010-09-28 16:30:5717#include "base/time.h"
[email protected]d4526962011-11-10 21:40:2818#include "sql/sql_export.h"
[email protected]e5ffd0e42009-09-11 21:30:5619
[email protected]e5ffd0e42009-09-11 21:30:5620struct sqlite3;
21struct sqlite3_stmt;
22
[email protected]a3ef4832013-02-02 05:12:3323namespace base {
24class FilePath;
25}
26
[email protected]e5ffd0e42009-09-11 21:30:5627namespace sql {
28
29class Statement;
30
31// Uniquely identifies a statement. There are two modes of operation:
32//
33// - In the most common mode, you will use the source file and line number to
34// identify your statement. This is a convienient way to get uniqueness for
35// a statement that is only used in one place. Use the SQL_FROM_HERE macro
36// to generate a StatementID.
37//
38// - In the "custom" mode you may use the statement from different places or
39// need to manage it yourself for whatever reason. In this case, you should
40// make up your own unique name and pass it to the StatementID. This name
41// must be a static string, since this object only deals with pointers and
42// assumes the underlying string doesn't change or get deleted.
43//
44// This object is copyable and assignable using the compiler-generated
45// operator= and copy constructor.
46class StatementID {
47 public:
48 // Creates a uniquely named statement with the given file ane line number.
49 // Normally you will use SQL_FROM_HERE instead of calling yourself.
50 StatementID(const char* file, int line)
51 : number_(line),
52 str_(file) {
53 }
54
55 // Creates a uniquely named statement with the given user-defined name.
56 explicit StatementID(const char* unique_name)
57 : number_(-1),
58 str_(unique_name) {
59 }
60
61 // This constructor is unimplemented and will generate a linker error if
62 // called. It is intended to try to catch people dynamically generating
63 // a statement name that will be deallocated and will cause a crash later.
64 // All strings must be static and unchanging!
65 explicit StatementID(const std::string& dont_ever_do_this);
66
67 // We need this to insert into our map.
68 bool operator<(const StatementID& other) const;
69
70 private:
71 int number_;
72 const char* str_;
73};
74
75#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
76
[email protected]faa604e2009-09-25 22:38:5977class Connection;
78
79// ErrorDelegate defines the interface to implement error handling and recovery
80// for sqlite operations. This allows the rest of the classes to return true or
81// false while the actual error code and causing statement are delivered using
82// the OnError() callback.
83// The tipical usage is to centralize the code designed to handle database
84// corruption, low-level IO errors or locking violations.
[email protected]49dc4f22012-10-17 17:41:1685class SQL_EXPORT ErrorDelegate {
[email protected]faa604e2009-09-25 22:38:5986 public:
[email protected]49dc4f22012-10-17 17:41:1687 virtual ~ErrorDelegate();
[email protected]d4799a32010-09-28 22:54:5888
[email protected]0d04ede2012-10-18 04:31:5389 // |error| is an sqlite result code as seen in sqlite3.h. |connection| is the
90 // db connection where the error happened and |stmt| is our best guess at the
91 // statement that triggered the error. Do not store these pointers.
[email protected]765b44502009-10-02 05:01:4292 //
93 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
94 // initialization).
95 //
[email protected]0d04ede2012-10-18 04:31:5396 // If the error condition has been fixed and the original statement succesfuly
97 // re-tried then returning SQLITE_OK is appropriate; otherwise it is
98 // recommended that you return the original |error| or the appropriate error
99 // code.
[email protected]faa604e2009-09-25 22:38:59100 virtual int OnError(int error, Connection* connection, Statement* stmt) = 0;
101};
102
[email protected]d4526962011-11-10 21:40:28103class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56104 private:
105 class StatementRef; // Forward declaration, see real one below.
106
107 public:
[email protected]765b44502009-10-02 05:01:42108 // The database is opened by calling Open[InMemory](). Any uncommitted
109 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56110 Connection();
111 ~Connection();
112
113 // Pre-init configuration ----------------------------------------------------
114
[email protected]765b44502009-10-02 05:01:42115 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56116 // must be called before Init(), and will only have an effect on new
117 // databases.
118 //
119 // From sqlite.org: "The page size must be a power of two greater than or
120 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
121 // value for SQLITE_MAX_PAGE_SIZE is 32768."
122 void set_page_size(int page_size) { page_size_ = page_size; }
123
124 // Sets the number of pages that will be cached in memory by sqlite. The
125 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42126 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56127 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
128
129 // Call to put the database in exclusive locking mode. There is no "back to
130 // normal" flag because of some additional requirements sqlite puts on this
131 // transaition (requires another access to the DB) and because we don't
132 // actually need it.
133 //
134 // Exclusive mode means that the database is not unlocked at the end of each
135 // transaction, which means there may be less time spent initializing the
136 // next transaction because it doesn't have to re-aquire locks.
137 //
[email protected]765b44502009-10-02 05:01:42138 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56139 void set_exclusive_locking() { exclusive_locking_ = true; }
140
[email protected]faa604e2009-09-25 22:38:59141 // Sets the object that will handle errors. Recomended that it should be set
[email protected]765b44502009-10-02 05:01:42142 // before calling Open(). If not set, the default is to ignore errors on
[email protected]faa604e2009-09-25 22:38:59143 // release and assert on debug builds.
[email protected]49dc4f22012-10-17 17:41:16144 // Takes ownership of |delegate|.
[email protected]faa604e2009-09-25 22:38:59145 void set_error_delegate(ErrorDelegate* delegate) {
[email protected]49dc4f22012-10-17 17:41:16146 error_delegate_.reset(delegate);
[email protected]faa604e2009-09-25 22:38:59147 }
148
[email protected]c088e3a32013-01-03 23:59:14149 // SQLite error codes for errors on all connections are logged to
150 // enum histogram "Sqlite.Error". Setting this additionally logs
151 // errors to the histogram |name|.
152 void set_error_histogram_name(const std::string& name) {
153 error_histogram_name_ = name;
154 }
155
[email protected]e5ffd0e42009-09-11 21:30:56156 // Initialization ------------------------------------------------------------
157
158 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55159 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33160 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42161
162 // Initializes the SQL connection for a temporary in-memory database. There
163 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55164 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20165 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42166
167 // Returns trie if the database has been successfully opened.
168 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56169
170 // Closes the database. This is automatically performed on destruction for
171 // you, but this allows you to close the database early. You must not call
172 // any other functions after closing it. It is permissable to call Close on
173 // an uninitialized or already-closed database.
174 void Close();
175
176 // Pre-loads the first <cache-size> pages into the cache from the file.
177 // If you expect to soon use a substantial portion of the database, this
178 // is much more efficient than allowing the pages to be populated organically
179 // since there is no per-page hard drive seeking. If the file is larger than
180 // the cache, the last part that doesn't fit in the cache will be brought in
181 // organically.
182 //
183 // This function assumes your class is using a meta table on the current
184 // database, as it openes a transaction on the meta table to force the
185 // database to be initialized. You should feel free to initialize the meta
186 // table after calling preload since the meta table will already be in the
187 // database if it exists, and if it doesn't exist, the database won't
188 // generally exist either.
189 void Preload();
190
[email protected]8e0c01282012-04-06 19:36:49191 // Raze the database to the ground. This approximates creating a
192 // fresh database from scratch, within the constraints of SQLite's
193 // locking protocol (locks and open handles can make doing this with
194 // filesystem operations problematic). Returns true if the database
195 // was razed.
196 //
197 // false is returned if the database is locked by some other
198 // process. RazeWithTimeout() may be used if appropriate.
199 //
200 // NOTE(shess): Raze() will DCHECK in the following situations:
201 // - database is not open.
202 // - the connection has a transaction open.
203 // - a SQLite issue occurs which is structural in nature (like the
204 // statements used are broken).
205 // Since Raze() is expected to be called in unexpected situations,
206 // these all return false, since it is unlikely that the caller
207 // could fix them.
[email protected]6d42f152012-11-10 00:38:24208 //
209 // The database's page size is taken from |page_size_|. The
210 // existing database's |auto_vacuum| setting is lost (the
211 // possibility of corruption makes it unreliable to pull it from the
212 // existing database). To re-enable on the empty database requires
213 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
214 //
215 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
216 // so Raze() sets auto_vacuum to 1.
217 //
218 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
219 // TODO(shess): Bake auto_vacuum into Connection's API so it can
220 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49221 bool Raze();
222 bool RazeWithTimout(base::TimeDelta timeout);
223
[email protected]e5ffd0e42009-09-11 21:30:56224 // Transactions --------------------------------------------------------------
225
226 // Transaction management. We maintain a virtual transaction stack to emulate
227 // nested transactions since sqlite can't do nested transactions. The
228 // limitation is you can't roll back a sub transaction: if any transaction
229 // fails, all transactions open will also be rolled back. Any nested
230 // transactions after one has rolled back will return fail for Begin(). If
231 // Begin() fails, you must not call Commit or Rollback().
232 //
233 // Normally you should use sql::Transaction to manage a transaction, which
234 // will scope it to a C++ context.
235 bool BeginTransaction();
236 void RollbackTransaction();
237 bool CommitTransaction();
238
239 // Returns the current transaction nesting, which will be 0 if there are
240 // no open transactions.
241 int transaction_nesting() const { return transaction_nesting_; }
242
243 // Statements ----------------------------------------------------------------
244
245 // Executes the given SQL string, returning true on success. This is
246 // normally used for simple, 1-off statements that don't take any bound
247 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20248 //
[email protected]eff1fa522011-12-12 23:50:59249 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20250 //
251 // Do not use ignore_result() to ignore all errors. Use
252 // ExecuteAndReturnErrorCode() and ignore only specific errors.
253 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56254
[email protected]eff1fa522011-12-12 23:50:59255 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20256 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59257
[email protected]e5ffd0e42009-09-11 21:30:56258 // Returns true if we have a statement with the given identifier already
259 // cached. This is normally not necessary to call, but can be useful if the
260 // caller has to dynamically build up SQL to avoid doing so if it's already
261 // cached.
262 bool HasCachedStatement(const StatementID& id) const;
263
264 // Returns a statement for the given SQL using the statement cache. It can
265 // take a nontrivial amount of work to parse and compile a statement, so
266 // keeping commonly-used ones around for future use is important for
267 // performance.
268 //
[email protected]eff1fa522011-12-12 23:50:59269 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
270 // the code will crash in debug). The caller must deal with this eventuality,
271 // either by checking validity of the |sql| before calling, by correctly
272 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56273 //
274 // The StatementID and the SQL must always correspond to one-another. The
275 // ID is the lookup into the cache, so crazy things will happen if you use
276 // different SQL with the same ID.
277 //
278 // You will normally use the SQL_FROM_HERE macro to generate a statement
279 // ID associated with the current line of code. This gives uniqueness without
280 // you having to manage unique names. See StatementID above for more.
281 //
282 // Example:
[email protected]3273dce2010-01-27 16:08:08283 // sql::Statement stmt(connection_.GetCachedStatement(
284 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56285 // if (!stmt)
286 // return false; // Error creating statement.
287 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
288 const char* sql);
289
[email protected]eff1fa522011-12-12 23:50:59290 // Used to check a |sql| statement for syntactic validity. If the statement is
291 // valid SQL, returns true.
292 bool IsSQLValid(const char* sql);
293
[email protected]e5ffd0e42009-09-11 21:30:56294 // Returns a non-cached statement for the given SQL. Use this for SQL that
295 // is only executed once or only rarely (there is overhead associated with
296 // keeping a statement cached).
297 //
298 // See GetCachedStatement above for examples and error information.
299 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
300
301 // Info querying -------------------------------------------------------------
302
303 // Returns true if the given table exists.
[email protected]765b44502009-10-02 05:01:42304 bool DoesTableExist(const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56305
[email protected]e2cadec82011-12-13 02:00:53306 // Returns true if the given index exists.
307 bool DoesIndexExist(const char* index_name) const;
308
[email protected]e5ffd0e42009-09-11 21:30:56309 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17310 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56311
312 // Returns sqlite's internal ID for the last inserted row. Valid only
313 // immediately after an insert.
314 int64 GetLastInsertRowId() const;
315
[email protected]1ed78a32009-09-15 20:24:17316 // Returns sqlite's count of the number of rows modified by the last
317 // statement executed. Will be 0 if no statement has executed or the database
318 // is closed.
319 int GetLastChangeCount() const;
320
[email protected]e5ffd0e42009-09-11 21:30:56321 // Errors --------------------------------------------------------------------
322
323 // Returns the error code associated with the last sqlite operation.
324 int GetErrorCode() const;
325
[email protected]767718e52010-09-21 23:18:49326 // Returns the errno associated with GetErrorCode(). See
327 // SQLITE_LAST_ERRNO in SQLite documentation.
328 int GetLastErrno() const;
329
[email protected]e5ffd0e42009-09-11 21:30:56330 // Returns a pointer to a statically allocated string associated with the
331 // last sqlite operation.
332 const char* GetErrorMessage() const;
333
334 private:
[email protected]eff1fa522011-12-12 23:50:59335 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56336 // (they should go through Statement).
337 friend class Statement;
338
[email protected]765b44502009-10-02 05:01:42339 // Internal initialize function used by both Init and InitInMemory. The file
340 // name is always 8 bits since we want to use the 8-bit version of
341 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
342 bool OpenInternal(const std::string& file_name);
343
[email protected]35f7e5392012-07-27 19:54:50344 // Check whether the current thread is allowed to make IO calls, but only
345 // if database wasn't open in memory. Function is inlined to be a no-op in
346 // official build.
347 void AssertIOAllowed() {
348 if (!in_memory_)
349 base::ThreadRestrictions::AssertIOAllowed();
350 }
351
[email protected]e2cadec82011-12-13 02:00:53352 // Internal helper for DoesTableExist and DoesIndexExist.
353 bool DoesTableOrIndexExist(const char* name, const char* type) const;
354
[email protected]e5ffd0e42009-09-11 21:30:56355 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
356 // Refcounting allows us to give these statements out to sql::Statement
357 // objects while also optionally maintaining a cache of compiled statements
358 // by just keeping a refptr to these objects.
359 //
360 // A statement ref can be valid, in which case it can be used, or invalid to
361 // indicate that the statement hasn't been created yet, has an error, or has
362 // been destroyed.
363 //
364 // The Connection may revoke a StatementRef in some error cases, so callers
365 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23366 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56367 public:
368 // Default constructor initializes to an invalid statement.
369 StatementRef();
[email protected]2eec0a22012-07-24 01:59:58370 explicit StatementRef(sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56371 StatementRef(Connection* connection, sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56372
373 // When true, the statement can be used.
374 bool is_valid() const { return !!stmt_; }
375
[email protected]b4c363b2013-01-17 13:11:17376 // If we've not been linked to a connection, this will be NULL.
377 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
378 // which prevents Statement::OnError() from forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56379 Connection* connection() const { return connection_; }
380
381 // Returns the sqlite statement if any. If the statement is not active,
382 // this will return NULL.
383 sqlite3_stmt* stmt() const { return stmt_; }
384
385 // Destroys the compiled statement and marks it NULL. The statement will
386 // no longer be active.
387 void Close();
388
[email protected]35f7e5392012-07-27 19:54:50389 // Check whether the current thread is allowed to make IO calls, but only
390 // if database wasn't open in memory.
391 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
392
[email protected]e5ffd0e42009-09-11 21:30:56393 private:
[email protected]877d55d2009-11-05 21:53:08394 friend class base::RefCounted<StatementRef>;
395
396 ~StatementRef();
397
[email protected]e5ffd0e42009-09-11 21:30:56398 Connection* connection_;
399 sqlite3_stmt* stmt_;
400
401 DISALLOW_COPY_AND_ASSIGN(StatementRef);
402 };
403 friend class StatementRef;
404
405 // Executes a rollback statement, ignoring all transaction state. Used
406 // internally in the transaction management code.
407 void DoRollback();
408
409 // Called by a StatementRef when it's being created or destroyed. See
410 // open_statements_ below.
411 void StatementRefCreated(StatementRef* ref);
412 void StatementRefDeleted(StatementRef* ref);
413
414 // Frees all cached statements from statement_cache_.
415 void ClearCache();
416
[email protected]faa604e2009-09-25 22:38:59417 // Called by Statement objects when an sqlite function returns an error.
418 // The return value is the error code reflected back to client code.
419 int OnSqliteError(int err, Statement* stmt);
420
[email protected]5b96f3772010-09-28 16:30:57421 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20422 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
423 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57424
[email protected]2eec0a22012-07-24 01:59:58425 // Internal helper for const functions. Like GetUniqueStatement(),
426 // except the statement is not entered into open_statements_,
427 // allowing this function to be const. Open statements can block
428 // closing the database, so only use in cases where the last ref is
429 // released before close could be called (which should always be the
430 // case for const functions).
431 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
432
[email protected]e5ffd0e42009-09-11 21:30:56433 // The actual sqlite database. Will be NULL before Init has been called or if
434 // Init resulted in an error.
435 sqlite3* db_;
436
437 // Parameters we'll configure in sqlite before doing anything else. Zero means
438 // use the default value.
439 int page_size_;
440 int cache_size_;
441 bool exclusive_locking_;
442
443 // All cached statements. Keeping a reference to these statements means that
444 // they'll remain active.
445 typedef std::map<StatementID, scoped_refptr<StatementRef> >
446 CachedStatementMap;
447 CachedStatementMap statement_cache_;
448
449 // A list of all StatementRefs we've given out. Each ref must register with
450 // us when it's created or destroyed. This allows us to potentially close
451 // any open statements when we encounter an error.
452 typedef std::set<StatementRef*> StatementRefSet;
453 StatementRefSet open_statements_;
454
455 // Number of currently-nested transactions.
456 int transaction_nesting_;
457
458 // True if any of the currently nested transactions have been rolled back.
459 // When we get to the outermost transaction, this will determine if we do
460 // a rollback instead of a commit.
461 bool needs_rollback_;
462
[email protected]35f7e5392012-07-27 19:54:50463 // True if database is open with OpenInMemory(), False if database is open
464 // with Open().
465 bool in_memory_;
466
[email protected]faa604e2009-09-25 22:38:59467 // This object handles errors resulting from all forms of executing sqlite
468 // commands or statements. It can be null which means default handling.
[email protected]49dc4f22012-10-17 17:41:16469 scoped_ptr<ErrorDelegate> error_delegate_;
[email protected]faa604e2009-09-25 22:38:59470
[email protected]c088e3a32013-01-03 23:59:14471 // Auxiliary error-code histogram.
472 std::string error_histogram_name_;
473
[email protected]e5ffd0e42009-09-11 21:30:56474 DISALLOW_COPY_AND_ASSIGN(Connection);
475};
476
477} // namespace sql
478
[email protected]f0a54b22011-07-19 18:40:21479#endif // SQL_CONNECTION_H_