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