blob: 2a971e58326aadc5deac8eb0730f347992066e24 [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 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#include "sql/connection.h"
[email protected]e5ffd0e42009-09-11 21:30:566
7#include <string.h>
8
[email protected]57999812013-02-24 05:40:529#include "base/files/file_path.h"
[email protected]348ac8f52013-05-21 03:27:0210#include "base/file_util.h"
[email protected]e5ffd0e42009-09-11 21:30:5611#include "base/logging.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5012#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3913#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4214#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1915#include "base/strings/string_util.h"
16#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4517#include "base/strings/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2118#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0319#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5620
[email protected]2e1cee762013-07-09 14:40:0021#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
22#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
23#endif
24
[email protected]5b96f3772010-09-28 16:30:5725namespace {
26
27// Spin for up to a second waiting for the lock to clear when setting
28// up the database.
29// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2730const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5731
32class ScopedBusyTimeout {
33 public:
34 explicit ScopedBusyTimeout(sqlite3* db)
35 : db_(db) {
36 }
37 ~ScopedBusyTimeout() {
38 sqlite3_busy_timeout(db_, 0);
39 }
40
41 int SetTimeout(base::TimeDelta timeout) {
42 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
43 return sqlite3_busy_timeout(db_,
44 static_cast<int>(timeout.InMilliseconds()));
45 }
46
47 private:
48 sqlite3* db_;
49};
50
[email protected]6d42f152012-11-10 00:38:2451// Helper to "safely" enable writable_schema. No error checking
52// because it is reasonable to just forge ahead in case of an error.
53// If turning it on fails, then most likely nothing will work, whereas
54// if turning it off fails, it only matters if some code attempts to
55// continue working with the database and tries to modify the
56// sqlite_master table (none of our code does this).
57class ScopedWritableSchema {
58 public:
59 explicit ScopedWritableSchema(sqlite3* db)
60 : db_(db) {
61 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
62 }
63 ~ScopedWritableSchema() {
64 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
65 }
66
67 private:
68 sqlite3* db_;
69};
70
[email protected]5b96f3772010-09-28 16:30:5771} // namespace
72
[email protected]e5ffd0e42009-09-11 21:30:5673namespace sql {
74
[email protected]4350e322013-06-18 22:18:1075// static
76Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
77
78// static
79bool Connection::ShouldIgnore(int error) {
80 if (!current_ignorer_cb_)
81 return false;
82 return current_ignorer_cb_->Run(error);
83}
84
85// static
86void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
87 CHECK(current_ignorer_cb_ == NULL);
88 current_ignorer_cb_ = cb;
89}
90
91// static
92void Connection::ResetErrorIgnorer() {
93 CHECK(current_ignorer_cb_);
94 current_ignorer_cb_ = NULL;
95}
96
[email protected]e5ffd0e42009-09-11 21:30:5697bool StatementID::operator<(const StatementID& other) const {
98 if (number_ != other.number_)
99 return number_ < other.number_;
100 return strcmp(str_, other.str_) < 0;
101}
102
[email protected]e5ffd0e42009-09-11 21:30:56103Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38104 sqlite3_stmt* stmt,
105 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56106 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38107 stmt_(stmt),
108 was_valid_(was_valid) {
109 if (connection)
110 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56111}
112
113Connection::StatementRef::~StatementRef() {
114 if (connection_)
115 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38116 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56117}
118
[email protected]41a97c812013-02-07 02:35:38119void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56120 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50121 // Call to AssertIOAllowed() cannot go at the beginning of the function
122 // because Close() is called unconditionally from destructor to clean
123 // connection_. And if this is inactive statement this won't cause any
124 // disk access and destructor most probably will be called on thread
125 // not allowing disk access.
126 // TODO([email protected]): This should move to the beginning
127 // of the function. http://crbug.com/136655.
128 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56129 sqlite3_finalize(stmt_);
130 stmt_ = NULL;
131 }
132 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38133
134 // Forced close is expected to happen from a statement error
135 // handler. In that case maintain the sense of |was_valid_| which
136 // previously held for this ref.
137 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56138}
139
140Connection::Connection()
141 : db_(NULL),
142 page_size_(0),
143 cache_size_(0),
144 exclusive_locking_(false),
145 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50146 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16147 in_memory_(false),
[email protected]526b4662013-06-14 04:09:12148 poisoned_(false) {
149}
[email protected]e5ffd0e42009-09-11 21:30:56150
151Connection::~Connection() {
152 Close();
153}
154
[email protected]a3ef4832013-02-02 05:12:33155bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02156 if (!histogram_tag_.empty()) {
157 int64 size_64 = 0;
158 if (file_util::GetFileSize(path, &size_64)) {
159 size_t sample = static_cast<size_t>(size_64 / 1024);
160 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
161 base::HistogramBase* histogram =
162 base::Histogram::FactoryGet(
163 full_histogram_name, 1, 1000000, 50,
164 base::HistogramBase::kUmaTargetedHistogramFlag);
165 if (histogram)
166 histogram->Add(sample);
167 }
168 }
169
[email protected]e5ffd0e42009-09-11 21:30:56170#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42171 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56172#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42173 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56174#endif
[email protected]765b44502009-10-02 05:01:42175}
[email protected]e5ffd0e42009-09-11 21:30:56176
[email protected]765b44502009-10-02 05:01:42177bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50178 in_memory_ = true;
[email protected]765b44502009-10-02 05:01:42179 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56180}
181
[email protected]41a97c812013-02-07 02:35:38182void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47183 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
184 // will delete the -journal file. For ChromiumOS or other more
185 // embedded systems, this is probably not appropriate, whereas on
186 // desktop it might make some sense.
187
[email protected]4b350052012-02-24 20:40:48188 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48189
[email protected]41a97c812013-02-07 02:35:38190 // Release cached statements.
191 statement_cache_.clear();
192
193 // With cached statements released, in-use statements will remain.
194 // Closing the database while statements are in use is an API
195 // violation, except for forced close (which happens from within a
196 // statement's error handler).
197 DCHECK(forced || open_statements_.empty());
198
199 // Deactivate any outstanding statements so sqlite3_close() works.
200 for (StatementRefSet::iterator i = open_statements_.begin();
201 i != open_statements_.end(); ++i)
202 (*i)->Close(forced);
203 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48204
[email protected]e5ffd0e42009-09-11 21:30:56205 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50206 // Call to AssertIOAllowed() cannot go at the beginning of the function
207 // because Close() must be called from destructor to clean
208 // statement_cache_, it won't cause any disk access and it most probably
209 // will happen on thread not allowing disk access.
210 // TODO([email protected]): This should move to the beginning
211 // of the function. http://crbug.com/136655.
212 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48213 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56214 sqlite3_close(db_);
215 db_ = NULL;
216 }
217}
218
[email protected]41a97c812013-02-07 02:35:38219void Connection::Close() {
220 // If the database was already closed by RazeAndClose(), then no
221 // need to close again. Clear the |poisoned_| bit so that incorrect
222 // API calls are caught.
223 if (poisoned_) {
224 poisoned_ = false;
225 return;
226 }
227
228 CloseInternal(false);
229}
230
[email protected]e5ffd0e42009-09-11 21:30:56231void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50232 AssertIOAllowed();
233
[email protected]e5ffd0e42009-09-11 21:30:56234 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38235 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56236 return;
237 }
238
239 // A statement must be open for the preload command to work. If the meta
240 // table doesn't exist, it probably means this is a new database and there
241 // is nothing to preload (so it's OK we do nothing).
242 if (!DoesTableExist("meta"))
243 return;
244 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59245 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56246 return;
247
[email protected]4176eee4b2011-01-26 14:33:32248#if !defined(USE_SYSTEM_SQLITE)
249 // This function is only defined in Chromium's version of sqlite.
250 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06251 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32252#endif
[email protected]e5ffd0e42009-09-11 21:30:56253}
254
[email protected]8e0c01282012-04-06 19:36:49255// Create an in-memory database with the existing database's page
256// size, then backup that database over the existing database.
257bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50258 AssertIOAllowed();
259
[email protected]8e0c01282012-04-06 19:36:49260 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38261 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49262 return false;
263 }
264
265 if (transaction_nesting_ > 0) {
266 DLOG(FATAL) << "Cannot raze within a transaction";
267 return false;
268 }
269
270 sql::Connection null_db;
271 if (!null_db.OpenInMemory()) {
272 DLOG(FATAL) << "Unable to open in-memory database.";
273 return false;
274 }
275
[email protected]6d42f152012-11-10 00:38:24276 if (page_size_) {
277 // Enforce SQLite restrictions on |page_size_|.
278 DCHECK(!(page_size_ & (page_size_ - 1)))
279 << " page_size_ " << page_size_ << " is not a power of two.";
280 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
281 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04282 const std::string sql =
283 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42284 if (!null_db.Execute(sql.c_str()))
285 return false;
286 }
287
[email protected]6d42f152012-11-10 00:38:24288#if defined(OS_ANDROID)
289 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
290 // in-memory databases do not respect this define.
291 // TODO(shess): Figure out a way to set this without using platform
292 // specific code. AFAICT from sqlite3.c, the only way to do it
293 // would be to create an actual filesystem database, which is
294 // unfortunate.
295 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
296 return false;
297#endif
[email protected]8e0c01282012-04-06 19:36:49298
299 // The page size doesn't take effect until a database has pages, and
300 // at this point the null database has none. Changing the schema
301 // version will create the first page. This will not affect the
302 // schema version in the resulting database, as SQLite's backup
303 // implementation propagates the schema version from the original
304 // connection to the new version of the database, incremented by one
305 // so that other readers see the schema change and act accordingly.
306 if (!null_db.Execute("PRAGMA schema_version = 1"))
307 return false;
308
[email protected]6d42f152012-11-10 00:38:24309 // SQLite tracks the expected number of database pages in the first
310 // page, and if it does not match the total retrieved from a
311 // filesystem call, treats the database as corrupt. This situation
312 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
313 // used to hint to SQLite to soldier on in that case, specifically
314 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
315 // sqlite3.c lockBtree().]
316 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
317 // page_size" can be used to query such a database.
318 ScopedWritableSchema writable_schema(db_);
319
[email protected]8e0c01282012-04-06 19:36:49320 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
321 null_db.db_, "main");
322 if (!backup) {
323 DLOG(FATAL) << "Unable to start sqlite3_backup().";
324 return false;
325 }
326
327 // -1 backs up the entire database.
328 int rc = sqlite3_backup_step(backup, -1);
329 int pages = sqlite3_backup_pagecount(backup);
330 sqlite3_backup_finish(backup);
331
332 // The destination database was locked.
333 if (rc == SQLITE_BUSY) {
334 return false;
335 }
336
337 // The entire database should have been backed up.
338 if (rc != SQLITE_DONE) {
339 DLOG(FATAL) << "Unable to copy entire null database.";
340 return false;
341 }
342
343 // Exactly one page should have been backed up. If this breaks,
344 // check this function to make sure assumptions aren't being broken.
345 DCHECK_EQ(pages, 1);
346
347 return true;
348}
349
350bool Connection::RazeWithTimout(base::TimeDelta timeout) {
351 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38352 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49353 return false;
354 }
355
356 ScopedBusyTimeout busy_timeout(db_);
357 busy_timeout.SetTimeout(timeout);
358 return Raze();
359}
360
[email protected]41a97c812013-02-07 02:35:38361bool Connection::RazeAndClose() {
362 if (!db_) {
363 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
364 return false;
365 }
366
367 // Raze() cannot run in a transaction.
368 while (transaction_nesting_) {
369 RollbackTransaction();
370 }
371
372 bool result = Raze();
373
374 CloseInternal(true);
375
376 // Mark the database so that future API calls fail appropriately,
377 // but don't DCHECK (because after calling this function they are
378 // expected to fail).
379 poisoned_ = true;
380
381 return result;
382}
383
[email protected]8d2e39e2013-06-24 05:55:08384// TODO(shess): To the extent possible, figure out the optimal
385// ordering for these deletes which will prevent other connections
386// from seeing odd behavior. For instance, it may be necessary to
387// manually lock the main database file in a SQLite-compatible fashion
388// (to prevent other processes from opening it), then delete the
389// journal files, then delete the main database file. Another option
390// might be to lock the main database file and poison the header with
391// junk to prevent other processes from opening it successfully (like
392// Gears "SQLite poison 3" trick).
393//
394// static
395bool Connection::Delete(const base::FilePath& path) {
396 base::ThreadRestrictions::AssertIOAllowed();
397
398 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
399 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
400
[email protected]918efbf2013-07-01 19:41:02401 base::Delete(journal_path, false);
402 base::Delete(wal_path, false);
403 base::Delete(path, false);
[email protected]8d2e39e2013-06-24 05:55:08404
405 return !file_util::PathExists(journal_path) &&
406 !file_util::PathExists(wal_path) &&
407 !file_util::PathExists(path);
408}
409
[email protected]e5ffd0e42009-09-11 21:30:56410bool Connection::BeginTransaction() {
411 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33412 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56413
414 // When we're going to rollback, fail on this begin and don't actually
415 // mark us as entering the nested transaction.
416 return false;
417 }
418
419 bool success = true;
420 if (!transaction_nesting_) {
421 needs_rollback_ = false;
422
423 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59424 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56425 return false;
426 }
427 transaction_nesting_++;
428 return success;
429}
430
431void Connection::RollbackTransaction() {
432 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38433 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56434 return;
435 }
436
437 transaction_nesting_--;
438
439 if (transaction_nesting_ > 0) {
440 // Mark the outermost transaction as needing rollback.
441 needs_rollback_ = true;
442 return;
443 }
444
445 DoRollback();
446}
447
448bool Connection::CommitTransaction() {
449 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38450 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56451 return false;
452 }
453 transaction_nesting_--;
454
455 if (transaction_nesting_ > 0) {
456 // Mark any nested transactions as failing after we've already got one.
457 return !needs_rollback_;
458 }
459
460 if (needs_rollback_) {
461 DoRollback();
462 return false;
463 }
464
465 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56466 return commit.Run();
467}
468
[email protected]eff1fa522011-12-12 23:50:59469int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50470 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38471 if (!db_) {
472 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
473 return SQLITE_ERROR;
474 }
[email protected]eff1fa522011-12-12 23:50:59475 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
476}
477
478bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38479 if (!db_) {
480 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
481 return false;
482 }
483
[email protected]eff1fa522011-12-12 23:50:59484 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00485 if (error != SQLITE_OK)
486 error = OnSqliteError(error, NULL);
487
[email protected]28fe0ff2012-02-25 00:40:33488 // This needs to be a FATAL log because the error case of arriving here is
489 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:10490 // a change alters the schema but not all queries adjust. This can happen
491 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:59492 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33493 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59494 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56495}
496
[email protected]5b96f3772010-09-28 16:30:57497bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38498 if (!db_) {
499 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57500 return false;
[email protected]41a97c812013-02-07 02:35:38501 }
[email protected]5b96f3772010-09-28 16:30:57502
503 ScopedBusyTimeout busy_timeout(db_);
504 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59505 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57506}
507
[email protected]e5ffd0e42009-09-11 21:30:56508bool Connection::HasCachedStatement(const StatementID& id) const {
509 return statement_cache_.find(id) != statement_cache_.end();
510}
511
512scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
513 const StatementID& id,
514 const char* sql) {
515 CachedStatementMap::iterator i = statement_cache_.find(id);
516 if (i != statement_cache_.end()) {
517 // Statement is in the cache. It should still be active (we're the only
518 // one invalidating cached statements, and we'll remove it from the cache
519 // if we do that. Make sure we reset it before giving out the cached one in
520 // case it still has some stuff bound.
521 DCHECK(i->second->is_valid());
522 sqlite3_reset(i->second->stmt());
523 return i->second;
524 }
525
526 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
527 if (statement->is_valid())
528 statement_cache_[id] = statement; // Only cache valid statements.
529 return statement;
530}
531
532scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
533 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50534 AssertIOAllowed();
535
[email protected]41a97c812013-02-07 02:35:38536 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56537 if (!db_)
[email protected]41a97c812013-02-07 02:35:38538 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56539
540 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00541 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
542 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59543 // This is evidence of a syntax error in the incoming SQL.
544 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00545
546 // It could also be database corruption.
547 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38548 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56549 }
[email protected]41a97c812013-02-07 02:35:38550 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56551}
552
[email protected]2eec0a22012-07-24 01:59:58553scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
554 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38555 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58556 if (!db_)
[email protected]41a97c812013-02-07 02:35:38557 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58558
559 sqlite3_stmt* stmt = NULL;
560 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
561 if (rc != SQLITE_OK) {
562 // This is evidence of a syntax error in the incoming SQL.
563 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38564 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58565 }
[email protected]41a97c812013-02-07 02:35:38566 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58567}
568
[email protected]eff1fa522011-12-12 23:50:59569bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50570 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38571 if (!db_) {
572 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
573 return false;
574 }
575
[email protected]eff1fa522011-12-12 23:50:59576 sqlite3_stmt* stmt = NULL;
577 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
578 return false;
579
580 sqlite3_finalize(stmt);
581 return true;
582}
583
[email protected]1ed78a32009-09-15 20:24:17584bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53585 return DoesTableOrIndexExist(table_name, "table");
586}
587
588bool Connection::DoesIndexExist(const char* index_name) const {
589 return DoesTableOrIndexExist(index_name, "index");
590}
591
592bool Connection::DoesTableOrIndexExist(
593 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58594 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
595 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53596 statement.BindString(0, type);
597 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33598
[email protected]e5ffd0e42009-09-11 21:30:56599 return statement.Step(); // Table exists if any row was returned.
600}
601
602bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17603 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56604 std::string sql("PRAGMA TABLE_INFO(");
605 sql.append(table_name);
606 sql.append(")");
607
[email protected]2eec0a22012-07-24 01:59:58608 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56609 while (statement.Step()) {
610 if (!statement.ColumnString(1).compare(column_name))
611 return true;
612 }
613 return false;
614}
615
616int64 Connection::GetLastInsertRowId() const {
617 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38618 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56619 return 0;
620 }
621 return sqlite3_last_insert_rowid(db_);
622}
623
[email protected]1ed78a32009-09-15 20:24:17624int Connection::GetLastChangeCount() const {
625 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38626 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17627 return 0;
628 }
629 return sqlite3_changes(db_);
630}
631
[email protected]e5ffd0e42009-09-11 21:30:56632int Connection::GetErrorCode() const {
633 if (!db_)
634 return SQLITE_ERROR;
635 return sqlite3_errcode(db_);
636}
637
[email protected]767718e52010-09-21 23:18:49638int Connection::GetLastErrno() const {
639 if (!db_)
640 return -1;
641
642 int err = 0;
643 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
644 return -2;
645
646 return err;
647}
648
[email protected]e5ffd0e42009-09-11 21:30:56649const char* Connection::GetErrorMessage() const {
650 if (!db_)
651 return "sql::Connection has no connection.";
652 return sqlite3_errmsg(db_);
653}
654
[email protected]765b44502009-10-02 05:01:42655bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50656 AssertIOAllowed();
657
[email protected]9cfbc922009-11-17 20:13:17658 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59659 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17660 return false;
661 }
662
[email protected]41a97c812013-02-07 02:35:38663 // If |poisoned_| is set, it means an error handler called
664 // RazeAndClose(). Until regular Close() is called, the caller
665 // should be treating the database as open, but is_open() currently
666 // only considers the sqlite3 handle's state.
667 // TODO(shess): Revise is_open() to consider poisoned_, and review
668 // to see if any non-testing code even depends on it.
669 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
670
[email protected]765b44502009-10-02 05:01:42671 int err = sqlite3_open(file_name.c_str(), &db_);
672 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50673 // Histogram failures specific to initial open for debugging
674 // purposes.
675 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
676
[email protected]765b44502009-10-02 05:01:42677 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29678 Close();
[email protected]765b44502009-10-02 05:01:42679 db_ = NULL;
680 return false;
681 }
682
[email protected]affa2da2013-06-06 22:20:34683 // SQLite uses a lookaside buffer to improve performance of small mallocs.
684 // Chromium already depends on small mallocs being efficient, so we disable
685 // this to avoid the extra memory overhead.
686 // This must be called immediatly after opening the database before any SQL
687 // statements are run.
688 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
689
[email protected]bd2ccdb4a2012-12-07 22:14:50690 // sqlite3_open() does not actually read the database file (unless a
691 // hot journal is found). Successfully executing this pragma on an
692 // existing database requires a valid header on page 1.
693 // TODO(shess): For now, just probing to see what the lay of the
694 // land is. If it's mostly SQLITE_NOTADB, then the database should
695 // be razed.
696 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
697 if (err != SQLITE_OK)
698 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
699
[email protected]658f8332010-09-18 04:40:43700 // Enable extended result codes to provide more color on I/O errors.
701 // Not having extended result codes is not a fatal problem, as
702 // Chromium code does not attempt to handle I/O errors anyhow. The
703 // current implementation always returns SQLITE_OK, the DCHECK is to
704 // quickly notify someone if SQLite changes.
705 err = sqlite3_extended_result_codes(db_, 1);
706 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
707
[email protected]2e1cee762013-07-09 14:40:00708#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
709 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
710 // REGEXP support. Add it in dynamically.
711 err = sqlite3IcuInit(db_);
712 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
713#endif // OS_IOS && USE_SYSTEM_SQLITE
714
[email protected]5b96f3772010-09-28 16:30:57715 // If indicated, lock up the database before doing anything else, so
716 // that the following code doesn't have to deal with locking.
717 // TODO(shess): This code is brittle. Find the cases where code
718 // doesn't request |exclusive_locking_| and audit that it does the
719 // right thing with SQLITE_BUSY, and that it doesn't make
720 // assumptions about who might change things in the database.
721 // http://crbug.com/56559
722 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:10723 // TODO(shess): This should probably be a failure. Code which
724 // requests exclusive locking but doesn't get it is almost certain
725 // to be ill-tested.
726 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:57727 }
728
[email protected]4e179ba2012-03-17 16:06:47729 // http://www.sqlite.org/pragma.html#pragma_journal_mode
730 // DELETE (default) - delete -journal file to commit.
731 // TRUNCATE - truncate -journal file to commit.
732 // PERSIST - zero out header of -journal file to commit.
733 // journal_size_limit provides size to trim to in PERSIST.
734 // TODO(shess): Figure out if PERSIST and journal_size_limit really
735 // matter. In theory, it keeps pages pre-allocated, so if
736 // transactions usually fit, it should be faster.
737 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
738 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
739
[email protected]c68ce172011-11-24 22:30:27740 const base::TimeDelta kBusyTimeout =
741 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
742
[email protected]765b44502009-10-02 05:01:42743 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57744 // Enforce SQLite restrictions on |page_size_|.
745 DCHECK(!(page_size_ & (page_size_ - 1)))
746 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24747 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57748 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04749 const std::string sql =
750 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:10751 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:42752 }
753
754 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:04755 const std::string sql =
756 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:10757 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:42758 }
759
[email protected]6e0b1442011-08-09 23:23:58760 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]6e0b1442011-08-09 23:23:58761 Close();
762 return false;
763 }
764
[email protected]765b44502009-10-02 05:01:42765 return true;
766}
767
[email protected]e5ffd0e42009-09-11 21:30:56768void Connection::DoRollback() {
769 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59770 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05771 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56772}
773
774void Connection::StatementRefCreated(StatementRef* ref) {
775 DCHECK(open_statements_.find(ref) == open_statements_.end());
776 open_statements_.insert(ref);
777}
778
779void Connection::StatementRefDeleted(StatementRef* ref) {
780 StatementRefSet::iterator i = open_statements_.find(ref);
781 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59782 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56783 else
784 open_statements_.erase(i);
785}
786
[email protected]210ce0af2013-05-15 09:10:39787void Connection::AddTaggedHistogram(const std::string& name,
788 size_t sample) const {
789 if (histogram_tag_.empty())
790 return;
791
792 // TODO(shess): The histogram macros create a bit of static storage
793 // for caching the histogram object. This code shouldn't execute
794 // often enough for such caching to be crucial. If it becomes an
795 // issue, the object could be cached alongside histogram_prefix_.
796 std::string full_histogram_name = name + "." + histogram_tag_;
797 base::HistogramBase* histogram =
798 base::SparseHistogram::FactoryGet(
799 full_histogram_name,
800 base::HistogramBase::kUmaTargetedHistogramFlag);
801 if (histogram)
802 histogram->Add(sample);
803}
804
[email protected]faa604e2009-09-25 22:38:59805int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]210ce0af2013-05-15 09:10:39806 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
807 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:14808
809 // Always log the error.
810 LOG(ERROR) << "sqlite error " << err
811 << ", errno " << GetLastErrno()
812 << ": " << GetErrorMessage();
813
[email protected]c3881b372013-05-17 08:39:46814 if (!error_callback_.is_null()) {
815 error_callback_.Run(err, stmt);
816 return err;
817 }
818
[email protected]faa604e2009-09-25 22:38:59819 // The default handling is to assert on debug and to ignore on release.
[email protected]4350e322013-06-18 22:18:10820 if (!ShouldIgnore(err))
821 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59822 return err;
823}
824
[email protected]80abf152013-05-22 12:42:42825// TODO(shess): Allow specifying integrity_check versus quick_check.
826// TODO(shess): Allow specifying maximum results (default 100 lines).
827bool Connection::IntegrityCheck(std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:42828 messages->clear();
829
[email protected]4658e2a02013-06-06 23:05:00830 // This has the side effect of setting SQLITE_RecoveryMode, which
831 // allows SQLite to process through certain cases of corruption.
832 // Failing to set this pragma probably means that the database is
833 // beyond recovery.
834 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
835 if (!Execute(kWritableSchema))
836 return false;
837
838 bool ret = false;
839 {
840 const char kSql[] = "PRAGMA integrity_check";
841 sql::Statement stmt(GetUniqueStatement(kSql));
842
843 // The pragma appears to return all results (up to 100 by default)
844 // as a single string. This doesn't appear to be an API contract,
845 // it could return separate lines, so loop _and_ split.
846 while (stmt.Step()) {
847 std::string result(stmt.ColumnString(0));
848 base::SplitString(result, '\n', messages);
849 }
850 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:42851 }
[email protected]4658e2a02013-06-06 23:05:00852
853 // Best effort to put things back as they were before.
854 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
855 ignore_result(Execute(kNoWritableSchema));
856
857 return ret;
[email protected]80abf152013-05-22 12:42:42858}
859
[email protected]e5ffd0e42009-09-11 21:30:56860} // namespace sql