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