Introduce PPB_UDPSocket_Dev.
[chromium-blink-merge.git] / sql / connection.h
blob049d7cf5b4e2f9715ffc4b7f67dd2e89dc367bff
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>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/threading/thread_restrictions.h"
19 #include "base/time.h"
20 #include "sql/sql_export.h"
22 struct sqlite3;
23 struct sqlite3_stmt;
25 namespace base {
26 class FilePath;
29 namespace sql {
31 class Statement;
33 // Uniquely identifies a statement. There are two modes of operation:
35 // - In the most common mode, you will use the source file and line number to
36 // identify your statement. This is a convienient way to get uniqueness for
37 // a statement that is only used in one place. Use the SQL_FROM_HERE macro
38 // to generate a StatementID.
40 // - In the "custom" mode you may use the statement from different places or
41 // need to manage it yourself for whatever reason. In this case, you should
42 // make up your own unique name and pass it to the StatementID. This name
43 // must be a static string, since this object only deals with pointers and
44 // assumes the underlying string doesn't change or get deleted.
46 // This object is copyable and assignable using the compiler-generated
47 // operator= and copy constructor.
48 class StatementID {
49 public:
50 // Creates a uniquely named statement with the given file ane line number.
51 // Normally you will use SQL_FROM_HERE instead of calling yourself.
52 StatementID(const char* file, int line)
53 : number_(line),
54 str_(file) {
57 // Creates a uniquely named statement with the given user-defined name.
58 explicit StatementID(const char* unique_name)
59 : number_(-1),
60 str_(unique_name) {
63 // This constructor is unimplemented and will generate a linker error if
64 // called. It is intended to try to catch people dynamically generating
65 // a statement name that will be deallocated and will cause a crash later.
66 // All strings must be static and unchanging!
67 explicit StatementID(const std::string& dont_ever_do_this);
69 // We need this to insert into our map.
70 bool operator<(const StatementID& other) const;
72 private:
73 int number_;
74 const char* str_;
77 #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
79 class Connection;
81 // ErrorDelegate defines the interface to implement error handling and recovery
82 // for sqlite operations. This allows the rest of the classes to return true or
83 // false while the actual error code and causing statement are delivered using
84 // the OnError() callback.
85 // The tipical usage is to centralize the code designed to handle database
86 // corruption, low-level IO errors or locking violations.
87 class SQL_EXPORT ErrorDelegate {
88 public:
89 virtual ~ErrorDelegate();
91 // |error| is an sqlite result code as seen in sqlite3.h. |connection| is the
92 // db connection where the error happened and |stmt| is our best guess at the
93 // statement that triggered the error. Do not store these pointers.
95 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
96 // initialization).
98 // If the error condition has been fixed and the original statement succesfuly
99 // re-tried then returning SQLITE_OK is appropriate; otherwise it is
100 // recommended that you return the original |error| or the appropriate error
101 // code.
102 virtual int OnError(int error, Connection* connection, Statement* stmt) = 0;
105 class SQL_EXPORT Connection {
106 private:
107 class StatementRef; // Forward declaration, see real one below.
109 public:
110 // The database is opened by calling Open[InMemory](). Any uncommitted
111 // transactions will be rolled back when this object is deleted.
112 Connection();
113 ~Connection();
115 // Pre-init configuration ----------------------------------------------------
117 // Sets the page size that will be used when creating a new database. This
118 // must be called before Init(), and will only have an effect on new
119 // databases.
121 // From sqlite.org: "The page size must be a power of two greater than or
122 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
123 // value for SQLITE_MAX_PAGE_SIZE is 32768."
124 void set_page_size(int page_size) { page_size_ = page_size; }
126 // Sets the number of pages that will be cached in memory by sqlite. The
127 // total cache size in bytes will be page_size * cache_size. This must be
128 // called before Open() to have an effect.
129 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
131 // Call to put the database in exclusive locking mode. There is no "back to
132 // normal" flag because of some additional requirements sqlite puts on this
133 // transaition (requires another access to the DB) and because we don't
134 // actually need it.
136 // Exclusive mode means that the database is not unlocked at the end of each
137 // transaction, which means there may be less time spent initializing the
138 // next transaction because it doesn't have to re-aquire locks.
140 // This must be called before Open() to have an effect.
141 void set_exclusive_locking() { exclusive_locking_ = true; }
143 // Set an error-handling callback. On errors, the error number (and
144 // statement, if available) will be passed to the callback.
146 // If no callback is set, the default action is to crash in debug
147 // mode or return failure in release mode.
149 // TODO(shess): ErrorDelegate allowed for returning a different
150 // error. Determine if this is necessary for the callback. In my
151 // experience, this is not well-tested and probably not safe, and
152 // current clients always return the same error passed.
153 // Additionally, most errors don't admit to a clean way to retry the
154 // failed operation, so converting an error to SQLITE_OK is probably
155 // not feasible.
156 typedef base::Callback<void(int, Statement*)> ErrorCallback;
157 void set_error_callback(const ErrorCallback& callback) {
158 error_callback_ = callback;
160 void reset_error_callback() {
161 error_callback_.Reset();
164 // Sets the object that will handle errors. Recomended that it should be set
165 // before calling Open(). If not set, the default is to ignore errors on
166 // release and assert on debug builds.
167 // Takes ownership of |delegate|.
168 // NOTE(shess): Deprecated, use set_error_callback().
169 void set_error_delegate(ErrorDelegate* delegate) {
170 error_delegate_.reset(delegate);
173 // Set this tag to enable additional connection-type histogramming
174 // for SQLite error codes and database version numbers.
175 void set_histogram_tag(const std::string& tag) {
176 histogram_tag_ = tag;
179 // Record a sparse UMA histogram sample under
180 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
181 // histogram is recorded.
182 void AddTaggedHistogram(const std::string& name, size_t sample) const;
184 // Run "PRAGMA integrity_check" and post each line of results into
185 // |messages|. Returns the success of running the statement - per
186 // the SQLite documentation, if no errors are found the call should
187 // succeed, and a single value "ok" should be in messages.
188 bool IntegrityCheck(std::vector<std::string>* messages);
190 // Initialization ------------------------------------------------------------
192 // Initializes the SQL connection for the given file, returning true if the
193 // file could be opened. You can call this or OpenInMemory.
194 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
196 // Initializes the SQL connection for a temporary in-memory database. There
197 // will be no associated file on disk, and the initial database will be
198 // empty. You can call this or Open.
199 bool OpenInMemory() WARN_UNUSED_RESULT;
201 // Returns true if the database has been successfully opened.
202 bool is_open() const { return !!db_; }
204 // Closes the database. This is automatically performed on destruction for
205 // you, but this allows you to close the database early. You must not call
206 // any other functions after closing it. It is permissable to call Close on
207 // an uninitialized or already-closed database.
208 void Close();
210 // Pre-loads the first <cache-size> pages into the cache from the file.
211 // If you expect to soon use a substantial portion of the database, this
212 // is much more efficient than allowing the pages to be populated organically
213 // since there is no per-page hard drive seeking. If the file is larger than
214 // the cache, the last part that doesn't fit in the cache will be brought in
215 // organically.
217 // This function assumes your class is using a meta table on the current
218 // database, as it openes a transaction on the meta table to force the
219 // database to be initialized. You should feel free to initialize the meta
220 // table after calling preload since the meta table will already be in the
221 // database if it exists, and if it doesn't exist, the database won't
222 // generally exist either.
223 void Preload();
225 // Raze the database to the ground. This approximates creating a
226 // fresh database from scratch, within the constraints of SQLite's
227 // locking protocol (locks and open handles can make doing this with
228 // filesystem operations problematic). Returns true if the database
229 // was razed.
231 // false is returned if the database is locked by some other
232 // process. RazeWithTimeout() may be used if appropriate.
234 // NOTE(shess): Raze() will DCHECK in the following situations:
235 // - database is not open.
236 // - the connection has a transaction open.
237 // - a SQLite issue occurs which is structural in nature (like the
238 // statements used are broken).
239 // Since Raze() is expected to be called in unexpected situations,
240 // these all return false, since it is unlikely that the caller
241 // could fix them.
243 // The database's page size is taken from |page_size_|. The
244 // existing database's |auto_vacuum| setting is lost (the
245 // possibility of corruption makes it unreliable to pull it from the
246 // existing database). To re-enable on the empty database requires
247 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
249 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
250 // so Raze() sets auto_vacuum to 1.
252 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
253 // TODO(shess): Bake auto_vacuum into Connection's API so it can
254 // just pick up the default.
255 bool Raze();
256 bool RazeWithTimout(base::TimeDelta timeout);
258 // Breaks all outstanding transactions (as initiated by
259 // BeginTransaction()), calls Raze() to destroy the database, then
260 // closes the database. After this is called, any operations
261 // against the connections (or statements prepared by the
262 // connection) should fail safely.
264 // The value from Raze() is returned, with Close() called in all
265 // cases.
266 bool RazeAndClose();
268 // Transactions --------------------------------------------------------------
270 // Transaction management. We maintain a virtual transaction stack to emulate
271 // nested transactions since sqlite can't do nested transactions. The
272 // limitation is you can't roll back a sub transaction: if any transaction
273 // fails, all transactions open will also be rolled back. Any nested
274 // transactions after one has rolled back will return fail for Begin(). If
275 // Begin() fails, you must not call Commit or Rollback().
277 // Normally you should use sql::Transaction to manage a transaction, which
278 // will scope it to a C++ context.
279 bool BeginTransaction();
280 void RollbackTransaction();
281 bool CommitTransaction();
283 // Returns the current transaction nesting, which will be 0 if there are
284 // no open transactions.
285 int transaction_nesting() const { return transaction_nesting_; }
287 // Statements ----------------------------------------------------------------
289 // Executes the given SQL string, returning true on success. This is
290 // normally used for simple, 1-off statements that don't take any bound
291 // parameters and don't return any data (e.g. CREATE TABLE).
293 // This will DCHECK if the |sql| contains errors.
295 // Do not use ignore_result() to ignore all errors. Use
296 // ExecuteAndReturnErrorCode() and ignore only specific errors.
297 bool Execute(const char* sql) WARN_UNUSED_RESULT;
299 // Like Execute(), but returns the error code given by SQLite.
300 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
302 // Returns true if we have a statement with the given identifier already
303 // cached. This is normally not necessary to call, but can be useful if the
304 // caller has to dynamically build up SQL to avoid doing so if it's already
305 // cached.
306 bool HasCachedStatement(const StatementID& id) const;
308 // Returns a statement for the given SQL using the statement cache. It can
309 // take a nontrivial amount of work to parse and compile a statement, so
310 // keeping commonly-used ones around for future use is important for
311 // performance.
313 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
314 // the code will crash in debug). The caller must deal with this eventuality,
315 // either by checking validity of the |sql| before calling, by correctly
316 // handling the return of an inert statement, or both.
318 // The StatementID and the SQL must always correspond to one-another. The
319 // ID is the lookup into the cache, so crazy things will happen if you use
320 // different SQL with the same ID.
322 // You will normally use the SQL_FROM_HERE macro to generate a statement
323 // ID associated with the current line of code. This gives uniqueness without
324 // you having to manage unique names. See StatementID above for more.
326 // Example:
327 // sql::Statement stmt(connection_.GetCachedStatement(
328 // SQL_FROM_HERE, "SELECT * FROM foo"));
329 // if (!stmt)
330 // return false; // Error creating statement.
331 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
332 const char* sql);
334 // Used to check a |sql| statement for syntactic validity. If the statement is
335 // valid SQL, returns true.
336 bool IsSQLValid(const char* sql);
338 // Returns a non-cached statement for the given SQL. Use this for SQL that
339 // is only executed once or only rarely (there is overhead associated with
340 // keeping a statement cached).
342 // See GetCachedStatement above for examples and error information.
343 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
345 // Info querying -------------------------------------------------------------
347 // Returns true if the given table exists.
348 bool DoesTableExist(const char* table_name) const;
350 // Returns true if the given index exists.
351 bool DoesIndexExist(const char* index_name) const;
353 // Returns true if a column with the given name exists in the given table.
354 bool DoesColumnExist(const char* table_name, const char* column_name) const;
356 // Returns sqlite's internal ID for the last inserted row. Valid only
357 // immediately after an insert.
358 int64 GetLastInsertRowId() const;
360 // Returns sqlite's count of the number of rows modified by the last
361 // statement executed. Will be 0 if no statement has executed or the database
362 // is closed.
363 int GetLastChangeCount() const;
365 // Errors --------------------------------------------------------------------
367 // Returns the error code associated with the last sqlite operation.
368 int GetErrorCode() const;
370 // Returns the errno associated with GetErrorCode(). See
371 // SQLITE_LAST_ERRNO in SQLite documentation.
372 int GetLastErrno() const;
374 // Returns a pointer to a statically allocated string associated with the
375 // last sqlite operation.
376 const char* GetErrorMessage() const;
378 private:
379 // Statement accesses StatementRef which we don't want to expose to everybody
380 // (they should go through Statement).
381 friend class Statement;
383 // Internal initialize function used by both Init and InitInMemory. The file
384 // name is always 8 bits since we want to use the 8-bit version of
385 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
386 bool OpenInternal(const std::string& file_name);
388 // Internal close function used by Close() and RazeAndClose().
389 // |forced| indicates that orderly-shutdown checks should not apply.
390 void CloseInternal(bool forced);
392 // Check whether the current thread is allowed to make IO calls, but only
393 // if database wasn't open in memory. Function is inlined to be a no-op in
394 // official build.
395 void AssertIOAllowed() {
396 if (!in_memory_)
397 base::ThreadRestrictions::AssertIOAllowed();
400 // Internal helper for DoesTableExist and DoesIndexExist.
401 bool DoesTableOrIndexExist(const char* name, const char* type) const;
403 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
404 // Refcounting allows us to give these statements out to sql::Statement
405 // objects while also optionally maintaining a cache of compiled statements
406 // by just keeping a refptr to these objects.
408 // A statement ref can be valid, in which case it can be used, or invalid to
409 // indicate that the statement hasn't been created yet, has an error, or has
410 // been destroyed.
412 // The Connection may revoke a StatementRef in some error cases, so callers
413 // should always check validity before using.
414 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
415 public:
416 // |connection| is the sql::Connection instance associated with
417 // the statement, and is used for tracking outstanding statements
418 // and for error handling. Set to NULL for invalid or untracked
419 // refs. |stmt| is the actual statement, and should only be NULL
420 // to create an invalid ref. |was_valid| indicates whether the
421 // statement should be considered valid for diagnistic purposes.
422 // |was_valid| can be true for NULL |stmt| if the connection has
423 // been forcibly closed by an error handler.
424 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
426 // When true, the statement can be used.
427 bool is_valid() const { return !!stmt_; }
429 // When true, the statement is either currently valid, or was
430 // previously valid but the connection was forcibly closed. Used
431 // for diagnostic checks.
432 bool was_valid() const { return was_valid_; }
434 // If we've not been linked to a connection, this will be NULL.
435 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
436 // which prevents Statement::OnError() from forwarding errors.
437 Connection* connection() const { return connection_; }
439 // Returns the sqlite statement if any. If the statement is not active,
440 // this will return NULL.
441 sqlite3_stmt* stmt() const { return stmt_; }
443 // Destroys the compiled statement and marks it NULL. The statement will
444 // no longer be active. |forced| is used to indicate if orderly-shutdown
445 // checks should apply (see Connection::RazeAndClose()).
446 void Close(bool forced);
448 // Check whether the current thread is allowed to make IO calls, but only
449 // if database wasn't open in memory.
450 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
452 private:
453 friend class base::RefCounted<StatementRef>;
455 ~StatementRef();
457 Connection* connection_;
458 sqlite3_stmt* stmt_;
459 bool was_valid_;
461 DISALLOW_COPY_AND_ASSIGN(StatementRef);
463 friend class StatementRef;
465 // Executes a rollback statement, ignoring all transaction state. Used
466 // internally in the transaction management code.
467 void DoRollback();
469 // Called by a StatementRef when it's being created or destroyed. See
470 // open_statements_ below.
471 void StatementRefCreated(StatementRef* ref);
472 void StatementRefDeleted(StatementRef* ref);
474 // Called by Statement objects when an sqlite function returns an error.
475 // The return value is the error code reflected back to client code.
476 int OnSqliteError(int err, Statement* stmt);
478 // Like |Execute()|, but retries if the database is locked.
479 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
480 WARN_UNUSED_RESULT;
482 // Internal helper for const functions. Like GetUniqueStatement(),
483 // except the statement is not entered into open_statements_,
484 // allowing this function to be const. Open statements can block
485 // closing the database, so only use in cases where the last ref is
486 // released before close could be called (which should always be the
487 // case for const functions).
488 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
490 // The actual sqlite database. Will be NULL before Init has been called or if
491 // Init resulted in an error.
492 sqlite3* db_;
494 // Parameters we'll configure in sqlite before doing anything else. Zero means
495 // use the default value.
496 int page_size_;
497 int cache_size_;
498 bool exclusive_locking_;
500 // All cached statements. Keeping a reference to these statements means that
501 // they'll remain active.
502 typedef std::map<StatementID, scoped_refptr<StatementRef> >
503 CachedStatementMap;
504 CachedStatementMap statement_cache_;
506 // A list of all StatementRefs we've given out. Each ref must register with
507 // us when it's created or destroyed. This allows us to potentially close
508 // any open statements when we encounter an error.
509 typedef std::set<StatementRef*> StatementRefSet;
510 StatementRefSet open_statements_;
512 // Number of currently-nested transactions.
513 int transaction_nesting_;
515 // True if any of the currently nested transactions have been rolled back.
516 // When we get to the outermost transaction, this will determine if we do
517 // a rollback instead of a commit.
518 bool needs_rollback_;
520 // True if database is open with OpenInMemory(), False if database is open
521 // with Open().
522 bool in_memory_;
524 // |true| if the connection was closed using RazeAndClose(). Used
525 // to enable diagnostics to distinguish calls to never-opened
526 // databases (incorrect use of the API) from calls to once-valid
527 // databases.
528 bool poisoned_;
530 ErrorCallback error_callback_;
532 // This object handles errors resulting from all forms of executing sqlite
533 // commands or statements. It can be null which means default handling.
534 scoped_ptr<ErrorDelegate> error_delegate_;
536 // Tag for auxiliary histograms.
537 std::string histogram_tag_;
539 DISALLOW_COPY_AND_ASSIGN(Connection);
542 } // namespace sql
544 #endif // SQL_CONNECTION_H_