blob: 0fda72e8596ad8a1acced731e49b8686aea50f88 [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]e5ffd0e42009-09-11 21:30:5610#include "base/logging.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5011#include "base/metrics/histogram.h"
[email protected]e5ffd0e42009-09-11 21:30:5612#include "base/string_util.h"
[email protected]f0a54b22011-07-19 18:40:2113#include "base/stringprintf.h"
[email protected]d55194ca2010-03-11 18:25:4514#include "base/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2115#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0316#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5617
[email protected]5b96f3772010-09-28 16:30:5718namespace {
19
20// Spin for up to a second waiting for the lock to clear when setting
21// up the database.
22// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2723const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5724
25class ScopedBusyTimeout {
26 public:
27 explicit ScopedBusyTimeout(sqlite3* db)
28 : db_(db) {
29 }
30 ~ScopedBusyTimeout() {
31 sqlite3_busy_timeout(db_, 0);
32 }
33
34 int SetTimeout(base::TimeDelta timeout) {
35 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
36 return sqlite3_busy_timeout(db_,
37 static_cast<int>(timeout.InMilliseconds()));
38 }
39
40 private:
41 sqlite3* db_;
42};
43
[email protected]6d42f152012-11-10 00:38:2444// Helper to "safely" enable writable_schema. No error checking
45// because it is reasonable to just forge ahead in case of an error.
46// If turning it on fails, then most likely nothing will work, whereas
47// if turning it off fails, it only matters if some code attempts to
48// continue working with the database and tries to modify the
49// sqlite_master table (none of our code does this).
50class ScopedWritableSchema {
51 public:
52 explicit ScopedWritableSchema(sqlite3* db)
53 : db_(db) {
54 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
55 }
56 ~ScopedWritableSchema() {
57 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
58 }
59
60 private:
61 sqlite3* db_;
62};
63
[email protected]5b96f3772010-09-28 16:30:5764} // namespace
65
[email protected]e5ffd0e42009-09-11 21:30:5666namespace sql {
67
68bool StatementID::operator<(const StatementID& other) const {
69 if (number_ != other.number_)
70 return number_ < other.number_;
71 return strcmp(str_, other.str_) < 0;
72}
73
[email protected]d4799a32010-09-28 22:54:5874ErrorDelegate::~ErrorDelegate() {
75}
76
[email protected]e5ffd0e42009-09-11 21:30:5677Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:3878 sqlite3_stmt* stmt,
79 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:5680 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:3881 stmt_(stmt),
82 was_valid_(was_valid) {
83 if (connection)
84 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:5685}
86
87Connection::StatementRef::~StatementRef() {
88 if (connection_)
89 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:3890 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:5691}
92
[email protected]41a97c812013-02-07 02:35:3893void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:5694 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:5095 // Call to AssertIOAllowed() cannot go at the beginning of the function
96 // because Close() is called unconditionally from destructor to clean
97 // connection_. And if this is inactive statement this won't cause any
98 // disk access and destructor most probably will be called on thread
99 // not allowing disk access.
100 // TODO([email protected]): This should move to the beginning
101 // of the function. http://crbug.com/136655.
102 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56103 sqlite3_finalize(stmt_);
104 stmt_ = NULL;
105 }
106 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38107
108 // Forced close is expected to happen from a statement error
109 // handler. In that case maintain the sense of |was_valid_| which
110 // previously held for this ref.
111 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56112}
113
114Connection::Connection()
115 : db_(NULL),
116 page_size_(0),
117 cache_size_(0),
118 exclusive_locking_(false),
119 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50120 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16121 in_memory_(false),
[email protected]41a97c812013-02-07 02:35:38122 poisoned_(false),
[email protected]49dc4f22012-10-17 17:41:16123 error_delegate_(NULL) {
[email protected]e5ffd0e42009-09-11 21:30:56124}
125
126Connection::~Connection() {
127 Close();
128}
129
[email protected]a3ef4832013-02-02 05:12:33130bool Connection::Open(const base::FilePath& path) {
[email protected]e5ffd0e42009-09-11 21:30:56131#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42132 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56133#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42134 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56135#endif
[email protected]765b44502009-10-02 05:01:42136}
[email protected]e5ffd0e42009-09-11 21:30:56137
[email protected]765b44502009-10-02 05:01:42138bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50139 in_memory_ = true;
[email protected]765b44502009-10-02 05:01:42140 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56141}
142
[email protected]41a97c812013-02-07 02:35:38143void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47144 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
145 // will delete the -journal file. For ChromiumOS or other more
146 // embedded systems, this is probably not appropriate, whereas on
147 // desktop it might make some sense.
148
[email protected]4b350052012-02-24 20:40:48149 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48150
[email protected]41a97c812013-02-07 02:35:38151 // Release cached statements.
152 statement_cache_.clear();
153
154 // With cached statements released, in-use statements will remain.
155 // Closing the database while statements are in use is an API
156 // violation, except for forced close (which happens from within a
157 // statement's error handler).
158 DCHECK(forced || open_statements_.empty());
159
160 // Deactivate any outstanding statements so sqlite3_close() works.
161 for (StatementRefSet::iterator i = open_statements_.begin();
162 i != open_statements_.end(); ++i)
163 (*i)->Close(forced);
164 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48165
[email protected]e5ffd0e42009-09-11 21:30:56166 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50167 // Call to AssertIOAllowed() cannot go at the beginning of the function
168 // because Close() must be called from destructor to clean
169 // statement_cache_, it won't cause any disk access and it most probably
170 // will happen on thread not allowing disk access.
171 // TODO([email protected]): This should move to the beginning
172 // of the function. http://crbug.com/136655.
173 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48174 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56175 sqlite3_close(db_);
176 db_ = NULL;
177 }
178}
179
[email protected]41a97c812013-02-07 02:35:38180void Connection::Close() {
181 // If the database was already closed by RazeAndClose(), then no
182 // need to close again. Clear the |poisoned_| bit so that incorrect
183 // API calls are caught.
184 if (poisoned_) {
185 poisoned_ = false;
186 return;
187 }
188
189 CloseInternal(false);
190}
191
[email protected]e5ffd0e42009-09-11 21:30:56192void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50193 AssertIOAllowed();
194
[email protected]e5ffd0e42009-09-11 21:30:56195 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38196 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56197 return;
198 }
199
200 // A statement must be open for the preload command to work. If the meta
201 // table doesn't exist, it probably means this is a new database and there
202 // is nothing to preload (so it's OK we do nothing).
203 if (!DoesTableExist("meta"))
204 return;
205 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59206 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56207 return;
208
[email protected]4176eee4b2011-01-26 14:33:32209#if !defined(USE_SYSTEM_SQLITE)
210 // This function is only defined in Chromium's version of sqlite.
211 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06212 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32213#endif
[email protected]e5ffd0e42009-09-11 21:30:56214}
215
[email protected]8e0c01282012-04-06 19:36:49216// Create an in-memory database with the existing database's page
217// size, then backup that database over the existing database.
218bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50219 AssertIOAllowed();
220
[email protected]8e0c01282012-04-06 19:36:49221 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38222 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49223 return false;
224 }
225
226 if (transaction_nesting_ > 0) {
227 DLOG(FATAL) << "Cannot raze within a transaction";
228 return false;
229 }
230
231 sql::Connection null_db;
232 if (!null_db.OpenInMemory()) {
233 DLOG(FATAL) << "Unable to open in-memory database.";
234 return false;
235 }
236
[email protected]6d42f152012-11-10 00:38:24237 if (page_size_) {
238 // Enforce SQLite restrictions on |page_size_|.
239 DCHECK(!(page_size_ & (page_size_ - 1)))
240 << " page_size_ " << page_size_ << " is not a power of two.";
241 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
242 DCHECK_LE(page_size_, kSqliteMaxPageSize);
243 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42244 if (!null_db.Execute(sql.c_str()))
245 return false;
246 }
247
[email protected]6d42f152012-11-10 00:38:24248#if defined(OS_ANDROID)
249 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
250 // in-memory databases do not respect this define.
251 // TODO(shess): Figure out a way to set this without using platform
252 // specific code. AFAICT from sqlite3.c, the only way to do it
253 // would be to create an actual filesystem database, which is
254 // unfortunate.
255 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
256 return false;
257#endif
[email protected]8e0c01282012-04-06 19:36:49258
259 // The page size doesn't take effect until a database has pages, and
260 // at this point the null database has none. Changing the schema
261 // version will create the first page. This will not affect the
262 // schema version in the resulting database, as SQLite's backup
263 // implementation propagates the schema version from the original
264 // connection to the new version of the database, incremented by one
265 // so that other readers see the schema change and act accordingly.
266 if (!null_db.Execute("PRAGMA schema_version = 1"))
267 return false;
268
[email protected]6d42f152012-11-10 00:38:24269 // SQLite tracks the expected number of database pages in the first
270 // page, and if it does not match the total retrieved from a
271 // filesystem call, treats the database as corrupt. This situation
272 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
273 // used to hint to SQLite to soldier on in that case, specifically
274 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
275 // sqlite3.c lockBtree().]
276 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
277 // page_size" can be used to query such a database.
278 ScopedWritableSchema writable_schema(db_);
279
[email protected]8e0c01282012-04-06 19:36:49280 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
281 null_db.db_, "main");
282 if (!backup) {
283 DLOG(FATAL) << "Unable to start sqlite3_backup().";
284 return false;
285 }
286
287 // -1 backs up the entire database.
288 int rc = sqlite3_backup_step(backup, -1);
289 int pages = sqlite3_backup_pagecount(backup);
290 sqlite3_backup_finish(backup);
291
292 // The destination database was locked.
293 if (rc == SQLITE_BUSY) {
294 return false;
295 }
296
297 // The entire database should have been backed up.
298 if (rc != SQLITE_DONE) {
299 DLOG(FATAL) << "Unable to copy entire null database.";
300 return false;
301 }
302
303 // Exactly one page should have been backed up. If this breaks,
304 // check this function to make sure assumptions aren't being broken.
305 DCHECK_EQ(pages, 1);
306
307 return true;
308}
309
310bool Connection::RazeWithTimout(base::TimeDelta timeout) {
311 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38312 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49313 return false;
314 }
315
316 ScopedBusyTimeout busy_timeout(db_);
317 busy_timeout.SetTimeout(timeout);
318 return Raze();
319}
320
[email protected]41a97c812013-02-07 02:35:38321bool Connection::RazeAndClose() {
322 if (!db_) {
323 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
324 return false;
325 }
326
327 // Raze() cannot run in a transaction.
328 while (transaction_nesting_) {
329 RollbackTransaction();
330 }
331
332 bool result = Raze();
333
334 CloseInternal(true);
335
336 // Mark the database so that future API calls fail appropriately,
337 // but don't DCHECK (because after calling this function they are
338 // expected to fail).
339 poisoned_ = true;
340
341 return result;
342}
343
[email protected]e5ffd0e42009-09-11 21:30:56344bool Connection::BeginTransaction() {
345 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33346 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56347
348 // When we're going to rollback, fail on this begin and don't actually
349 // mark us as entering the nested transaction.
350 return false;
351 }
352
353 bool success = true;
354 if (!transaction_nesting_) {
355 needs_rollback_ = false;
356
357 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59358 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56359 return false;
360 }
361 transaction_nesting_++;
362 return success;
363}
364
365void Connection::RollbackTransaction() {
366 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38367 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56368 return;
369 }
370
371 transaction_nesting_--;
372
373 if (transaction_nesting_ > 0) {
374 // Mark the outermost transaction as needing rollback.
375 needs_rollback_ = true;
376 return;
377 }
378
379 DoRollback();
380}
381
382bool Connection::CommitTransaction() {
383 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38384 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56385 return false;
386 }
387 transaction_nesting_--;
388
389 if (transaction_nesting_ > 0) {
390 // Mark any nested transactions as failing after we've already got one.
391 return !needs_rollback_;
392 }
393
394 if (needs_rollback_) {
395 DoRollback();
396 return false;
397 }
398
399 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56400 return commit.Run();
401}
402
[email protected]eff1fa522011-12-12 23:50:59403int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50404 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38405 if (!db_) {
406 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
407 return SQLITE_ERROR;
408 }
[email protected]eff1fa522011-12-12 23:50:59409 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
410}
411
412bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38413 if (!db_) {
414 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
415 return false;
416 }
417
[email protected]eff1fa522011-12-12 23:50:59418 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00419 if (error != SQLITE_OK)
420 error = OnSqliteError(error, NULL);
421
[email protected]28fe0ff2012-02-25 00:40:33422 // This needs to be a FATAL log because the error case of arriving here is
423 // that there's a malformed SQL statement. This can arise in development if
424 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59425 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33426 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59427 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56428}
429
[email protected]5b96f3772010-09-28 16:30:57430bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38431 if (!db_) {
432 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57433 return false;
[email protected]41a97c812013-02-07 02:35:38434 }
[email protected]5b96f3772010-09-28 16:30:57435
436 ScopedBusyTimeout busy_timeout(db_);
437 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59438 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57439}
440
[email protected]e5ffd0e42009-09-11 21:30:56441bool Connection::HasCachedStatement(const StatementID& id) const {
442 return statement_cache_.find(id) != statement_cache_.end();
443}
444
445scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
446 const StatementID& id,
447 const char* sql) {
448 CachedStatementMap::iterator i = statement_cache_.find(id);
449 if (i != statement_cache_.end()) {
450 // Statement is in the cache. It should still be active (we're the only
451 // one invalidating cached statements, and we'll remove it from the cache
452 // if we do that. Make sure we reset it before giving out the cached one in
453 // case it still has some stuff bound.
454 DCHECK(i->second->is_valid());
455 sqlite3_reset(i->second->stmt());
456 return i->second;
457 }
458
459 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
460 if (statement->is_valid())
461 statement_cache_[id] = statement; // Only cache valid statements.
462 return statement;
463}
464
465scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
466 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50467 AssertIOAllowed();
468
[email protected]41a97c812013-02-07 02:35:38469 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56470 if (!db_)
[email protected]41a97c812013-02-07 02:35:38471 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56472
473 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00474 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
475 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59476 // This is evidence of a syntax error in the incoming SQL.
477 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00478
479 // It could also be database corruption.
480 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38481 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56482 }
[email protected]41a97c812013-02-07 02:35:38483 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56484}
485
[email protected]2eec0a22012-07-24 01:59:58486scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
487 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38488 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58489 if (!db_)
[email protected]41a97c812013-02-07 02:35:38490 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58491
492 sqlite3_stmt* stmt = NULL;
493 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
494 if (rc != SQLITE_OK) {
495 // This is evidence of a syntax error in the incoming SQL.
496 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38497 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58498 }
[email protected]41a97c812013-02-07 02:35:38499 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58500}
501
[email protected]eff1fa522011-12-12 23:50:59502bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50503 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38504 if (!db_) {
505 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
506 return false;
507 }
508
[email protected]eff1fa522011-12-12 23:50:59509 sqlite3_stmt* stmt = NULL;
510 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
511 return false;
512
513 sqlite3_finalize(stmt);
514 return true;
515}
516
[email protected]1ed78a32009-09-15 20:24:17517bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53518 return DoesTableOrIndexExist(table_name, "table");
519}
520
521bool Connection::DoesIndexExist(const char* index_name) const {
522 return DoesTableOrIndexExist(index_name, "index");
523}
524
525bool Connection::DoesTableOrIndexExist(
526 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58527 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
528 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53529 statement.BindString(0, type);
530 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33531
[email protected]e5ffd0e42009-09-11 21:30:56532 return statement.Step(); // Table exists if any row was returned.
533}
534
535bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17536 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56537 std::string sql("PRAGMA TABLE_INFO(");
538 sql.append(table_name);
539 sql.append(")");
540
[email protected]2eec0a22012-07-24 01:59:58541 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56542 while (statement.Step()) {
543 if (!statement.ColumnString(1).compare(column_name))
544 return true;
545 }
546 return false;
547}
548
549int64 Connection::GetLastInsertRowId() const {
550 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38551 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56552 return 0;
553 }
554 return sqlite3_last_insert_rowid(db_);
555}
556
[email protected]1ed78a32009-09-15 20:24:17557int Connection::GetLastChangeCount() const {
558 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38559 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17560 return 0;
561 }
562 return sqlite3_changes(db_);
563}
564
[email protected]e5ffd0e42009-09-11 21:30:56565int Connection::GetErrorCode() const {
566 if (!db_)
567 return SQLITE_ERROR;
568 return sqlite3_errcode(db_);
569}
570
[email protected]767718e52010-09-21 23:18:49571int Connection::GetLastErrno() const {
572 if (!db_)
573 return -1;
574
575 int err = 0;
576 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
577 return -2;
578
579 return err;
580}
581
[email protected]e5ffd0e42009-09-11 21:30:56582const char* Connection::GetErrorMessage() const {
583 if (!db_)
584 return "sql::Connection has no connection.";
585 return sqlite3_errmsg(db_);
586}
587
[email protected]765b44502009-10-02 05:01:42588bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50589 AssertIOAllowed();
590
[email protected]9cfbc922009-11-17 20:13:17591 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59592 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17593 return false;
594 }
595
[email protected]41a97c812013-02-07 02:35:38596 // If |poisoned_| is set, it means an error handler called
597 // RazeAndClose(). Until regular Close() is called, the caller
598 // should be treating the database as open, but is_open() currently
599 // only considers the sqlite3 handle's state.
600 // TODO(shess): Revise is_open() to consider poisoned_, and review
601 // to see if any non-testing code even depends on it.
602 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
603
[email protected]765b44502009-10-02 05:01:42604 int err = sqlite3_open(file_name.c_str(), &db_);
605 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50606 // Histogram failures specific to initial open for debugging
607 // purposes.
608 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
609
[email protected]765b44502009-10-02 05:01:42610 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29611 Close();
[email protected]765b44502009-10-02 05:01:42612 db_ = NULL;
613 return false;
614 }
615
[email protected]bd2ccdb4a2012-12-07 22:14:50616 // sqlite3_open() does not actually read the database file (unless a
617 // hot journal is found). Successfully executing this pragma on an
618 // existing database requires a valid header on page 1.
619 // TODO(shess): For now, just probing to see what the lay of the
620 // land is. If it's mostly SQLITE_NOTADB, then the database should
621 // be razed.
622 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
623 if (err != SQLITE_OK)
624 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
625
[email protected]658f8332010-09-18 04:40:43626 // Enable extended result codes to provide more color on I/O errors.
627 // Not having extended result codes is not a fatal problem, as
628 // Chromium code does not attempt to handle I/O errors anyhow. The
629 // current implementation always returns SQLITE_OK, the DCHECK is to
630 // quickly notify someone if SQLite changes.
631 err = sqlite3_extended_result_codes(db_, 1);
632 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
633
[email protected]5b96f3772010-09-28 16:30:57634 // If indicated, lock up the database before doing anything else, so
635 // that the following code doesn't have to deal with locking.
636 // TODO(shess): This code is brittle. Find the cases where code
637 // doesn't request |exclusive_locking_| and audit that it does the
638 // right thing with SQLITE_BUSY, and that it doesn't make
639 // assumptions about who might change things in the database.
640 // http://crbug.com/56559
641 if (exclusive_locking_) {
642 // TODO(shess): This should probably be a full CHECK(). Code
643 // which requests exclusive locking but doesn't get it is almost
644 // certain to be ill-tested.
645 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59646 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57647 }
648
[email protected]4e179ba2012-03-17 16:06:47649 // http://www.sqlite.org/pragma.html#pragma_journal_mode
650 // DELETE (default) - delete -journal file to commit.
651 // TRUNCATE - truncate -journal file to commit.
652 // PERSIST - zero out header of -journal file to commit.
653 // journal_size_limit provides size to trim to in PERSIST.
654 // TODO(shess): Figure out if PERSIST and journal_size_limit really
655 // matter. In theory, it keeps pages pre-allocated, so if
656 // transactions usually fit, it should be faster.
657 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
658 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
659
[email protected]c68ce172011-11-24 22:30:27660 const base::TimeDelta kBusyTimeout =
661 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
662
[email protected]765b44502009-10-02 05:01:42663 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57664 // Enforce SQLite restrictions on |page_size_|.
665 DCHECK(!(page_size_ & (page_size_ - 1)))
666 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24667 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57668 DCHECK_LE(page_size_, kSqliteMaxPageSize);
669 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
670 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59671 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42672 }
673
674 if (cache_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57675 const std::string sql = StringPrintf("PRAGMA cache_size=%d", cache_size_);
676 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59677 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42678 }
679
[email protected]6e0b1442011-08-09 23:23:58680 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59681 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58682 Close();
683 return false;
684 }
685
[email protected]765b44502009-10-02 05:01:42686 return true;
687}
688
[email protected]e5ffd0e42009-09-11 21:30:56689void Connection::DoRollback() {
690 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59691 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05692 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56693}
694
695void Connection::StatementRefCreated(StatementRef* ref) {
696 DCHECK(open_statements_.find(ref) == open_statements_.end());
697 open_statements_.insert(ref);
698}
699
700void Connection::StatementRefDeleted(StatementRef* ref) {
701 StatementRefSet::iterator i = open_statements_.find(ref);
702 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59703 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56704 else
705 open_statements_.erase(i);
706}
707
[email protected]faa604e2009-09-25 22:38:59708int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]c088e3a32013-01-03 23:59:14709 // Strip extended error codes.
710 int base_err = err&0xff;
711
712 static size_t kSqliteErrorMax = 50;
713 UMA_HISTOGRAM_ENUMERATION("Sqlite.Error", base_err, kSqliteErrorMax);
714 if (!error_histogram_name_.empty()) {
715 // TODO(shess): The histogram macros create a bit of static
716 // storage for caching the histogram object. Since SQLite is
717 // being used for I/O, generally without error, this code
718 // shouldn't execute often enough for such caching to be crucial.
719 // If it becomes an issue, the object could be cached alongside
720 // error_histogram_name_.
[email protected]de415552013-01-23 04:12:17721 base::HistogramBase* histogram =
[email protected]c088e3a32013-01-03 23:59:14722 base::LinearHistogram::FactoryGet(
723 error_histogram_name_, 1, kSqliteErrorMax, kSqliteErrorMax + 1,
[email protected]de415552013-01-23 04:12:17724 base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]c088e3a32013-01-03 23:59:14725 if (histogram)
726 histogram->Add(base_err);
727 }
728
729 // Always log the error.
730 LOG(ERROR) << "sqlite error " << err
731 << ", errno " << GetLastErrno()
732 << ": " << GetErrorMessage();
733
[email protected]faa604e2009-09-25 22:38:59734 if (error_delegate_.get())
735 return error_delegate_->OnError(err, this, stmt);
[email protected]c088e3a32013-01-03 23:59:14736
[email protected]faa604e2009-09-25 22:38:59737 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59738 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59739 return err;
740}
741
[email protected]e5ffd0e42009-09-11 21:30:56742} // namespace sql