blob: 9b81804bc1fafb68bac8bfb9a63dff4c6887305c [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]9fe37552011-12-23 17:07:2014#include "base/compiler_specific.h"
[email protected]3b63f8f42011-03-28 01:54:1515#include "base/memory/ref_counted.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
184 // Transactions --------------------------------------------------------------
185
186 // Transaction management. We maintain a virtual transaction stack to emulate
187 // nested transactions since sqlite can't do nested transactions. The
188 // limitation is you can't roll back a sub transaction: if any transaction
189 // fails, all transactions open will also be rolled back. Any nested
190 // transactions after one has rolled back will return fail for Begin(). If
191 // Begin() fails, you must not call Commit or Rollback().
192 //
193 // Normally you should use sql::Transaction to manage a transaction, which
194 // will scope it to a C++ context.
195 bool BeginTransaction();
196 void RollbackTransaction();
197 bool CommitTransaction();
198
199 // Returns the current transaction nesting, which will be 0 if there are
200 // no open transactions.
201 int transaction_nesting() const { return transaction_nesting_; }
202
203 // Statements ----------------------------------------------------------------
204
205 // Executes the given SQL string, returning true on success. This is
206 // normally used for simple, 1-off statements that don't take any bound
207 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20208 //
[email protected]eff1fa522011-12-12 23:50:59209 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20210 //
211 // Do not use ignore_result() to ignore all errors. Use
212 // ExecuteAndReturnErrorCode() and ignore only specific errors.
213 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56214
[email protected]eff1fa522011-12-12 23:50:59215 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20216 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59217
[email protected]e5ffd0e42009-09-11 21:30:56218 // Returns true if we have a statement with the given identifier already
219 // cached. This is normally not necessary to call, but can be useful if the
220 // caller has to dynamically build up SQL to avoid doing so if it's already
221 // cached.
222 bool HasCachedStatement(const StatementID& id) const;
223
224 // Returns a statement for the given SQL using the statement cache. It can
225 // take a nontrivial amount of work to parse and compile a statement, so
226 // keeping commonly-used ones around for future use is important for
227 // performance.
228 //
[email protected]eff1fa522011-12-12 23:50:59229 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
230 // the code will crash in debug). The caller must deal with this eventuality,
231 // either by checking validity of the |sql| before calling, by correctly
232 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56233 //
234 // The StatementID and the SQL must always correspond to one-another. The
235 // ID is the lookup into the cache, so crazy things will happen if you use
236 // different SQL with the same ID.
237 //
238 // You will normally use the SQL_FROM_HERE macro to generate a statement
239 // ID associated with the current line of code. This gives uniqueness without
240 // you having to manage unique names. See StatementID above for more.
241 //
242 // Example:
[email protected]3273dce2010-01-27 16:08:08243 // sql::Statement stmt(connection_.GetCachedStatement(
244 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56245 // if (!stmt)
246 // return false; // Error creating statement.
247 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
248 const char* sql);
249
[email protected]eff1fa522011-12-12 23:50:59250 // Used to check a |sql| statement for syntactic validity. If the statement is
251 // valid SQL, returns true.
252 bool IsSQLValid(const char* sql);
253
[email protected]e5ffd0e42009-09-11 21:30:56254 // Returns a non-cached statement for the given SQL. Use this for SQL that
255 // is only executed once or only rarely (there is overhead associated with
256 // keeping a statement cached).
257 //
258 // See GetCachedStatement above for examples and error information.
259 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
260
261 // Info querying -------------------------------------------------------------
262
263 // Returns true if the given table exists.
[email protected]765b44502009-10-02 05:01:42264 bool DoesTableExist(const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56265
[email protected]e2cadec82011-12-13 02:00:53266 // Returns true if the given index exists.
267 bool DoesIndexExist(const char* index_name) const;
268
[email protected]e5ffd0e42009-09-11 21:30:56269 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17270 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56271
272 // Returns sqlite's internal ID for the last inserted row. Valid only
273 // immediately after an insert.
274 int64 GetLastInsertRowId() const;
275
[email protected]1ed78a32009-09-15 20:24:17276 // Returns sqlite's count of the number of rows modified by the last
277 // statement executed. Will be 0 if no statement has executed or the database
278 // is closed.
279 int GetLastChangeCount() const;
280
[email protected]e5ffd0e42009-09-11 21:30:56281 // Errors --------------------------------------------------------------------
282
283 // Returns the error code associated with the last sqlite operation.
284 int GetErrorCode() const;
285
[email protected]767718e52010-09-21 23:18:49286 // Returns the errno associated with GetErrorCode(). See
287 // SQLITE_LAST_ERRNO in SQLite documentation.
288 int GetLastErrno() const;
289
[email protected]e5ffd0e42009-09-11 21:30:56290 // Returns a pointer to a statically allocated string associated with the
291 // last sqlite operation.
292 const char* GetErrorMessage() const;
293
294 private:
[email protected]eff1fa522011-12-12 23:50:59295 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56296 // (they should go through Statement).
297 friend class Statement;
298
[email protected]765b44502009-10-02 05:01:42299 // Internal initialize function used by both Init and InitInMemory. The file
300 // name is always 8 bits since we want to use the 8-bit version of
301 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
302 bool OpenInternal(const std::string& file_name);
303
[email protected]e2cadec82011-12-13 02:00:53304 // Internal helper for DoesTableExist and DoesIndexExist.
305 bool DoesTableOrIndexExist(const char* name, const char* type) const;
306
[email protected]e5ffd0e42009-09-11 21:30:56307 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
308 // Refcounting allows us to give these statements out to sql::Statement
309 // objects while also optionally maintaining a cache of compiled statements
310 // by just keeping a refptr to these objects.
311 //
312 // A statement ref can be valid, in which case it can be used, or invalid to
313 // indicate that the statement hasn't been created yet, has an error, or has
314 // been destroyed.
315 //
316 // The Connection may revoke a StatementRef in some error cases, so callers
317 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23318 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56319 public:
320 // Default constructor initializes to an invalid statement.
321 StatementRef();
322 StatementRef(Connection* connection, sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56323
324 // When true, the statement can be used.
325 bool is_valid() const { return !!stmt_; }
326
327 // If we've not been linked to a connection, this will be NULL. Guaranteed
328 // non-NULL when is_valid().
329 Connection* connection() const { return connection_; }
330
331 // Returns the sqlite statement if any. If the statement is not active,
332 // this will return NULL.
333 sqlite3_stmt* stmt() const { return stmt_; }
334
335 // Destroys the compiled statement and marks it NULL. The statement will
336 // no longer be active.
337 void Close();
338
339 private:
[email protected]877d55d2009-11-05 21:53:08340 friend class base::RefCounted<StatementRef>;
341
342 ~StatementRef();
343
[email protected]e5ffd0e42009-09-11 21:30:56344 Connection* connection_;
345 sqlite3_stmt* stmt_;
346
347 DISALLOW_COPY_AND_ASSIGN(StatementRef);
348 };
349 friend class StatementRef;
350
351 // Executes a rollback statement, ignoring all transaction state. Used
352 // internally in the transaction management code.
353 void DoRollback();
354
355 // Called by a StatementRef when it's being created or destroyed. See
356 // open_statements_ below.
357 void StatementRefCreated(StatementRef* ref);
358 void StatementRefDeleted(StatementRef* ref);
359
360 // Frees all cached statements from statement_cache_.
361 void ClearCache();
362
[email protected]faa604e2009-09-25 22:38:59363 // Called by Statement objects when an sqlite function returns an error.
364 // The return value is the error code reflected back to client code.
365 int OnSqliteError(int err, Statement* stmt);
366
[email protected]5b96f3772010-09-28 16:30:57367 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20368 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
369 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57370
[email protected]e5ffd0e42009-09-11 21:30:56371 // The actual sqlite database. Will be NULL before Init has been called or if
372 // Init resulted in an error.
373 sqlite3* db_;
374
375 // Parameters we'll configure in sqlite before doing anything else. Zero means
376 // use the default value.
377 int page_size_;
378 int cache_size_;
379 bool exclusive_locking_;
380
381 // All cached statements. Keeping a reference to these statements means that
382 // they'll remain active.
383 typedef std::map<StatementID, scoped_refptr<StatementRef> >
384 CachedStatementMap;
385 CachedStatementMap statement_cache_;
386
387 // A list of all StatementRefs we've given out. Each ref must register with
388 // us when it's created or destroyed. This allows us to potentially close
389 // any open statements when we encounter an error.
390 typedef std::set<StatementRef*> StatementRefSet;
391 StatementRefSet open_statements_;
392
393 // Number of currently-nested transactions.
394 int transaction_nesting_;
395
396 // True if any of the currently nested transactions have been rolled back.
397 // When we get to the outermost transaction, this will determine if we do
398 // a rollback instead of a commit.
399 bool needs_rollback_;
400
[email protected]faa604e2009-09-25 22:38:59401 // This object handles errors resulting from all forms of executing sqlite
402 // commands or statements. It can be null which means default handling.
403 scoped_refptr<ErrorDelegate> error_delegate_;
404
[email protected]e5ffd0e42009-09-11 21:30:56405 DISALLOW_COPY_AND_ASSIGN(Connection);
406};
407
408} // namespace sql
409
[email protected]f0a54b22011-07-19 18:40:21410#endif // SQL_CONNECTION_H_