blob: 5446c0c67a927101ba081cf370e08f28209b21a2 [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 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]32b76ef2010-07-26 23:08:247#pragma once
[email protected]e5ffd0e42009-09-11 21:30:568
9#include <map>
10#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3311#include <string>
[email protected]e5ffd0e42009-09-11 21:30:5612
13#include "base/basictypes.h"
[email protected]3b63f8f42011-03-28 01:54:1514#include "base/memory/ref_counted.h"
[email protected]5b96f3772010-09-28 16:30:5715#include "base/time.h"
[email protected]d4526962011-11-10 21:40:2816#include "sql/sql_export.h"
[email protected]e5ffd0e42009-09-11 21:30:5617
18class FilePath;
19struct sqlite3;
20struct sqlite3_stmt;
21
22namespace sql {
23
24class Statement;
25
26// Uniquely identifies a statement. There are two modes of operation:
27//
28// - In the most common mode, you will use the source file and line number to
29// identify your statement. This is a convienient way to get uniqueness for
30// a statement that is only used in one place. Use the SQL_FROM_HERE macro
31// to generate a StatementID.
32//
33// - In the "custom" mode you may use the statement from different places or
34// need to manage it yourself for whatever reason. In this case, you should
35// make up your own unique name and pass it to the StatementID. This name
36// must be a static string, since this object only deals with pointers and
37// assumes the underlying string doesn't change or get deleted.
38//
39// This object is copyable and assignable using the compiler-generated
40// operator= and copy constructor.
41class StatementID {
42 public:
43 // Creates a uniquely named statement with the given file ane line number.
44 // Normally you will use SQL_FROM_HERE instead of calling yourself.
45 StatementID(const char* file, int line)
46 : number_(line),
47 str_(file) {
48 }
49
50 // Creates a uniquely named statement with the given user-defined name.
51 explicit StatementID(const char* unique_name)
52 : number_(-1),
53 str_(unique_name) {
54 }
55
56 // This constructor is unimplemented and will generate a linker error if
57 // called. It is intended to try to catch people dynamically generating
58 // a statement name that will be deallocated and will cause a crash later.
59 // All strings must be static and unchanging!
60 explicit StatementID(const std::string& dont_ever_do_this);
61
62 // We need this to insert into our map.
63 bool operator<(const StatementID& other) const;
64
65 private:
66 int number_;
67 const char* str_;
68};
69
70#define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
71
[email protected]faa604e2009-09-25 22:38:5972class Connection;
73
74// ErrorDelegate defines the interface to implement error handling and recovery
75// for sqlite operations. This allows the rest of the classes to return true or
76// false while the actual error code and causing statement are delivered using
77// the OnError() callback.
78// The tipical usage is to centralize the code designed to handle database
79// corruption, low-level IO errors or locking violations.
[email protected]d4526962011-11-10 21:40:2880class SQL_EXPORT ErrorDelegate : public base::RefCounted<ErrorDelegate> {
[email protected]faa604e2009-09-25 22:38:5981 public:
[email protected]d4799a32010-09-28 22:54:5882 ErrorDelegate();
83
[email protected]faa604e2009-09-25 22:38:5984 // |error| is an sqlite result code as seen in sqlite\preprocessed\sqlite3.h
85 // |connection| is db connection where the error happened and |stmt| is
[email protected]765b44502009-10-02 05:01:4286 // our best guess at the statement that triggered the error. Do not store
[email protected]faa604e2009-09-25 22:38:5987 // these pointers.
[email protected]765b44502009-10-02 05:01:4288 //
89 // |stmt| MAY BE NULL if there is no statement causing the problem (i.e. on
90 // initialization).
91 //
[email protected]faa604e2009-09-25 22:38:5992 // If the error condition has been fixed an the original statement succesfuly
93 // re-tried then returning SQLITE_OK is appropiate; otherwise is recomended
94 // that you return the original |error| or the appropiae error code.
95 virtual int OnError(int error, Connection* connection, Statement* stmt) = 0;
[email protected]877d55d2009-11-05 21:53:0896
97 protected:
98 friend class base::RefCounted<ErrorDelegate>;
99
[email protected]d4799a32010-09-28 22:54:58100 virtual ~ErrorDelegate();
[email protected]faa604e2009-09-25 22:38:59101};
102
[email protected]d4526962011-11-10 21:40:28103class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:56104 private:
105 class StatementRef; // Forward declaration, see real one below.
106
107 public:
[email protected]765b44502009-10-02 05:01:42108 // The database is opened by calling Open[InMemory](). Any uncommitted
109 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:56110 Connection();
111 ~Connection();
112
113 // Pre-init configuration ----------------------------------------------------
114
[email protected]765b44502009-10-02 05:01:42115 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:56116 // must be called before Init(), and will only have an effect on new
117 // databases.
118 //
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; }
123
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
[email protected]765b44502009-10-02 05:01:42126 // called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56127 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
128
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.
133 //
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.
137 //
[email protected]765b44502009-10-02 05:01:42138 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56139 void set_exclusive_locking() { exclusive_locking_ = true; }
140
[email protected]faa604e2009-09-25 22:38:59141 // Sets the object that will handle errors. Recomended that it should be set
[email protected]765b44502009-10-02 05:01:42142 // before calling Open(). If not set, the default is to ignore errors on
[email protected]faa604e2009-09-25 22:38:59143 // release and assert on debug builds.
144 void set_error_delegate(ErrorDelegate* delegate) {
145 error_delegate_ = delegate;
146 }
147
[email protected]e5ffd0e42009-09-11 21:30:56148 // Initialization ------------------------------------------------------------
149
150 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55151 // file could be opened. You can call this or OpenInMemory.
[email protected]765b44502009-10-02 05:01:42152 bool Open(const FilePath& path);
153
154 // Initializes the SQL connection for a temporary in-memory database. There
155 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55156 // empty. You can call this or Open.
[email protected]765b44502009-10-02 05:01:42157 bool OpenInMemory();
158
159 // Returns trie if the database has been successfully opened.
160 bool is_open() const { return !!db_; }
[email protected]e5ffd0e42009-09-11 21:30:56161
162 // Closes the database. This is automatically performed on destruction for
163 // you, but this allows you to close the database early. You must not call
164 // any other functions after closing it. It is permissable to call Close on
165 // an uninitialized or already-closed database.
166 void Close();
167
168 // Pre-loads the first <cache-size> pages into the cache from the file.
169 // If you expect to soon use a substantial portion of the database, this
170 // is much more efficient than allowing the pages to be populated organically
171 // since there is no per-page hard drive seeking. If the file is larger than
172 // the cache, the last part that doesn't fit in the cache will be brought in
173 // organically.
174 //
175 // This function assumes your class is using a meta table on the current
176 // database, as it openes a transaction on the meta table to force the
177 // database to be initialized. You should feel free to initialize the meta
178 // table after calling preload since the meta table will already be in the
179 // database if it exists, and if it doesn't exist, the database won't
180 // generally exist either.
181 void Preload();
182
183 // Transactions --------------------------------------------------------------
184
185 // Transaction management. We maintain a virtual transaction stack to emulate
186 // nested transactions since sqlite can't do nested transactions. The
187 // limitation is you can't roll back a sub transaction: if any transaction
188 // fails, all transactions open will also be rolled back. Any nested
189 // transactions after one has rolled back will return fail for Begin(). If
190 // Begin() fails, you must not call Commit or Rollback().
191 //
192 // Normally you should use sql::Transaction to manage a transaction, which
193 // will scope it to a C++ context.
194 bool BeginTransaction();
195 void RollbackTransaction();
196 bool CommitTransaction();
197
198 // Returns the current transaction nesting, which will be 0 if there are
199 // no open transactions.
200 int transaction_nesting() const { return transaction_nesting_; }
201
202 // Statements ----------------------------------------------------------------
203
204 // Executes the given SQL string, returning true on success. This is
205 // normally used for simple, 1-off statements that don't take any bound
206 // parameters and don't return any data (e.g. CREATE TABLE).
207 bool Execute(const char* sql);
208
209 // Returns true if we have a statement with the given identifier already
210 // cached. This is normally not necessary to call, but can be useful if the
211 // caller has to dynamically build up SQL to avoid doing so if it's already
212 // cached.
213 bool HasCachedStatement(const StatementID& id) const;
214
215 // Returns a statement for the given SQL using the statement cache. It can
216 // take a nontrivial amount of work to parse and compile a statement, so
217 // keeping commonly-used ones around for future use is important for
218 // performance.
219 //
220 // The SQL may have an error, so the caller must check validity of the
221 // statement before using it.
222 //
223 // The StatementID and the SQL must always correspond to one-another. The
224 // ID is the lookup into the cache, so crazy things will happen if you use
225 // different SQL with the same ID.
226 //
227 // You will normally use the SQL_FROM_HERE macro to generate a statement
228 // ID associated with the current line of code. This gives uniqueness without
229 // you having to manage unique names. See StatementID above for more.
230 //
231 // Example:
[email protected]3273dce2010-01-27 16:08:08232 // sql::Statement stmt(connection_.GetCachedStatement(
233 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56234 // if (!stmt)
235 // return false; // Error creating statement.
236 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
237 const char* sql);
238
239 // Returns a non-cached statement for the given SQL. Use this for SQL that
240 // is only executed once or only rarely (there is overhead associated with
241 // keeping a statement cached).
242 //
243 // See GetCachedStatement above for examples and error information.
244 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
245
246 // Info querying -------------------------------------------------------------
247
248 // Returns true if the given table exists.
[email protected]765b44502009-10-02 05:01:42249 bool DoesTableExist(const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56250
251 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17252 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56253
254 // Returns sqlite's internal ID for the last inserted row. Valid only
255 // immediately after an insert.
256 int64 GetLastInsertRowId() const;
257
[email protected]1ed78a32009-09-15 20:24:17258 // Returns sqlite's count of the number of rows modified by the last
259 // statement executed. Will be 0 if no statement has executed or the database
260 // is closed.
261 int GetLastChangeCount() const;
262
[email protected]e5ffd0e42009-09-11 21:30:56263 // Errors --------------------------------------------------------------------
264
265 // Returns the error code associated with the last sqlite operation.
266 int GetErrorCode() const;
267
[email protected]767718e52010-09-21 23:18:49268 // Returns the errno associated with GetErrorCode(). See
269 // SQLITE_LAST_ERRNO in SQLite documentation.
270 int GetLastErrno() const;
271
[email protected]e5ffd0e42009-09-11 21:30:56272 // Returns a pointer to a statically allocated string associated with the
273 // last sqlite operation.
274 const char* GetErrorMessage() const;
275
276 private:
277 // Statement access StatementRef which we don't want to expose to erverybody
278 // (they should go through Statement).
279 friend class Statement;
280
[email protected]765b44502009-10-02 05:01:42281 // Internal initialize function used by both Init and InitInMemory. The file
282 // name is always 8 bits since we want to use the 8-bit version of
283 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
284 bool OpenInternal(const std::string& file_name);
285
[email protected]e5ffd0e42009-09-11 21:30:56286 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
287 // Refcounting allows us to give these statements out to sql::Statement
288 // objects while also optionally maintaining a cache of compiled statements
289 // by just keeping a refptr to these objects.
290 //
291 // A statement ref can be valid, in which case it can be used, or invalid to
292 // indicate that the statement hasn't been created yet, has an error, or has
293 // been destroyed.
294 //
295 // The Connection may revoke a StatementRef in some error cases, so callers
296 // should always check validity before using.
297 class StatementRef : public base::RefCounted<StatementRef> {
298 public:
299 // Default constructor initializes to an invalid statement.
300 StatementRef();
301 StatementRef(Connection* connection, sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56302
303 // When true, the statement can be used.
304 bool is_valid() const { return !!stmt_; }
305
306 // If we've not been linked to a connection, this will be NULL. Guaranteed
307 // non-NULL when is_valid().
308 Connection* connection() const { return connection_; }
309
310 // Returns the sqlite statement if any. If the statement is not active,
311 // this will return NULL.
312 sqlite3_stmt* stmt() const { return stmt_; }
313
314 // Destroys the compiled statement and marks it NULL. The statement will
315 // no longer be active.
316 void Close();
317
318 private:
[email protected]877d55d2009-11-05 21:53:08319 friend class base::RefCounted<StatementRef>;
320
321 ~StatementRef();
322
[email protected]e5ffd0e42009-09-11 21:30:56323 Connection* connection_;
324 sqlite3_stmt* stmt_;
325
326 DISALLOW_COPY_AND_ASSIGN(StatementRef);
327 };
328 friend class StatementRef;
329
330 // Executes a rollback statement, ignoring all transaction state. Used
331 // internally in the transaction management code.
332 void DoRollback();
333
334 // Called by a StatementRef when it's being created or destroyed. See
335 // open_statements_ below.
336 void StatementRefCreated(StatementRef* ref);
337 void StatementRefDeleted(StatementRef* ref);
338
339 // Frees all cached statements from statement_cache_.
340 void ClearCache();
341
[email protected]faa604e2009-09-25 22:38:59342 // Called by Statement objects when an sqlite function returns an error.
343 // The return value is the error code reflected back to client code.
344 int OnSqliteError(int err, Statement* stmt);
345
[email protected]5b96f3772010-09-28 16:30:57346 // Like |Execute()|, but retries if the database is locked.
347 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout);
348
[email protected]e5ffd0e42009-09-11 21:30:56349 // The actual sqlite database. Will be NULL before Init has been called or if
350 // Init resulted in an error.
351 sqlite3* db_;
352
353 // Parameters we'll configure in sqlite before doing anything else. Zero means
354 // use the default value.
355 int page_size_;
356 int cache_size_;
357 bool exclusive_locking_;
358
359 // All cached statements. Keeping a reference to these statements means that
360 // they'll remain active.
361 typedef std::map<StatementID, scoped_refptr<StatementRef> >
362 CachedStatementMap;
363 CachedStatementMap statement_cache_;
364
365 // A list of all StatementRefs we've given out. Each ref must register with
366 // us when it's created or destroyed. This allows us to potentially close
367 // any open statements when we encounter an error.
368 typedef std::set<StatementRef*> StatementRefSet;
369 StatementRefSet open_statements_;
370
371 // Number of currently-nested transactions.
372 int transaction_nesting_;
373
374 // True if any of the currently nested transactions have been rolled back.
375 // When we get to the outermost transaction, this will determine if we do
376 // a rollback instead of a commit.
377 bool needs_rollback_;
378
[email protected]faa604e2009-09-25 22:38:59379 // This object handles errors resulting from all forms of executing sqlite
380 // commands or statements. It can be null which means default handling.
381 scoped_refptr<ErrorDelegate> error_delegate_;
382
[email protected]e5ffd0e42009-09-11 21:30:56383 DISALLOW_COPY_AND_ASSIGN(Connection);
384};
385
386} // namespace sql
387
[email protected]f0a54b22011-07-19 18:40:21388#endif // SQL_CONNECTION_H_