blob: 65020a04ebb86e0842f1048d119e2d88185b4fbf [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]35f7e5392012-07-27 19:54:5015#include "base/threading/thread_restrictions.h"
[email protected]5b96f3772010-09-28 16:30:5716#include "base/time.h"
[email protected]d4526962011-11-10 21:40:2817#include "sql/sql_export.h"
[email protected]e5ffd0e42009-09-11 21:30:5618
19class FilePath;
20struct sqlite3;
21struct sqlite3_stmt;
22
23namespace sql {
24
25class Statement;
26
27// Uniquely identifies a statement. There are two modes of operation:
28//
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.
33//
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.
39//
40// This object is copyable and assignable using the compiler-generated
41// operator= and copy constructor.
42class StatementID {
43 public:
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)
47 : number_(line),
48 str_(file) {
49 }
50
51 // Creates a uniquely named statement with the given user-defined name.
52 explicit StatementID(const char* unique_name)
53 : number_(-1),
54 str_(unique_name) {
55 }
56
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);
62
63 // We need this to insert into our map.
64 bool operator<(const StatementID& other) const;
65
66 private:
67 int number_;
68 const char* str_;
69};
70
71#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
72
[email protected]faa604e2009-09-25 22:38:5973class Connection;
74
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.
[email protected]d4526962011-11-10 21:40:2881class SQL_EXPORT ErrorDelegate : public base::RefCounted<ErrorDelegate> {
[email protected]faa604e2009-09-25 22:38:5982 public:
[email protected]d4799a32010-09-28 22:54:5883 ErrorDelegate();
84
[email protected]faa604e2009-09-25 22:38:5985 // |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
[email protected]765b44502009-10-02 05:01:4287 // our best guess at the statement that triggered the error. Do not store
[email protected]faa604e2009-09-25 22:38:5988 // these pointers.
[email protected]765b44502009-10-02 05:01:4289 //
90 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
91 // initialization).
92 //
[email protected]faa604e2009-09-25 22:38:5993 // 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;
[email protected]877d55d2009-11-05 21:53:0897
98 protected:
99 friend class base::RefCounted<ErrorDelegate>;
100
[email protected]d4799a32010-09-28 22:54:58101 virtual ~ErrorDelegate();
[email protected]faa604e2009-09-25 22:38:59102};
103
[email protected]d4526962011-11-10 21:40:28104class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56105 private:
106 class StatementRef; // Forward declaration, see real one below.
107
108 public:
[email protected]765b44502009-10-02 05:01:42109 // The database is opened by calling Open[InMemory](). Any uncommitted
110 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56111 Connection();
112 ~Connection();
113
114 // Pre-init configuration ----------------------------------------------------
115
[email protected]765b44502009-10-02 05:01:42116 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56117 // must be called before Init(), and will only have an effect on new
118 // databases.
119 //
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; }
124
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
[email protected]765b44502009-10-02 05:01:42127 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56128 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
129
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
133 // actually need it.
134 //
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.
138 //
[email protected]765b44502009-10-02 05:01:42139 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56140 void set_exclusive_locking() { exclusive_locking_ = true; }
141
[email protected]faa604e2009-09-25 22:38:59142 // Sets the object that will handle errors. Recomended that it should be set
[email protected]765b44502009-10-02 05:01:42143 // before calling Open(). If not set, the default is to ignore errors on
[email protected]faa604e2009-09-25 22:38:59144 // release and assert on debug builds.
145 void set_error_delegate(ErrorDelegate* delegate) {
146 error_delegate_ = delegate;
147 }
148
[email protected]e5ffd0e42009-09-11 21:30:56149 // Initialization ------------------------------------------------------------
150
151 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55152 // file could be opened. You can call this or OpenInMemory.
[email protected]9fe37552011-12-23 17:07:20153 bool Open(const FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42154
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
[email protected]35f2094c2009-12-29 22:46:55157 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20158 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42159
160 // Returns trie if the database has been successfully opened.
161 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56162
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.
167 void Close();
168
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
174 // organically.
175 //
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.
182 void Preload();
183
[email protected]8e0c01282012-04-06 19:36:49184 // 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
188 // was razed.
189 //
190 // false is returned if the database is locked by some other
191 // process. RazeWithTimeout() may be used if appropriate.
192 //
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
200 // could fix them.
201 bool Raze();
202 bool RazeWithTimout(base::TimeDelta timeout);
203
[email protected]e5ffd0e42009-09-11 21:30:56204 // Transactions --------------------------------------------------------------
205
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().
212 //
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();
218
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_; }
222
223 // Statements ----------------------------------------------------------------
224
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).
[email protected]9fe37552011-12-23 17:07:20228 //
[email protected]eff1fa522011-12-12 23:50:59229 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20230 //
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;
[email protected]e5ffd0e42009-09-11 21:30:56234
[email protected]eff1fa522011-12-12 23:50:59235 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20236 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59237
[email protected]e5ffd0e42009-09-11 21:30:56238 // 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
241 // cached.
242 bool HasCachedStatement(const StatementID& id) const;
243
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
247 // performance.
248 //
[email protected]eff1fa522011-12-12 23:50:59249 // 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.
[email protected]e5ffd0e42009-09-11 21:30:56253 //
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.
257 //
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.
261 //
262 // Example:
[email protected]3273dce2010-01-27 16:08:08263 // sql::Statement stmt(connection_.GetCachedStatement(
264 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56265 // if (!stmt)
266 // return false; // Error creating statement.
267 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
268 const char* sql);
269
[email protected]eff1fa522011-12-12 23:50:59270 // Used to check a |sql| statement for syntactic validity. If the statement is
271 // valid SQL, returns true.
272 bool IsSQLValid(const char* sql);
273
[email protected]e5ffd0e42009-09-11 21:30:56274 // 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).
277 //
278 // See GetCachedStatement above for examples and error information.
279 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
280
281 // Info querying -------------------------------------------------------------
282
283 // Returns true if the given table exists.
[email protected]765b44502009-10-02 05:01:42284 bool DoesTableExist(const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56285
[email protected]e2cadec82011-12-13 02:00:53286 // Returns true if the given index exists.
287 bool DoesIndexExist(const char* index_name) const;
288
[email protected]e5ffd0e42009-09-11 21:30:56289 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17290 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56291
292 // Returns sqlite's internal ID for the last inserted row. Valid only
293 // immediately after an insert.
294 int64 GetLastInsertRowId() const;
295
[email protected]1ed78a32009-09-15 20:24:17296 // 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
298 // is closed.
299 int GetLastChangeCount() const;
300
[email protected]e5ffd0e42009-09-11 21:30:56301 // Errors --------------------------------------------------------------------
302
303 // Returns the error code associated with the last sqlite operation.
304 int GetErrorCode() const;
305
[email protected]767718e52010-09-21 23:18:49306 // Returns the errno associated with GetErrorCode(). See
307 // SQLITE_LAST_ERRNO in SQLite documentation.
308 int GetLastErrno() const;
309
[email protected]e5ffd0e42009-09-11 21:30:56310 // Returns a pointer to a statically allocated string associated with the
311 // last sqlite operation.
312 const char* GetErrorMessage() const;
313
314 private:
[email protected]eff1fa522011-12-12 23:50:59315 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56316 // (they should go through Statement).
317 friend class Statement;
318
[email protected]765b44502009-10-02 05:01:42319 // 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);
323
[email protected]35f7e5392012-07-27 19:54:50324 // Check whether the current thread is allowed to make IO calls, but only
325 // if database wasn't open in memory. Function is inlined to be a no-op in
326 // official build.
327 void AssertIOAllowed() {
328 if (!in_memory_)
329 base::ThreadRestrictions::AssertIOAllowed();
330 }
331
[email protected]e2cadec82011-12-13 02:00:53332 // Internal helper for DoesTableExist and DoesIndexExist.
333 bool DoesTableOrIndexExist(const char* name, const char* type) const;
334
[email protected]e5ffd0e42009-09-11 21:30:56335 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
336 // Refcounting allows us to give these statements out to sql::Statement
337 // objects while also optionally maintaining a cache of compiled statements
338 // by just keeping a refptr to these objects.
339 //
340 // A statement ref can be valid, in which case it can be used, or invalid to
341 // indicate that the statement hasn't been created yet, has an error, or has
342 // been destroyed.
343 //
344 // The Connection may revoke a StatementRef in some error cases, so callers
345 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23346 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56347 public:
348 // Default constructor initializes to an invalid statement.
349 StatementRef();
[email protected]2eec0a22012-07-24 01:59:58350 explicit StatementRef(sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56351 StatementRef(Connection* connection, sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56352
353 // When true, the statement can be used.
354 bool is_valid() const { return !!stmt_; }
355
356 // If we've not been linked to a connection, this will be NULL. Guaranteed
357 // non-NULL when is_valid().
358 Connection* connection() const { return connection_; }
359
360 // Returns the sqlite statement if any. If the statement is not active,
361 // this will return NULL.
362 sqlite3_stmt* stmt() const { return stmt_; }
363
364 // Destroys the compiled statement and marks it NULL. The statement will
365 // no longer be active.
366 void Close();
367
[email protected]35f7e5392012-07-27 19:54:50368 // Check whether the current thread is allowed to make IO calls, but only
369 // if database wasn't open in memory.
370 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
371
[email protected]e5ffd0e42009-09-11 21:30:56372 private:
[email protected]877d55d2009-11-05 21:53:08373 friend class base::RefCounted<StatementRef>;
374
375 ~StatementRef();
376
[email protected]e5ffd0e42009-09-11 21:30:56377 Connection* connection_;
378 sqlite3_stmt* stmt_;
379
380 DISALLOW_COPY_AND_ASSIGN(StatementRef);
381 };
382 friend class StatementRef;
383
384 // Executes a rollback statement, ignoring all transaction state. Used
385 // internally in the transaction management code.
386 void DoRollback();
387
388 // Called by a StatementRef when it's being created or destroyed. See
389 // open_statements_ below.
390 void StatementRefCreated(StatementRef* ref);
391 void StatementRefDeleted(StatementRef* ref);
392
393 // Frees all cached statements from statement_cache_.
394 void ClearCache();
395
[email protected]faa604e2009-09-25 22:38:59396 // Called by Statement objects when an sqlite function returns an error.
397 // The return value is the error code reflected back to client code.
398 int OnSqliteError(int err, Statement* stmt);
399
[email protected]5b96f3772010-09-28 16:30:57400 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20401 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
402 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57403
[email protected]2eec0a22012-07-24 01:59:58404 // Internal helper for const functions. Like GetUniqueStatement(),
405 // except the statement is not entered into open_statements_,
406 // allowing this function to be const. Open statements can block
407 // closing the database, so only use in cases where the last ref is
408 // released before close could be called (which should always be the
409 // case for const functions).
410 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
411
[email protected]e5ffd0e42009-09-11 21:30:56412 // The actual sqlite database. Will be NULL before Init has been called or if
413 // Init resulted in an error.
414 sqlite3* db_;
415
416 // Parameters we'll configure in sqlite before doing anything else. Zero means
417 // use the default value.
418 int page_size_;
419 int cache_size_;
420 bool exclusive_locking_;
421
422 // All cached statements. Keeping a reference to these statements means that
423 // they'll remain active.
424 typedef std::map<StatementID, scoped_refptr<StatementRef> >
425 CachedStatementMap;
426 CachedStatementMap statement_cache_;
427
428 // A list of all StatementRefs we've given out. Each ref must register with
429 // us when it's created or destroyed. This allows us to potentially close
430 // any open statements when we encounter an error.
431 typedef std::set<StatementRef*> StatementRefSet;
432 StatementRefSet open_statements_;
433
434 // Number of currently-nested transactions.
435 int transaction_nesting_;
436
437 // True if any of the currently nested transactions have been rolled back.
438 // When we get to the outermost transaction, this will determine if we do
439 // a rollback instead of a commit.
440 bool needs_rollback_;
441
[email protected]35f7e5392012-07-27 19:54:50442 // True if database is open with OpenInMemory(), False if database is open
443 // with Open().
444 bool in_memory_;
445
[email protected]faa604e2009-09-25 22:38:59446 // This object handles errors resulting from all forms of executing sqlite
447 // commands or statements. It can be null which means default handling.
448 scoped_refptr<ErrorDelegate> error_delegate_;
449
[email protected]e5ffd0e42009-09-11 21:30:56450 DISALLOW_COPY_AND_ASSIGN(Connection);
451};
452
453} // namespace sql
454
[email protected]f0a54b22011-07-19 18:40:21455#endif // SQL_CONNECTION_H_