blob: 39b999bd3171d729fcf452b87df01374c950f6c2 [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).
[email protected]eff1fa522011-12-12 23:50:59207 // This will DCHECK if the |sql| contains errors.
[email protected]e5ffd0e42009-09-11 21:30:56208 bool Execute(const char* sql);
209
[email protected]eff1fa522011-12-12 23:50:59210 // Like Execute(), but returns the error code given by SQLite.
211 int ExecuteAndReturnErrorCode(const char* sql);
212
[email protected]e5ffd0e42009-09-11 21:30:56213 // Returns true if we have a statement with the given identifier already
214 // cached. This is normally not necessary to call, but can be useful if the
215 // caller has to dynamically build up SQL to avoid doing so if it's already
216 // cached.
217 bool HasCachedStatement(const StatementID& id) const;
218
219 // Returns a statement for the given SQL using the statement cache. It can
220 // take a nontrivial amount of work to parse and compile a statement, so
221 // keeping commonly-used ones around for future use is important for
222 // performance.
223 //
[email protected]eff1fa522011-12-12 23:50:59224 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
225 // the code will crash in debug). The caller must deal with this eventuality,
226 // either by checking validity of the |sql| before calling, by correctly
227 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56228 //
229 // The StatementID and the SQL must always correspond to one-another. The
230 // ID is the lookup into the cache, so crazy things will happen if you use
231 // different SQL with the same ID.
232 //
233 // You will normally use the SQL_FROM_HERE macro to generate a statement
234 // ID associated with the current line of code. This gives uniqueness without
235 // you having to manage unique names. See StatementID above for more.
236 //
237 // Example:
[email protected]3273dce2010-01-27 16:08:08238 // sql::Statement stmt(connection_.GetCachedStatement(
239 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56240 // if (!stmt)
241 // return false; // Error creating statement.
242 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
243 const char* sql);
244
[email protected]eff1fa522011-12-12 23:50:59245 // Used to check a |sql| statement for syntactic validity. If the statement is
246 // valid SQL, returns true.
247 bool IsSQLValid(const char* sql);
248
[email protected]e5ffd0e42009-09-11 21:30:56249 // Returns a non-cached statement for the given SQL. Use this for SQL that
250 // is only executed once or only rarely (there is overhead associated with
251 // keeping a statement cached).
252 //
253 // See GetCachedStatement above for examples and error information.
254 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
255
256 // Info querying -------------------------------------------------------------
257
258 // Returns true if the given table exists.
[email protected]765b44502009-10-02 05:01:42259 bool DoesTableExist(const char* table_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56260
[email protected]e2cadec82011-12-13 02:00:53261 // Returns true if the given index exists.
262 bool DoesIndexExist(const char* index_name) const;
263
[email protected]e5ffd0e42009-09-11 21:30:56264 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17265 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56266
267 // Returns sqlite's internal ID for the last inserted row. Valid only
268 // immediately after an insert.
269 int64 GetLastInsertRowId() const;
270
[email protected]1ed78a32009-09-15 20:24:17271 // Returns sqlite's count of the number of rows modified by the last
272 // statement executed. Will be 0 if no statement has executed or the database
273 // is closed.
274 int GetLastChangeCount() const;
275
[email protected]e5ffd0e42009-09-11 21:30:56276 // Errors --------------------------------------------------------------------
277
278 // Returns the error code associated with the last sqlite operation.
279 int GetErrorCode() const;
280
[email protected]767718e52010-09-21 23:18:49281 // Returns the errno associated with GetErrorCode(). See
282 // SQLITE_LAST_ERRNO in SQLite documentation.
283 int GetLastErrno() const;
284
[email protected]e5ffd0e42009-09-11 21:30:56285 // Returns a pointer to a statically allocated string associated with the
286 // last sqlite operation.
287 const char* GetErrorMessage() const;
288
289 private:
[email protected]eff1fa522011-12-12 23:50:59290 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56291 // (they should go through Statement).
292 friend class Statement;
293
[email protected]765b44502009-10-02 05:01:42294 // Internal initialize function used by both Init and InitInMemory. The file
295 // name is always 8 bits since we want to use the 8-bit version of
296 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
297 bool OpenInternal(const std::string& file_name);
298
[email protected]e2cadec82011-12-13 02:00:53299 // Internal helper for DoesTableExist and DoesIndexExist.
300 bool DoesTableOrIndexExist(const char* name, const char* type) const;
301
[email protected]e5ffd0e42009-09-11 21:30:56302 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
303 // Refcounting allows us to give these statements out to sql::Statement
304 // objects while also optionally maintaining a cache of compiled statements
305 // by just keeping a refptr to these objects.
306 //
307 // A statement ref can be valid, in which case it can be used, or invalid to
308 // indicate that the statement hasn't been created yet, has an error, or has
309 // been destroyed.
310 //
311 // The Connection may revoke a StatementRef in some error cases, so callers
312 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23313 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56314 public:
315 // Default constructor initializes to an invalid statement.
316 StatementRef();
317 StatementRef(Connection* connection, sqlite3_stmt* stmt);
[email protected]e5ffd0e42009-09-11 21:30:56318
319 // When true, the statement can be used.
320 bool is_valid() const { return !!stmt_; }
321
322 // If we've not been linked to a connection, this will be NULL. Guaranteed
323 // non-NULL when is_valid().
324 Connection* connection() const { return connection_; }
325
326 // Returns the sqlite statement if any. If the statement is not active,
327 // this will return NULL.
328 sqlite3_stmt* stmt() const { return stmt_; }
329
330 // Destroys the compiled statement and marks it NULL. The statement will
331 // no longer be active.
332 void Close();
333
334 private:
[email protected]877d55d2009-11-05 21:53:08335 friend class base::RefCounted<StatementRef>;
336
337 ~StatementRef();
338
[email protected]e5ffd0e42009-09-11 21:30:56339 Connection* connection_;
340 sqlite3_stmt* stmt_;
341
342 DISALLOW_COPY_AND_ASSIGN(StatementRef);
343 };
344 friend class StatementRef;
345
346 // Executes a rollback statement, ignoring all transaction state. Used
347 // internally in the transaction management code.
348 void DoRollback();
349
350 // Called by a StatementRef when it's being created or destroyed. See
351 // open_statements_ below.
352 void StatementRefCreated(StatementRef* ref);
353 void StatementRefDeleted(StatementRef* ref);
354
355 // Frees all cached statements from statement_cache_.
356 void ClearCache();
357
[email protected]faa604e2009-09-25 22:38:59358 // Called by Statement objects when an sqlite function returns an error.
359 // The return value is the error code reflected back to client code.
360 int OnSqliteError(int err, Statement* stmt);
361
[email protected]5b96f3772010-09-28 16:30:57362 // Like |Execute()|, but retries if the database is locked.
363 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout);
364
[email protected]e5ffd0e42009-09-11 21:30:56365 // The actual sqlite database. Will be NULL before Init has been called or if
366 // Init resulted in an error.
367 sqlite3* db_;
368
369 // Parameters we'll configure in sqlite before doing anything else. Zero means
370 // use the default value.
371 int page_size_;
372 int cache_size_;
373 bool exclusive_locking_;
374
375 // All cached statements. Keeping a reference to these statements means that
376 // they'll remain active.
377 typedef std::map<StatementID, scoped_refptr<StatementRef> >
378 CachedStatementMap;
379 CachedStatementMap statement_cache_;
380
381 // A list of all StatementRefs we've given out. Each ref must register with
382 // us when it's created or destroyed. This allows us to potentially close
383 // any open statements when we encounter an error.
384 typedef std::set<StatementRef*> StatementRefSet;
385 StatementRefSet open_statements_;
386
387 // Number of currently-nested transactions.
388 int transaction_nesting_;
389
390 // True if any of the currently nested transactions have been rolled back.
391 // When we get to the outermost transaction, this will determine if we do
392 // a rollback instead of a commit.
393 bool needs_rollback_;
394
[email protected]faa604e2009-09-25 22:38:59395 // This object handles errors resulting from all forms of executing sqlite
396 // commands or statements. It can be null which means default handling.
397 scoped_refptr<ErrorDelegate> error_delegate_;
398
[email protected]e5ffd0e42009-09-11 21:30:56399 DISALLOW_COPY_AND_ASSIGN(Connection);
400};
401
402} // namespace sql
403
[email protected]f0a54b22011-07-19 18:40:21404#endif // SQL_CONNECTION_H_