blob: 904d614c6814c15a38f538d5641488e531e78d52 [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:
79 virtual ~ErrorDelegate() {}
80 // |error| is an sqlite result code as seen in sqlite\preprocessed\sqlite3.h
81 // |connection| is db connection where the error happened and |stmt| is
82 // our best guess at the statement that triggered the error. Do not store
83 // these pointers.
84 // If the error condition has been fixed an the original statement succesfuly
85 // re-tried then returning SQLITE_OK is appropiate; otherwise is recomended
86 // that you return the original |error| or the appropiae error code.
87 virtual int OnError(int error, Connection* connection, Statement* stmt) = 0;
88};
89
[email protected]e5ffd0e42009-09-11 21:30:5690class Connection {
91 private:
92 class StatementRef; // Forward declaration, see real one below.
93
94 public:
95 // The database is opened by calling Init(). Any uncommitted transactions
96 // will be rolled back when this object is deleted.
97 Connection();
98 ~Connection();
99
100 // Pre-init configuration ----------------------------------------------------
101
102 // Sets the page size that will be used when creating a new adtabase. This
103 // must be called before Init(), and will only have an effect on new
104 // databases.
105 //
106 // From sqlite.org: "The page size must be a power of two greater than or
107 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
108 // value for SQLITE_MAX_PAGE_SIZE is 32768."
109 void set_page_size(int page_size) { page_size_ = page_size; }
110
111 // Sets the number of pages that will be cached in memory by sqlite. The
112 // total cache size in bytes will be page_size * cache_size. This must be
113 // called before Init() to have an effect.
114 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
115
116 // Call to put the database in exclusive locking mode. There is no "back to
117 // normal" flag because of some additional requirements sqlite puts on this
118 // transaition (requires another access to the DB) and because we don't
119 // actually need it.
120 //
121 // Exclusive mode means that the database is not unlocked at the end of each
122 // transaction, which means there may be less time spent initializing the
123 // next transaction because it doesn't have to re-aquire locks.
124 //
125 // This must be called before Init() to have an effect.
126 void set_exclusive_locking() { exclusive_locking_ = true; }
127
[email protected]faa604e2009-09-25 22:38:59128 // Sets the object that will handle errors. Recomended that it should be set
129 // before calling Init(). If not set, the default is to ignore errors on
130 // release and assert on debug builds.
131 void set_error_delegate(ErrorDelegate* delegate) {
132 error_delegate_ = delegate;
133 }
134
[email protected]e5ffd0e42009-09-11 21:30:56135 // Initialization ------------------------------------------------------------
136
137 // Initializes the SQL connection for the given file, returning true if the
138 // file could be opened.
139 bool Init(const FilePath& path);
140
141 // Closes the database. This is automatically performed on destruction for
142 // you, but this allows you to close the database early. You must not call
143 // any other functions after closing it. It is permissable to call Close on
144 // an uninitialized or already-closed database.
145 void Close();
146
147 // Pre-loads the first <cache-size> pages into the cache from the file.
148 // If you expect to soon use a substantial portion of the database, this
149 // is much more efficient than allowing the pages to be populated organically
150 // since there is no per-page hard drive seeking. If the file is larger than
151 // the cache, the last part that doesn't fit in the cache will be brought in
152 // organically.
153 //
154 // This function assumes your class is using a meta table on the current
155 // database, as it openes a transaction on the meta table to force the
156 // database to be initialized. You should feel free to initialize the meta
157 // table after calling preload since the meta table will already be in the
158 // database if it exists, and if it doesn't exist, the database won't
159 // generally exist either.
160 void Preload();
161
162 // Transactions --------------------------------------------------------------
163
164 // Transaction management. We maintain a virtual transaction stack to emulate
165 // nested transactions since sqlite can't do nested transactions. The
166 // limitation is you can't roll back a sub transaction: if any transaction
167 // fails, all transactions open will also be rolled back. Any nested
168 // transactions after one has rolled back will return fail for Begin(). If
169 // Begin() fails, you must not call Commit or Rollback().
170 //
171 // Normally you should use sql::Transaction to manage a transaction, which
172 // will scope it to a C++ context.
173 bool BeginTransaction();
174 void RollbackTransaction();
175 bool CommitTransaction();
176
177 // Returns the current transaction nesting, which will be 0 if there are
178 // no open transactions.
179 int transaction_nesting() const { return transaction_nesting_; }
180
181 // Statements ----------------------------------------------------------------
182
183 // Executes the given SQL string, returning true on success. This is
184 // normally used for simple, 1-off statements that don't take any bound
185 // parameters and don't return any data (e.g. CREATE TABLE).
186 bool Execute(const char* sql);
187
188 // Returns true if we have a statement with the given identifier already
189 // cached. This is normally not necessary to call, but can be useful if the
190 // caller has to dynamically build up SQL to avoid doing so if it's already
191 // cached.
192 bool HasCachedStatement(const StatementID& id) const;
193
194 // Returns a statement for the given SQL using the statement cache. It can
195 // take a nontrivial amount of work to parse and compile a statement, so
196 // keeping commonly-used ones around for future use is important for
197 // performance.
198 //
199 // The SQL may have an error, so the caller must check validity of the
200 // statement before using it.
201 //
202 // The StatementID and the SQL must always correspond to one-another. The
203 // ID is the lookup into the cache, so crazy things will happen if you use
204 // different SQL with the same ID.
205 //
206 // You will normally use the SQL_FROM_HERE macro to generate a statement
207 // ID associated with the current line of code. This gives uniqueness without
208 // you having to manage unique names. See StatementID above for more.
209 //
210 // Example:
211 // sql::Statement stmt = connection_.GetCachedStatement(
212 // SQL_FROM_HERE, "SELECT * FROM foo");
213 // if (!stmt)
214 // return false; // Error creating statement.
215 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
216 const char* sql);
217
218 // Returns a non-cached statement for the given SQL. Use this for SQL that
219 // is only executed once or only rarely (there is overhead associated with
220 // keeping a statement cached).
221 //
222 // See GetCachedStatement above for examples and error information.
223 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
224
225 // Info querying -------------------------------------------------------------
226
227 // Returns true if the given table exists.
[email protected]1ed78a32009-09-15 20:24:17228 bool DoesTableExist( const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56229
230 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17231 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56232
233 // Returns sqlite's internal ID for the last inserted row. Valid only
234 // immediately after an insert.
235 int64 GetLastInsertRowId() const;
236
[email protected]1ed78a32009-09-15 20:24:17237 // Returns sqlite's count of the number of rows modified by the last
238 // statement executed. Will be 0 if no statement has executed or the database
239 // is closed.
240 int GetLastChangeCount() const;
241
[email protected]e5ffd0e42009-09-11 21:30:56242 // Errors --------------------------------------------------------------------
243
244 // Returns the error code associated with the last sqlite operation.
245 int GetErrorCode() const;
246
247 // Returns a pointer to a statically allocated string associated with the
248 // last sqlite operation.
249 const char* GetErrorMessage() const;
250
251 private:
252 // Statement access StatementRef which we don't want to expose to erverybody
253 // (they should go through Statement).
254 friend class Statement;
255
256 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
257 // Refcounting allows us to give these statements out to sql::Statement
258 // objects while also optionally maintaining a cache of compiled statements
259 // by just keeping a refptr to these objects.
260 //
261 // A statement ref can be valid, in which case it can be used, or invalid to
262 // indicate that the statement hasn't been created yet, has an error, or has
263 // been destroyed.
264 //
265 // The Connection may revoke a StatementRef in some error cases, so callers
266 // should always check validity before using.
267 class StatementRef : public base::RefCounted<StatementRef> {
268 public:
269 // Default constructor initializes to an invalid statement.
270 StatementRef();
271 StatementRef(Connection* connection, sqlite3_stmt* stmt);
272 ~StatementRef();
273
274 // When true, the statement can be used.
275 bool is_valid() const { return !!stmt_; }
276
277 // If we've not been linked to a connection, this will be NULL. Guaranteed
278 // non-NULL when is_valid().
279 Connection* connection() const { return connection_; }
280
281 // Returns the sqlite statement if any. If the statement is not active,
282 // this will return NULL.
283 sqlite3_stmt* stmt() const { return stmt_; }
284
285 // Destroys the compiled statement and marks it NULL. The statement will
286 // no longer be active.
287 void Close();
288
289 private:
290 Connection* connection_;
291 sqlite3_stmt* stmt_;
292
293 DISALLOW_COPY_AND_ASSIGN(StatementRef);
294 };
295 friend class StatementRef;
296
297 // Executes a rollback statement, ignoring all transaction state. Used
298 // internally in the transaction management code.
299 void DoRollback();
300
301 // Called by a StatementRef when it's being created or destroyed. See
302 // open_statements_ below.
303 void StatementRefCreated(StatementRef* ref);
304 void StatementRefDeleted(StatementRef* ref);
305
306 // Frees all cached statements from statement_cache_.
307 void ClearCache();
308
[email protected]faa604e2009-09-25 22:38:59309 // Called by Statement objects when an sqlite function returns an error.
310 // The return value is the error code reflected back to client code.
311 int OnSqliteError(int err, Statement* stmt);
312
[email protected]e5ffd0e42009-09-11 21:30:56313 // The actual sqlite database. Will be NULL before Init has been called or if
314 // Init resulted in an error.
315 sqlite3* db_;
316
317 // Parameters we'll configure in sqlite before doing anything else. Zero means
318 // use the default value.
319 int page_size_;
320 int cache_size_;
321 bool exclusive_locking_;
322
323 // All cached statements. Keeping a reference to these statements means that
324 // they'll remain active.
325 typedef std::map<StatementID, scoped_refptr<StatementRef> >
326 CachedStatementMap;
327 CachedStatementMap statement_cache_;
328
329 // A list of all StatementRefs we've given out. Each ref must register with
330 // us when it's created or destroyed. This allows us to potentially close
331 // any open statements when we encounter an error.
332 typedef std::set<StatementRef*> StatementRefSet;
333 StatementRefSet open_statements_;
334
335 // Number of currently-nested transactions.
336 int transaction_nesting_;
337
338 // True if any of the currently nested transactions have been rolled back.
339 // When we get to the outermost transaction, this will determine if we do
340 // a rollback instead of a commit.
341 bool needs_rollback_;
342
[email protected]faa604e2009-09-25 22:38:59343 // This object handles errors resulting from all forms of executing sqlite
344 // commands or statements. It can be null which means default handling.
345 scoped_refptr<ErrorDelegate> error_delegate_;
346
[email protected]e5ffd0e42009-09-11 21:30:56347 DISALLOW_COPY_AND_ASSIGN(Connection);
348};
349
350} // namespace sql
351
352#endif // APP_SQL_CONNECTION_H_