blob: 52587acb3576282e2feb55e2e053c18323b1ce56 [file] [log] [blame]
[email protected]e5ffd0e42009-09-11 21:30:561// Copyright (c) 2009 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.
4
5#ifndef APP_SQL_CONNECTION_H_
6#define APP_SQL_CONNECTION_H_
7
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"
13#include "base/ref_counted.h"
14
15class FilePath;
16struct sqlite3;
17struct sqlite3_stmt;
18
19namespace sql {
20
21class Statement;
22
23// Uniquely identifies a statement. There are two modes of operation:
24//
25// - In the most common mode, you will use the source file and line number to
26// identify your statement. This is a convienient way to get uniqueness for
27// a statement that is only used in one place. Use the SQL_FROM_HERE macro
28// to generate a StatementID.
29//
30// - In the "custom" mode you may use the statement from different places or
31// need to manage it yourself for whatever reason. In this case, you should
32// make up your own unique name and pass it to the StatementID. This name
33// must be a static string, since this object only deals with pointers and
34// assumes the underlying string doesn't change or get deleted.
35//
36// This object is copyable and assignable using the compiler-generated
37// operator= and copy constructor.
38class StatementID {
39 public:
40 // Creates a uniquely named statement with the given file ane line number.
41 // Normally you will use SQL_FROM_HERE instead of calling yourself.
42 StatementID(const char* file, int line)
43 : number_(line),
44 str_(file) {
45 }
46
47 // Creates a uniquely named statement with the given user-defined name.
48 explicit StatementID(const char* unique_name)
49 : number_(-1),
50 str_(unique_name) {
51 }
52
53 // This constructor is unimplemented and will generate a linker error if
54 // called. It is intended to try to catch people dynamically generating
55 // a statement name that will be deallocated and will cause a crash later.
56 // All strings must be static and unchanging!
57 explicit StatementID(const std::string& dont_ever_do_this);
58
59 // We need this to insert into our map.
60 bool operator<(const StatementID& other) const;
61
62 private:
63 int number_;
64 const char* str_;
65};
66
67#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
68
[email protected]faa604e2009-09-25 22:38:5969class Connection;
70
71// ErrorDelegate defines the interface to implement error handling and recovery
72// for sqlite operations. This allows the rest of the classes to return true or
73// false while the actual error code and causing statement are delivered using
74// the OnError() callback.
75// The tipical usage is to centralize the code designed to handle database
76// corruption, low-level IO errors or locking violations.
77class ErrorDelegate : public base::RefCounted<ErrorDelegate> {
78 public:
[email protected]faa604e2009-09-25 22:38:5979 // |error| is an sqlite result code as seen in sqlite\preprocessed\sqlite3.h
80 // |connection| is db connection where the error happened and |stmt| is
[email protected]765b44502009-10-02 05:01:4281 // our best guess at the statement that triggered the error. Do not store
[email protected]faa604e2009-09-25 22:38:5982 // these pointers.
[email protected]765b44502009-10-02 05:01:4283 //
84 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
85 // initialization).
86 //
[email protected]faa604e2009-09-25 22:38:5987 // If the error condition has been fixed an the original statement succesfuly
88 // re-tried then returning SQLITE_OK is appropiate; otherwise is recomended
89 // that you return the original |error| or the appropiae error code.
90 virtual int OnError(int error, Connection* connection, Statement* stmt) = 0;
[email protected]877d55d2009-11-05 21:53:0891
92 protected:
93 friend class base::RefCounted<ErrorDelegate>;
94
95 virtual ~ErrorDelegate() {}
[email protected]faa604e2009-09-25 22:38:5996};
97
[email protected]e5ffd0e42009-09-11 21:30:5698class Connection {
99 private:
100 class StatementRef; // Forward declaration, see real one below.
101
102 public:
[email protected]765b44502009-10-02 05:01:42103 // The database is opened by calling Open[InMemory](). Any uncommitted
104 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56105 Connection();
106 ~Connection();
107
108 // Pre-init configuration ----------------------------------------------------
109
[email protected]765b44502009-10-02 05:01:42110 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56111 // must be called before Init(), and will only have an effect on new
112 // databases.
113 //
114 // From sqlite.org: "The page size must be a power of two greater than or
115 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
116 // value for SQLITE_MAX_PAGE_SIZE is 32768."
117 void set_page_size(int page_size) { page_size_ = page_size; }
118
119 // Sets the number of pages that will be cached in memory by sqlite. The
120 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:42121 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56122 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
123
124 // Call to put the database in exclusive locking mode. There is no "back to
125 // normal" flag because of some additional requirements sqlite puts on this
126 // transaition (requires another access to the DB) and because we don't
127 // actually need it.
128 //
129 // Exclusive mode means that the database is not unlocked at the end of each
130 // transaction, which means there may be less time spent initializing the
131 // next transaction because it doesn't have to re-aquire locks.
132 //
[email protected]765b44502009-10-02 05:01:42133 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56134 void set_exclusive_locking() { exclusive_locking_ = true; }
135
[email protected]faa604e2009-09-25 22:38:59136 // Sets the object that will handle errors. Recomended that it should be set
[email protected]765b44502009-10-02 05:01:42137 // before calling Open(). If not set, the default is to ignore errors on
[email protected]faa604e2009-09-25 22:38:59138 // release and assert on debug builds.
139 void set_error_delegate(ErrorDelegate* delegate) {
140 error_delegate_ = delegate;
141 }
142
[email protected]e5ffd0e42009-09-11 21:30:56143 // Initialization ------------------------------------------------------------
144
145 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55146 // file could be opened. You can call this or OpenInMemory.
[email protected]765b44502009-10-02 05:01:42147 bool Open(const FilePath& path);
148
149 // Initializes the SQL connection for a temporary in-memory database. There
150 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55151 // empty. You can call this or Open.
[email protected]765b44502009-10-02 05:01:42152 bool OpenInMemory();
153
154 // Returns trie if the database has been successfully opened.
155 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56156
157 // Closes the database. This is automatically performed on destruction for
158 // you, but this allows you to close the database early. You must not call
159 // any other functions after closing it. It is permissable to call Close on
160 // an uninitialized or already-closed database.
161 void Close();
162
163 // Pre-loads the first <cache-size> pages into the cache from the file.
164 // If you expect to soon use a substantial portion of the database, this
165 // is much more efficient than allowing the pages to be populated organically
166 // since there is no per-page hard drive seeking. If the file is larger than
167 // the cache, the last part that doesn't fit in the cache will be brought in
168 // organically.
169 //
170 // This function assumes your class is using a meta table on the current
171 // database, as it openes a transaction on the meta table to force the
172 // database to be initialized. You should feel free to initialize the meta
173 // table after calling preload since the meta table will already be in the
174 // database if it exists, and if it doesn't exist, the database won't
175 // generally exist either.
176 void Preload();
177
178 // Transactions --------------------------------------------------------------
179
180 // Transaction management. We maintain a virtual transaction stack to emulate
181 // nested transactions since sqlite can't do nested transactions. The
182 // limitation is you can't roll back a sub transaction: if any transaction
183 // fails, all transactions open will also be rolled back. Any nested
184 // transactions after one has rolled back will return fail for Begin(). If
185 // Begin() fails, you must not call Commit or Rollback().
186 //
187 // Normally you should use sql::Transaction to manage a transaction, which
188 // will scope it to a C++ context.
189 bool BeginTransaction();
190 void RollbackTransaction();
191 bool CommitTransaction();
192
193 // Returns the current transaction nesting, which will be 0 if there are
194 // no open transactions.
195 int transaction_nesting() const { return transaction_nesting_; }
196
197 // Statements ----------------------------------------------------------------
198
199 // Executes the given SQL string, returning true on success. This is
200 // normally used for simple, 1-off statements that don't take any bound
201 // parameters and don't return any data (e.g. CREATE TABLE).
202 bool Execute(const char* sql);
203
204 // Returns true if we have a statement with the given identifier already
205 // cached. This is normally not necessary to call, but can be useful if the
206 // caller has to dynamically build up SQL to avoid doing so if it's already
207 // cached.
208 bool HasCachedStatement(const StatementID& id) const;
209
210 // Returns a statement for the given SQL using the statement cache. It can
211 // take a nontrivial amount of work to parse and compile a statement, so
212 // keeping commonly-used ones around for future use is important for
213 // performance.
214 //
215 // The SQL may have an error, so the caller must check validity of the
216 // statement before using it.
217 //
218 // The StatementID and the SQL must always correspond to one-another. The
219 // ID is the lookup into the cache, so crazy things will happen if you use
220 // different SQL with the same ID.
221 //
222 // You will normally use the SQL_FROM_HERE macro to generate a statement
223 // ID associated with the current line of code. This gives uniqueness without
224 // you having to manage unique names. See StatementID above for more.
225 //
226 // Example:
227 // sql::Statement stmt = connection_.GetCachedStatement(
228 // SQL_FROM_HERE, "SELECT * FROM foo");
229 // if (!stmt)
230 // return false; // Error creating statement.
231 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
232 const char* sql);
233
234 // Returns a non-cached statement for the given SQL. Use this for SQL that
235 // is only executed once or only rarely (there is overhead associated with
236 // keeping a statement cached).
237 //
238 // See GetCachedStatement above for examples and error information.
239 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
240
241 // Info querying -------------------------------------------------------------
242
243 // Returns true if the given table exists.
[email protected]765b44502009-10-02 05:01:42244 bool DoesTableExist(const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56245
246 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17247 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56248
249 // Returns sqlite's internal ID for the last inserted row. Valid only
250 // immediately after an insert.
251 int64 GetLastInsertRowId() const;
252
[email protected]1ed78a32009-09-15 20:24:17253 // Returns sqlite's count of the number of rows modified by the last
254 // statement executed. Will be 0 if no statement has executed or the database
255 // is closed.
256 int GetLastChangeCount() const;
257
[email protected]e5ffd0e42009-09-11 21:30:56258 // Errors --------------------------------------------------------------------
259
260 // Returns the error code associated with the last sqlite operation.
261 int GetErrorCode() const;
262
263 // Returns a pointer to a statically allocated string associated with the
264 // last sqlite operation.
265 const char* GetErrorMessage() const;
266
267 private:
268 // Statement access StatementRef which we don't want to expose to erverybody
269 // (they should go through Statement).
270 friend class Statement;
271
[email protected]765b44502009-10-02 05:01:42272 // Internal initialize function used by both Init and InitInMemory. The file
273 // name is always 8 bits since we want to use the 8-bit version of
274 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
275 bool OpenInternal(const std::string& file_name);
276
[email protected]e5ffd0e42009-09-11 21:30:56277 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
278 // Refcounting allows us to give these statements out to sql::Statement
279 // objects while also optionally maintaining a cache of compiled statements
280 // by just keeping a refptr to these objects.
281 //
282 // A statement ref can be valid, in which case it can be used, or invalid to
283 // indicate that the statement hasn't been created yet, has an error, or has
284 // been destroyed.
285 //
286 // The Connection may revoke a StatementRef in some error cases, so callers
287 // should always check validity before using.
288 class StatementRef : public base::RefCounted<StatementRef> {
289 public:
290 // Default constructor initializes to an invalid statement.
291 StatementRef();
292 StatementRef(Connection* connection, sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56293
294 // When true, the statement can be used.
295 bool is_valid() const { return !!stmt_; }
296
297 // If we've not been linked to a connection, this will be NULL. Guaranteed
298 // non-NULL when is_valid().
299 Connection* connection() const { return connection_; }
300
301 // Returns the sqlite statement if any. If the statement is not active,
302 // this will return NULL.
303 sqlite3_stmt* stmt() const { return stmt_; }
304
305 // Destroys the compiled statement and marks it NULL. The statement will
306 // no longer be active.
307 void Close();
308
309 private:
[email protected]877d55d2009-11-05 21:53:08310 friend class base::RefCounted<StatementRef>;
311
312 ~StatementRef();
313
[email protected]e5ffd0e42009-09-11 21:30:56314 Connection* connection_;
315 sqlite3_stmt* stmt_;
316
317 DISALLOW_COPY_AND_ASSIGN(StatementRef);
318 };
319 friend class StatementRef;
320
321 // Executes a rollback statement, ignoring all transaction state. Used
322 // internally in the transaction management code.
323 void DoRollback();
324
325 // Called by a StatementRef when it's being created or destroyed. See
326 // open_statements_ below.
327 void StatementRefCreated(StatementRef* ref);
328 void StatementRefDeleted(StatementRef* ref);
329
330 // Frees all cached statements from statement_cache_.
331 void ClearCache();
332
[email protected]faa604e2009-09-25 22:38:59333 // Called by Statement objects when an sqlite function returns an error.
334 // The return value is the error code reflected back to client code.
335 int OnSqliteError(int err, Statement* stmt);
336
[email protected]e5ffd0e42009-09-11 21:30:56337 // The actual sqlite database. Will be NULL before Init has been called or if
338 // Init resulted in an error.
339 sqlite3* db_;
340
341 // Parameters we'll configure in sqlite before doing anything else. Zero means
342 // use the default value.
343 int page_size_;
344 int cache_size_;
345 bool exclusive_locking_;
346
347 // All cached statements. Keeping a reference to these statements means that
348 // they'll remain active.
349 typedef std::map<StatementID, scoped_refptr<StatementRef> >
350 CachedStatementMap;
351 CachedStatementMap statement_cache_;
352
353 // A list of all StatementRefs we've given out. Each ref must register with
354 // us when it's created or destroyed. This allows us to potentially close
355 // any open statements when we encounter an error.
356 typedef std::set<StatementRef*> StatementRefSet;
357 StatementRefSet open_statements_;
358
359 // Number of currently-nested transactions.
360 int transaction_nesting_;
361
362 // True if any of the currently nested transactions have been rolled back.
363 // When we get to the outermost transaction, this will determine if we do
364 // a rollback instead of a commit.
365 bool needs_rollback_;
366
[email protected]faa604e2009-09-25 22:38:59367 // This object handles errors resulting from all forms of executing sqlite
368 // commands or statements. It can be null which means default handling.
369 scoped_refptr<ErrorDelegate> error_delegate_;
370
[email protected]e5ffd0e42009-09-11 21:30:56371 DISALLOW_COPY_AND_ASSIGN(Connection);
372};
373
374} // namespace sql
375
376#endif // APP_SQL_CONNECTION_H_