Revert 200549 "Revert 200486 "Include full user email in the res..."
[chromium-blink-merge.git] / sql / connection.h
blob44b97f6d1bd959497dfe8977e603e3f4dd0fbac4
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_
8 #include <map>
9 #include <set>
10 #include <string>
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"
20 struct sqlite3;
21 struct sqlite3_stmt;
23 namespace base {
24 class FilePath;
27 namespace sql {
29 class Statement;
31 // Uniquely identifies a statement. There are two modes of operation:
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.
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.
44 // This object is copyable and assignable using the compiler-generated
45 // operator= and copy constructor.
46 class 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) {
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) {
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);
67 // We need this to insert into our map.
68 bool operator<(const StatementID& other) const;
70 private:
71 int number_;
72 const char* str_;
75 #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
77 class Connection;
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.
85 class SQL_EXPORT ErrorDelegate {
86 public:
87 virtual ~ErrorDelegate();
89 // |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.
93 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
94 // initialization).
96 // 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.
100 virtual int OnError(int error, Connection* connection, Statement* stmt) = 0;
103 class SQL_EXPORT Connection {
104 private:
105 class StatementRef; // Forward declaration, see real one below.
107 public:
108 // The database is opened by calling Open[InMemory](). Any uncommitted
109 // transactions will be rolled back when this object is deleted.
110 Connection();
111 ~Connection();
113 // Pre-init configuration ----------------------------------------------------
115 // Sets the page size that will be used when creating a new database. This
116 // must be called before Init(), and will only have an effect on new
117 // databases.
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; }
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
126 // called before Open() to have an effect.
127 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
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.
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.
138 // This must be called before Open() to have an effect.
139 void set_exclusive_locking() { exclusive_locking_ = true; }
141 // Sets the object that will handle errors. Recomended that it should be set
142 // before calling Open(). If not set, the default is to ignore errors on
143 // release and assert on debug builds.
144 // Takes ownership of |delegate|.
145 void set_error_delegate(ErrorDelegate* delegate) {
146 error_delegate_.reset(delegate);
149 // Set this tag to enable additional connection-type histogramming
150 // for SQLite error codes and database version numbers.
151 void set_histogram_tag(const std::string& tag) {
152 histogram_tag_ = tag;
155 // Record a sparse UMA histogram sample under
156 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
157 // histogram is recorded.
158 void AddTaggedHistogram(const std::string& name, size_t sample) const;
160 // Initialization ------------------------------------------------------------
162 // Initializes the SQL connection for the given file, returning true if the
163 // file could be opened. You can call this or OpenInMemory.
164 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
166 // Initializes the SQL connection for a temporary in-memory database. There
167 // will be no associated file on disk, and the initial database will be
168 // empty. You can call this or Open.
169 bool OpenInMemory() WARN_UNUSED_RESULT;
171 // Returns true if the database has been successfully opened.
172 bool is_open() const { return !!db_; }
174 // Closes the database. This is automatically performed on destruction for
175 // you, but this allows you to close the database early. You must not call
176 // any other functions after closing it. It is permissable to call Close on
177 // an uninitialized or already-closed database.
178 void Close();
180 // Pre-loads the first <cache-size> pages into the cache from the file.
181 // If you expect to soon use a substantial portion of the database, this
182 // is much more efficient than allowing the pages to be populated organically
183 // since there is no per-page hard drive seeking. If the file is larger than
184 // the cache, the last part that doesn't fit in the cache will be brought in
185 // organically.
187 // This function assumes your class is using a meta table on the current
188 // database, as it openes a transaction on the meta table to force the
189 // database to be initialized. You should feel free to initialize the meta
190 // table after calling preload since the meta table will already be in the
191 // database if it exists, and if it doesn't exist, the database won't
192 // generally exist either.
193 void Preload();
195 // Raze the database to the ground. This approximates creating a
196 // fresh database from scratch, within the constraints of SQLite's
197 // locking protocol (locks and open handles can make doing this with
198 // filesystem operations problematic). Returns true if the database
199 // was razed.
201 // false is returned if the database is locked by some other
202 // process. RazeWithTimeout() may be used if appropriate.
204 // NOTE(shess): Raze() will DCHECK in the following situations:
205 // - database is not open.
206 // - the connection has a transaction open.
207 // - a SQLite issue occurs which is structural in nature (like the
208 // statements used are broken).
209 // Since Raze() is expected to be called in unexpected situations,
210 // these all return false, since it is unlikely that the caller
211 // could fix them.
213 // The database's page size is taken from |page_size_|. The
214 // existing database's |auto_vacuum| setting is lost (the
215 // possibility of corruption makes it unreliable to pull it from the
216 // existing database). To re-enable on the empty database requires
217 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
219 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
220 // so Raze() sets auto_vacuum to 1.
222 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
223 // TODO(shess): Bake auto_vacuum into Connection's API so it can
224 // just pick up the default.
225 bool Raze();
226 bool RazeWithTimout(base::TimeDelta timeout);
228 // Breaks all outstanding transactions (as initiated by
229 // BeginTransaction()), calls Raze() to destroy the database, then
230 // closes the database. After this is called, any operations
231 // against the connections (or statements prepared by the
232 // connection) should fail safely.
234 // The value from Raze() is returned, with Close() called in all
235 // cases.
236 bool RazeAndClose();
238 // Transactions --------------------------------------------------------------
240 // Transaction management. We maintain a virtual transaction stack to emulate
241 // nested transactions since sqlite can't do nested transactions. The
242 // limitation is you can't roll back a sub transaction: if any transaction
243 // fails, all transactions open will also be rolled back. Any nested
244 // transactions after one has rolled back will return fail for Begin(). If
245 // Begin() fails, you must not call Commit or Rollback().
247 // Normally you should use sql::Transaction to manage a transaction, which
248 // will scope it to a C++ context.
249 bool BeginTransaction();
250 void RollbackTransaction();
251 bool CommitTransaction();
253 // Returns the current transaction nesting, which will be 0 if there are
254 // no open transactions.
255 int transaction_nesting() const { return transaction_nesting_; }
257 // Statements ----------------------------------------------------------------
259 // Executes the given SQL string, returning true on success. This is
260 // normally used for simple, 1-off statements that don't take any bound
261 // parameters and don't return any data (e.g. CREATE TABLE).
263 // This will DCHECK if the |sql| contains errors.
265 // Do not use ignore_result() to ignore all errors. Use
266 // ExecuteAndReturnErrorCode() and ignore only specific errors.
267 bool Execute(const char* sql) WARN_UNUSED_RESULT;
269 // Like Execute(), but returns the error code given by SQLite.
270 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
272 // Returns true if we have a statement with the given identifier already
273 // cached. This is normally not necessary to call, but can be useful if the
274 // caller has to dynamically build up SQL to avoid doing so if it's already
275 // cached.
276 bool HasCachedStatement(const StatementID& id) const;
278 // Returns a statement for the given SQL using the statement cache. It can
279 // take a nontrivial amount of work to parse and compile a statement, so
280 // keeping commonly-used ones around for future use is important for
281 // performance.
283 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
284 // the code will crash in debug). The caller must deal with this eventuality,
285 // either by checking validity of the |sql| before calling, by correctly
286 // handling the return of an inert statement, or both.
288 // The StatementID and the SQL must always correspond to one-another. The
289 // ID is the lookup into the cache, so crazy things will happen if you use
290 // different SQL with the same ID.
292 // You will normally use the SQL_FROM_HERE macro to generate a statement
293 // ID associated with the current line of code. This gives uniqueness without
294 // you having to manage unique names. See StatementID above for more.
296 // Example:
297 // sql::Statement stmt(connection_.GetCachedStatement(
298 // SQL_FROM_HERE, "SELECT * FROM foo"));
299 // if (!stmt)
300 // return false; // Error creating statement.
301 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
302 const char* sql);
304 // Used to check a |sql| statement for syntactic validity. If the statement is
305 // valid SQL, returns true.
306 bool IsSQLValid(const char* sql);
308 // Returns a non-cached statement for the given SQL. Use this for SQL that
309 // is only executed once or only rarely (there is overhead associated with
310 // keeping a statement cached).
312 // See GetCachedStatement above for examples and error information.
313 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
315 // Info querying -------------------------------------------------------------
317 // Returns true if the given table exists.
318 bool DoesTableExist(const char* table_name) const;
320 // Returns true if the given index exists.
321 bool DoesIndexExist(const char* index_name) const;
323 // Returns true if a column with the given name exists in the given table.
324 bool DoesColumnExist(const char* table_name, const char* column_name) const;
326 // Returns sqlite's internal ID for the last inserted row. Valid only
327 // immediately after an insert.
328 int64 GetLastInsertRowId() const;
330 // Returns sqlite's count of the number of rows modified by the last
331 // statement executed. Will be 0 if no statement has executed or the database
332 // is closed.
333 int GetLastChangeCount() const;
335 // Errors --------------------------------------------------------------------
337 // Returns the error code associated with the last sqlite operation.
338 int GetErrorCode() const;
340 // Returns the errno associated with GetErrorCode(). See
341 // SQLITE_LAST_ERRNO in SQLite documentation.
342 int GetLastErrno() const;
344 // Returns a pointer to a statically allocated string associated with the
345 // last sqlite operation.
346 const char* GetErrorMessage() const;
348 private:
349 // Statement accesses StatementRef which we don't want to expose to everybody
350 // (they should go through Statement).
351 friend class Statement;
353 // Internal initialize function used by both Init and InitInMemory. The file
354 // name is always 8 bits since we want to use the 8-bit version of
355 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
356 bool OpenInternal(const std::string& file_name);
358 // Internal close function used by Close() and RazeAndClose().
359 // |forced| indicates that orderly-shutdown checks should not apply.
360 void CloseInternal(bool forced);
362 // Check whether the current thread is allowed to make IO calls, but only
363 // if database wasn't open in memory. Function is inlined to be a no-op in
364 // official build.
365 void AssertIOAllowed() {
366 if (!in_memory_)
367 base::ThreadRestrictions::AssertIOAllowed();
370 // Internal helper for DoesTableExist and DoesIndexExist.
371 bool DoesTableOrIndexExist(const char* name, const char* type) const;
373 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
374 // Refcounting allows us to give these statements out to sql::Statement
375 // objects while also optionally maintaining a cache of compiled statements
376 // by just keeping a refptr to these objects.
378 // A statement ref can be valid, in which case it can be used, or invalid to
379 // indicate that the statement hasn't been created yet, has an error, or has
380 // been destroyed.
382 // The Connection may revoke a StatementRef in some error cases, so callers
383 // should always check validity before using.
384 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
385 public:
386 // |connection| is the sql::Connection instance associated with
387 // the statement, and is used for tracking outstanding statements
388 // and for error handling. Set to NULL for invalid or untracked
389 // refs. |stmt| is the actual statement, and should only be NULL
390 // to create an invalid ref. |was_valid| indicates whether the
391 // statement should be considered valid for diagnistic purposes.
392 // |was_valid| can be true for NULL |stmt| if the connection has
393 // been forcibly closed by an error handler.
394 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
396 // When true, the statement can be used.
397 bool is_valid() const { return !!stmt_; }
399 // When true, the statement is either currently valid, or was
400 // previously valid but the connection was forcibly closed. Used
401 // for diagnostic checks.
402 bool was_valid() const { return was_valid_; }
404 // If we've not been linked to a connection, this will be NULL.
405 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
406 // which prevents Statement::OnError() from forwarding errors.
407 Connection* connection() const { return connection_; }
409 // Returns the sqlite statement if any. If the statement is not active,
410 // this will return NULL.
411 sqlite3_stmt* stmt() const { return stmt_; }
413 // Destroys the compiled statement and marks it NULL. The statement will
414 // no longer be active. |forced| is used to indicate if orderly-shutdown
415 // checks should apply (see Connection::RazeAndClose()).
416 void Close(bool forced);
418 // Check whether the current thread is allowed to make IO calls, but only
419 // if database wasn't open in memory.
420 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
422 private:
423 friend class base::RefCounted<StatementRef>;
425 ~StatementRef();
427 Connection* connection_;
428 sqlite3_stmt* stmt_;
429 bool was_valid_;
431 DISALLOW_COPY_AND_ASSIGN(StatementRef);
433 friend class StatementRef;
435 // Executes a rollback statement, ignoring all transaction state. Used
436 // internally in the transaction management code.
437 void DoRollback();
439 // Called by a StatementRef when it's being created or destroyed. See
440 // open_statements_ below.
441 void StatementRefCreated(StatementRef* ref);
442 void StatementRefDeleted(StatementRef* ref);
444 // Called by Statement objects when an sqlite function returns an error.
445 // The return value is the error code reflected back to client code.
446 int OnSqliteError(int err, Statement* stmt);
448 // Like |Execute()|, but retries if the database is locked.
449 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
450 WARN_UNUSED_RESULT;
452 // Internal helper for const functions. Like GetUniqueStatement(),
453 // except the statement is not entered into open_statements_,
454 // allowing this function to be const. Open statements can block
455 // closing the database, so only use in cases where the last ref is
456 // released before close could be called (which should always be the
457 // case for const functions).
458 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
460 // The actual sqlite database. Will be NULL before Init has been called or if
461 // Init resulted in an error.
462 sqlite3* db_;
464 // Parameters we'll configure in sqlite before doing anything else. Zero means
465 // use the default value.
466 int page_size_;
467 int cache_size_;
468 bool exclusive_locking_;
470 // All cached statements. Keeping a reference to these statements means that
471 // they'll remain active.
472 typedef std::map<StatementID, scoped_refptr<StatementRef> >
473 CachedStatementMap;
474 CachedStatementMap statement_cache_;
476 // A list of all StatementRefs we've given out. Each ref must register with
477 // us when it's created or destroyed. This allows us to potentially close
478 // any open statements when we encounter an error.
479 typedef std::set<StatementRef*> StatementRefSet;
480 StatementRefSet open_statements_;
482 // Number of currently-nested transactions.
483 int transaction_nesting_;
485 // True if any of the currently nested transactions have been rolled back.
486 // When we get to the outermost transaction, this will determine if we do
487 // a rollback instead of a commit.
488 bool needs_rollback_;
490 // True if database is open with OpenInMemory(), False if database is open
491 // with Open().
492 bool in_memory_;
494 // |true| if the connection was closed using RazeAndClose(). Used
495 // to enable diagnostics to distinguish calls to never-opened
496 // databases (incorrect use of the API) from calls to once-valid
497 // databases.
498 bool poisoned_;
500 // This object handles errors resulting from all forms of executing sqlite
501 // commands or statements. It can be null which means default handling.
502 scoped_ptr<ErrorDelegate> error_delegate_;
504 // Tag for auxiliary histograms.
505 std::string histogram_tag_;
507 DISALLOW_COPY_AND_ASSIGN(Connection);
510 } // namespace sql
512 #endif // SQL_CONNECTION_H_