blob: 701a1298075a44431d470fd75c38cffedc678f7b [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]210ce0af2013-05-15 09:10:3912#include "base/metrics/sparse_histogram.h"
[email protected]e5ffd0e42009-09-11 21:30:5613#include "base/string_util.h"
[email protected]f0a54b22011-07-19 18:40:2114#include "base/stringprintf.h"
[email protected]d55194ca2010-03-11 18:25:4515#include "base/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2116#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0317#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5618
[email protected]5b96f3772010-09-28 16:30:5719namespace {
20
21// Spin for up to a second waiting for the lock to clear when setting
22// up the database.
23// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2724const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5725
26class ScopedBusyTimeout {
27 public:
28 explicit ScopedBusyTimeout(sqlite3* db)
29 : db_(db) {
30 }
31 ~ScopedBusyTimeout() {
32 sqlite3_busy_timeout(db_, 0);
33 }
34
35 int SetTimeout(base::TimeDelta timeout) {
36 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
37 return sqlite3_busy_timeout(db_,
38 static_cast<int>(timeout.InMilliseconds()));
39 }
40
41 private:
42 sqlite3* db_;
43};
44
[email protected]6d42f152012-11-10 00:38:2445// Helper to "safely" enable writable_schema. No error checking
46// because it is reasonable to just forge ahead in case of an error.
47// If turning it on fails, then most likely nothing will work, whereas
48// if turning it off fails, it only matters if some code attempts to
49// continue working with the database and tries to modify the
50// sqlite_master table (none of our code does this).
51class ScopedWritableSchema {
52 public:
53 explicit ScopedWritableSchema(sqlite3* db)
54 : db_(db) {
55 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
56 }
57 ~ScopedWritableSchema() {
58 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
59 }
60
61 private:
62 sqlite3* db_;
63};
64
[email protected]5b96f3772010-09-28 16:30:5765} // namespace
66
[email protected]e5ffd0e42009-09-11 21:30:5667namespace sql {
68
69bool StatementID::operator<(const StatementID& other) const {
70 if (number_ != other.number_)
71 return number_ < other.number_;
72 return strcmp(str_, other.str_) < 0;
73}
74
[email protected]d4799a32010-09-28 22:54:5875ErrorDelegate::~ErrorDelegate() {
76}
77
[email protected]e5ffd0e42009-09-11 21:30:5678Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:3879 sqlite3_stmt* stmt,
80 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:5681 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:3882 stmt_(stmt),
83 was_valid_(was_valid) {
84 if (connection)
85 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:5686}
87
88Connection::StatementRef::~StatementRef() {
89 if (connection_)
90 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:3891 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:5692}
93
[email protected]41a97c812013-02-07 02:35:3894void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:5695 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:5096 // Call to AssertIOAllowed() cannot go at the beginning of the function
97 // because Close() is called unconditionally from destructor to clean
98 // connection_. And if this is inactive statement this won't cause any
99 // disk access and destructor most probably will be called on thread
100 // not allowing disk access.
101 // TODO([email protected]): This should move to the beginning
102 // of the function. http://crbug.com/136655.
103 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56104 sqlite3_finalize(stmt_);
105 stmt_ = NULL;
106 }
107 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38108
109 // Forced close is expected to happen from a statement error
110 // handler. In that case maintain the sense of |was_valid_| which
111 // previously held for this ref.
112 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56113}
114
115Connection::Connection()
116 : db_(NULL),
117 page_size_(0),
118 cache_size_(0),
119 exclusive_locking_(false),
120 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50121 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16122 in_memory_(false),
[email protected]41a97c812013-02-07 02:35:38123 poisoned_(false),
[email protected]49dc4f22012-10-17 17:41:16124 error_delegate_(NULL) {
[email protected]e5ffd0e42009-09-11 21:30:56125}
126
127Connection::~Connection() {
128 Close();
129}
130
[email protected]a3ef4832013-02-02 05:12:33131bool Connection::Open(const base::FilePath& path) {
[email protected]e5ffd0e42009-09-11 21:30:56132#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42133 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56134#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42135 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56136#endif
[email protected]765b44502009-10-02 05:01:42137}
[email protected]e5ffd0e42009-09-11 21:30:56138
[email protected]765b44502009-10-02 05:01:42139bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50140 in_memory_ = true;
[email protected]765b44502009-10-02 05:01:42141 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56142}
143
[email protected]41a97c812013-02-07 02:35:38144void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47145 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
146 // will delete the -journal file. For ChromiumOS or other more
147 // embedded systems, this is probably not appropriate, whereas on
148 // desktop it might make some sense.
149
[email protected]4b350052012-02-24 20:40:48150 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48151
[email protected]41a97c812013-02-07 02:35:38152 // Release cached statements.
153 statement_cache_.clear();
154
155 // With cached statements released, in-use statements will remain.
156 // Closing the database while statements are in use is an API
157 // violation, except for forced close (which happens from within a
158 // statement's error handler).
159 DCHECK(forced || open_statements_.empty());
160
161 // Deactivate any outstanding statements so sqlite3_close() works.
162 for (StatementRefSet::iterator i = open_statements_.begin();
163 i != open_statements_.end(); ++i)
164 (*i)->Close(forced);
165 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48166
[email protected]e5ffd0e42009-09-11 21:30:56167 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50168 // Call to AssertIOAllowed() cannot go at the beginning of the function
169 // because Close() must be called from destructor to clean
170 // statement_cache_, it won't cause any disk access and it most probably
171 // will happen on thread not allowing disk access.
172 // TODO([email protected]): This should move to the beginning
173 // of the function. http://crbug.com/136655.
174 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48175 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56176 sqlite3_close(db_);
177 db_ = NULL;
178 }
179}
180
[email protected]41a97c812013-02-07 02:35:38181void Connection::Close() {
182 // If the database was already closed by RazeAndClose(), then no
183 // need to close again. Clear the |poisoned_| bit so that incorrect
184 // API calls are caught.
185 if (poisoned_) {
186 poisoned_ = false;
187 return;
188 }
189
190 CloseInternal(false);
191}
192
[email protected]e5ffd0e42009-09-11 21:30:56193void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50194 AssertIOAllowed();
195
[email protected]e5ffd0e42009-09-11 21:30:56196 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38197 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56198 return;
199 }
200
201 // A statement must be open for the preload command to work. If the meta
202 // table doesn't exist, it probably means this is a new database and there
203 // is nothing to preload (so it's OK we do nothing).
204 if (!DoesTableExist("meta"))
205 return;
206 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59207 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56208 return;
209
[email protected]4176eee4b2011-01-26 14:33:32210#if !defined(USE_SYSTEM_SQLITE)
211 // This function is only defined in Chromium's version of sqlite.
212 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06213 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32214#endif
[email protected]e5ffd0e42009-09-11 21:30:56215}
216
[email protected]8e0c01282012-04-06 19:36:49217// Create an in-memory database with the existing database's page
218// size, then backup that database over the existing database.
219bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50220 AssertIOAllowed();
221
[email protected]8e0c01282012-04-06 19:36:49222 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38223 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49224 return false;
225 }
226
227 if (transaction_nesting_ > 0) {
228 DLOG(FATAL) << "Cannot raze within a transaction";
229 return false;
230 }
231
232 sql::Connection null_db;
233 if (!null_db.OpenInMemory()) {
234 DLOG(FATAL) << "Unable to open in-memory database.";
235 return false;
236 }
237
[email protected]6d42f152012-11-10 00:38:24238 if (page_size_) {
239 // Enforce SQLite restrictions on |page_size_|.
240 DCHECK(!(page_size_ & (page_size_ - 1)))
241 << " page_size_ " << page_size_ << " is not a power of two.";
242 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
243 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04244 const std::string sql =
245 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42246 if (!null_db.Execute(sql.c_str()))
247 return false;
248 }
249
[email protected]6d42f152012-11-10 00:38:24250#if defined(OS_ANDROID)
251 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
252 // in-memory databases do not respect this define.
253 // TODO(shess): Figure out a way to set this without using platform
254 // specific code. AFAICT from sqlite3.c, the only way to do it
255 // would be to create an actual filesystem database, which is
256 // unfortunate.
257 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
258 return false;
259#endif
[email protected]8e0c01282012-04-06 19:36:49260
261 // The page size doesn't take effect until a database has pages, and
262 // at this point the null database has none. Changing the schema
263 // version will create the first page. This will not affect the
264 // schema version in the resulting database, as SQLite's backup
265 // implementation propagates the schema version from the original
266 // connection to the new version of the database, incremented by one
267 // so that other readers see the schema change and act accordingly.
268 if (!null_db.Execute("PRAGMA schema_version = 1"))
269 return false;
270
[email protected]6d42f152012-11-10 00:38:24271 // SQLite tracks the expected number of database pages in the first
272 // page, and if it does not match the total retrieved from a
273 // filesystem call, treats the database as corrupt. This situation
274 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
275 // used to hint to SQLite to soldier on in that case, specifically
276 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
277 // sqlite3.c lockBtree().]
278 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
279 // page_size" can be used to query such a database.
280 ScopedWritableSchema writable_schema(db_);
281
[email protected]8e0c01282012-04-06 19:36:49282 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
283 null_db.db_, "main");
284 if (!backup) {
285 DLOG(FATAL) << "Unable to start sqlite3_backup().";
286 return false;
287 }
288
289 // -1 backs up the entire database.
290 int rc = sqlite3_backup_step(backup, -1);
291 int pages = sqlite3_backup_pagecount(backup);
292 sqlite3_backup_finish(backup);
293
294 // The destination database was locked.
295 if (rc == SQLITE_BUSY) {
296 return false;
297 }
298
299 // The entire database should have been backed up.
300 if (rc != SQLITE_DONE) {
301 DLOG(FATAL) << "Unable to copy entire null database.";
302 return false;
303 }
304
305 // Exactly one page should have been backed up. If this breaks,
306 // check this function to make sure assumptions aren't being broken.
307 DCHECK_EQ(pages, 1);
308
309 return true;
310}
311
312bool Connection::RazeWithTimout(base::TimeDelta timeout) {
313 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38314 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49315 return false;
316 }
317
318 ScopedBusyTimeout busy_timeout(db_);
319 busy_timeout.SetTimeout(timeout);
320 return Raze();
321}
322
[email protected]41a97c812013-02-07 02:35:38323bool Connection::RazeAndClose() {
324 if (!db_) {
325 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
326 return false;
327 }
328
329 // Raze() cannot run in a transaction.
330 while (transaction_nesting_) {
331 RollbackTransaction();
332 }
333
334 bool result = Raze();
335
336 CloseInternal(true);
337
338 // Mark the database so that future API calls fail appropriately,
339 // but don't DCHECK (because after calling this function they are
340 // expected to fail).
341 poisoned_ = true;
342
343 return result;
344}
345
[email protected]e5ffd0e42009-09-11 21:30:56346bool Connection::BeginTransaction() {
347 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33348 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56349
350 // When we're going to rollback, fail on this begin and don't actually
351 // mark us as entering the nested transaction.
352 return false;
353 }
354
355 bool success = true;
356 if (!transaction_nesting_) {
357 needs_rollback_ = false;
358
359 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59360 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56361 return false;
362 }
363 transaction_nesting_++;
364 return success;
365}
366
367void Connection::RollbackTransaction() {
368 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38369 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56370 return;
371 }
372
373 transaction_nesting_--;
374
375 if (transaction_nesting_ > 0) {
376 // Mark the outermost transaction as needing rollback.
377 needs_rollback_ = true;
378 return;
379 }
380
381 DoRollback();
382}
383
384bool Connection::CommitTransaction() {
385 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38386 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56387 return false;
388 }
389 transaction_nesting_--;
390
391 if (transaction_nesting_ > 0) {
392 // Mark any nested transactions as failing after we've already got one.
393 return !needs_rollback_;
394 }
395
396 if (needs_rollback_) {
397 DoRollback();
398 return false;
399 }
400
401 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56402 return commit.Run();
403}
404
[email protected]eff1fa522011-12-12 23:50:59405int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50406 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38407 if (!db_) {
408 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
409 return SQLITE_ERROR;
410 }
[email protected]eff1fa522011-12-12 23:50:59411 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
412}
413
414bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38415 if (!db_) {
416 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
417 return false;
418 }
419
[email protected]eff1fa522011-12-12 23:50:59420 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00421 if (error != SQLITE_OK)
422 error = OnSqliteError(error, NULL);
423
[email protected]28fe0ff2012-02-25 00:40:33424 // This needs to be a FATAL log because the error case of arriving here is
425 // that there's a malformed SQL statement. This can arise in development if
426 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59427 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33428 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59429 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56430}
431
[email protected]5b96f3772010-09-28 16:30:57432bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38433 if (!db_) {
434 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57435 return false;
[email protected]41a97c812013-02-07 02:35:38436 }
[email protected]5b96f3772010-09-28 16:30:57437
438 ScopedBusyTimeout busy_timeout(db_);
439 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59440 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57441}
442
[email protected]e5ffd0e42009-09-11 21:30:56443bool Connection::HasCachedStatement(const StatementID& id) const {
444 return statement_cache_.find(id) != statement_cache_.end();
445}
446
447scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
448 const StatementID& id,
449 const char* sql) {
450 CachedStatementMap::iterator i = statement_cache_.find(id);
451 if (i != statement_cache_.end()) {
452 // Statement is in the cache. It should still be active (we're the only
453 // one invalidating cached statements, and we'll remove it from the cache
454 // if we do that. Make sure we reset it before giving out the cached one in
455 // case it still has some stuff bound.
456 DCHECK(i->second->is_valid());
457 sqlite3_reset(i->second->stmt());
458 return i->second;
459 }
460
461 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
462 if (statement->is_valid())
463 statement_cache_[id] = statement; // Only cache valid statements.
464 return statement;
465}
466
467scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
468 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50469 AssertIOAllowed();
470
[email protected]41a97c812013-02-07 02:35:38471 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56472 if (!db_)
[email protected]41a97c812013-02-07 02:35:38473 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56474
475 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00476 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
477 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59478 // This is evidence of a syntax error in the incoming SQL.
479 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00480
481 // It could also be database corruption.
482 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38483 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56484 }
[email protected]41a97c812013-02-07 02:35:38485 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56486}
487
[email protected]2eec0a22012-07-24 01:59:58488scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
489 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38490 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58491 if (!db_)
[email protected]41a97c812013-02-07 02:35:38492 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58493
494 sqlite3_stmt* stmt = NULL;
495 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
496 if (rc != SQLITE_OK) {
497 // This is evidence of a syntax error in the incoming SQL.
498 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38499 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58500 }
[email protected]41a97c812013-02-07 02:35:38501 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58502}
503
[email protected]eff1fa522011-12-12 23:50:59504bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50505 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38506 if (!db_) {
507 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
508 return false;
509 }
510
[email protected]eff1fa522011-12-12 23:50:59511 sqlite3_stmt* stmt = NULL;
512 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
513 return false;
514
515 sqlite3_finalize(stmt);
516 return true;
517}
518
[email protected]1ed78a32009-09-15 20:24:17519bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53520 return DoesTableOrIndexExist(table_name, "table");
521}
522
523bool Connection::DoesIndexExist(const char* index_name) const {
524 return DoesTableOrIndexExist(index_name, "index");
525}
526
527bool Connection::DoesTableOrIndexExist(
528 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58529 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
530 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53531 statement.BindString(0, type);
532 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33533
[email protected]e5ffd0e42009-09-11 21:30:56534 return statement.Step(); // Table exists if any row was returned.
535}
536
537bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17538 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56539 std::string sql("PRAGMA TABLE_INFO(");
540 sql.append(table_name);
541 sql.append(")");
542
[email protected]2eec0a22012-07-24 01:59:58543 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56544 while (statement.Step()) {
545 if (!statement.ColumnString(1).compare(column_name))
546 return true;
547 }
548 return false;
549}
550
551int64 Connection::GetLastInsertRowId() const {
552 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38553 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56554 return 0;
555 }
556 return sqlite3_last_insert_rowid(db_);
557}
558
[email protected]1ed78a32009-09-15 20:24:17559int Connection::GetLastChangeCount() const {
560 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38561 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17562 return 0;
563 }
564 return sqlite3_changes(db_);
565}
566
[email protected]e5ffd0e42009-09-11 21:30:56567int Connection::GetErrorCode() const {
568 if (!db_)
569 return SQLITE_ERROR;
570 return sqlite3_errcode(db_);
571}
572
[email protected]767718e52010-09-21 23:18:49573int Connection::GetLastErrno() const {
574 if (!db_)
575 return -1;
576
577 int err = 0;
578 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
579 return -2;
580
581 return err;
582}
583
[email protected]e5ffd0e42009-09-11 21:30:56584const char* Connection::GetErrorMessage() const {
585 if (!db_)
586 return "sql::Connection has no connection.";
587 return sqlite3_errmsg(db_);
588}
589
[email protected]765b44502009-10-02 05:01:42590bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50591 AssertIOAllowed();
592
[email protected]9cfbc922009-11-17 20:13:17593 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59594 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17595 return false;
596 }
597
[email protected]41a97c812013-02-07 02:35:38598 // If |poisoned_| is set, it means an error handler called
599 // RazeAndClose(). Until regular Close() is called, the caller
600 // should be treating the database as open, but is_open() currently
601 // only considers the sqlite3 handle's state.
602 // TODO(shess): Revise is_open() to consider poisoned_, and review
603 // to see if any non-testing code even depends on it.
604 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
605
[email protected]765b44502009-10-02 05:01:42606 int err = sqlite3_open(file_name.c_str(), &db_);
607 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50608 // Histogram failures specific to initial open for debugging
609 // purposes.
610 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
611
[email protected]765b44502009-10-02 05:01:42612 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29613 Close();
[email protected]765b44502009-10-02 05:01:42614 db_ = NULL;
615 return false;
616 }
617
[email protected]bd2ccdb4a2012-12-07 22:14:50618 // sqlite3_open() does not actually read the database file (unless a
619 // hot journal is found). Successfully executing this pragma on an
620 // existing database requires a valid header on page 1.
621 // TODO(shess): For now, just probing to see what the lay of the
622 // land is. If it's mostly SQLITE_NOTADB, then the database should
623 // be razed.
624 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
625 if (err != SQLITE_OK)
626 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
627
[email protected]658f8332010-09-18 04:40:43628 // Enable extended result codes to provide more color on I/O errors.
629 // Not having extended result codes is not a fatal problem, as
630 // Chromium code does not attempt to handle I/O errors anyhow. The
631 // current implementation always returns SQLITE_OK, the DCHECK is to
632 // quickly notify someone if SQLite changes.
633 err = sqlite3_extended_result_codes(db_, 1);
634 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
635
[email protected]5b96f3772010-09-28 16:30:57636 // If indicated, lock up the database before doing anything else, so
637 // that the following code doesn't have to deal with locking.
638 // TODO(shess): This code is brittle. Find the cases where code
639 // doesn't request |exclusive_locking_| and audit that it does the
640 // right thing with SQLITE_BUSY, and that it doesn't make
641 // assumptions about who might change things in the database.
642 // http://crbug.com/56559
643 if (exclusive_locking_) {
644 // TODO(shess): This should probably be a full CHECK(). Code
645 // which requests exclusive locking but doesn't get it is almost
646 // certain to be ill-tested.
647 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59648 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57649 }
650
[email protected]4e179ba2012-03-17 16:06:47651 // http://www.sqlite.org/pragma.html#pragma_journal_mode
652 // DELETE (default) - delete -journal file to commit.
653 // TRUNCATE - truncate -journal file to commit.
654 // PERSIST - zero out header of -journal file to commit.
655 // journal_size_limit provides size to trim to in PERSIST.
656 // TODO(shess): Figure out if PERSIST and journal_size_limit really
657 // matter. In theory, it keeps pages pre-allocated, so if
658 // transactions usually fit, it should be faster.
659 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
660 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
661
[email protected]c68ce172011-11-24 22:30:27662 const base::TimeDelta kBusyTimeout =
663 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
664
[email protected]765b44502009-10-02 05:01:42665 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57666 // Enforce SQLite restrictions on |page_size_|.
667 DCHECK(!(page_size_ & (page_size_ - 1)))
668 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24669 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57670 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04671 const std::string sql =
672 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]5b96f3772010-09-28 16:30:57673 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59674 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42675 }
676
677 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:04678 const std::string sql =
679 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]5b96f3772010-09-28 16:30:57680 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59681 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42682 }
683
[email protected]6e0b1442011-08-09 23:23:58684 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59685 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58686 Close();
687 return false;
688 }
689
[email protected]765b44502009-10-02 05:01:42690 return true;
691}
692
[email protected]e5ffd0e42009-09-11 21:30:56693void Connection::DoRollback() {
694 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59695 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05696 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56697}
698
699void Connection::StatementRefCreated(StatementRef* ref) {
700 DCHECK(open_statements_.find(ref) == open_statements_.end());
701 open_statements_.insert(ref);
702}
703
704void Connection::StatementRefDeleted(StatementRef* ref) {
705 StatementRefSet::iterator i = open_statements_.find(ref);
706 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59707 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56708 else
709 open_statements_.erase(i);
710}
711
[email protected]210ce0af2013-05-15 09:10:39712void Connection::AddTaggedHistogram(const std::string& name,
713 size_t sample) const {
714 if (histogram_tag_.empty())
715 return;
716
717 // TODO(shess): The histogram macros create a bit of static storage
718 // for caching the histogram object. This code shouldn't execute
719 // often enough for such caching to be crucial. If it becomes an
720 // issue, the object could be cached alongside histogram_prefix_.
721 std::string full_histogram_name = name + "." + histogram_tag_;
722 base::HistogramBase* histogram =
723 base::SparseHistogram::FactoryGet(
724 full_histogram_name,
725 base::HistogramBase::kUmaTargetedHistogramFlag);
726 if (histogram)
727 histogram->Add(sample);
728}
729
[email protected]faa604e2009-09-25 22:38:59730int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]210ce0af2013-05-15 09:10:39731 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
732 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:14733
734 // Always log the error.
735 LOG(ERROR) << "sqlite error " << err
736 << ", errno " << GetLastErrno()
737 << ": " << GetErrorMessage();
738
[email protected]c3881b372013-05-17 08:39:46739 if (!error_callback_.is_null()) {
740 error_callback_.Run(err, stmt);
741 return err;
742 }
743
744 // TODO(shess): Remove |error_delegate_| once everything is
745 // converted to |error_callback_|.
[email protected]faa604e2009-09-25 22:38:59746 if (error_delegate_.get())
747 return error_delegate_->OnError(err, this, stmt);
[email protected]c088e3a32013-01-03 23:59:14748
[email protected]faa604e2009-09-25 22:38:59749 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59750 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59751 return err;
752}
753
[email protected]e5ffd0e42009-09-11 21:30:56754} // namespace sql