blob: b3af75e9b860e5f462d031cc16f2b36f346eb263 [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]e5ffd0e42009-09-11 21:30:5614#include "base/string_util.h"
[email protected]f0a54b22011-07-19 18:40:2115#include "base/stringprintf.h"
[email protected]d55194ca2010-03-11 18:25:4516#include "base/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2117#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0318#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5619
[email protected]5b96f3772010-09-28 16:30:5720namespace {
21
22// Spin for up to a second waiting for the lock to clear when setting
23// up the database.
24// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2725const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5726
27class ScopedBusyTimeout {
28 public:
29 explicit ScopedBusyTimeout(sqlite3* db)
30 : db_(db) {
31 }
32 ~ScopedBusyTimeout() {
33 sqlite3_busy_timeout(db_, 0);
34 }
35
36 int SetTimeout(base::TimeDelta timeout) {
37 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
38 return sqlite3_busy_timeout(db_,
39 static_cast<int>(timeout.InMilliseconds()));
40 }
41
42 private:
43 sqlite3* db_;
44};
45
[email protected]6d42f152012-11-10 00:38:2446// Helper to "safely" enable writable_schema. No error checking
47// because it is reasonable to just forge ahead in case of an error.
48// If turning it on fails, then most likely nothing will work, whereas
49// if turning it off fails, it only matters if some code attempts to
50// continue working with the database and tries to modify the
51// sqlite_master table (none of our code does this).
52class ScopedWritableSchema {
53 public:
54 explicit ScopedWritableSchema(sqlite3* db)
55 : db_(db) {
56 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
57 }
58 ~ScopedWritableSchema() {
59 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
60 }
61
62 private:
63 sqlite3* db_;
64};
65
[email protected]5b96f3772010-09-28 16:30:5766} // namespace
67
[email protected]e5ffd0e42009-09-11 21:30:5668namespace sql {
69
70bool StatementID::operator<(const StatementID& other) const {
71 if (number_ != other.number_)
72 return number_ < other.number_;
73 return strcmp(str_, other.str_) < 0;
74}
75
[email protected]d4799a32010-09-28 22:54:5876ErrorDelegate::~ErrorDelegate() {
77}
78
[email protected]e5ffd0e42009-09-11 21:30:5679Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:3880 sqlite3_stmt* stmt,
81 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:5682 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:3883 stmt_(stmt),
84 was_valid_(was_valid) {
85 if (connection)
86 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:5687}
88
89Connection::StatementRef::~StatementRef() {
90 if (connection_)
91 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:3892 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:5693}
94
[email protected]41a97c812013-02-07 02:35:3895void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:5696 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:5097 // Call to AssertIOAllowed() cannot go at the beginning of the function
98 // because Close() is called unconditionally from destructor to clean
99 // connection_. And if this is inactive statement this won't cause any
100 // disk access and destructor most probably will be called on thread
101 // not allowing disk access.
102 // TODO([email protected]): This should move to the beginning
103 // of the function. http://crbug.com/136655.
104 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56105 sqlite3_finalize(stmt_);
106 stmt_ = NULL;
107 }
108 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38109
110 // Forced close is expected to happen from a statement error
111 // handler. In that case maintain the sense of |was_valid_| which
112 // previously held for this ref.
113 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56114}
115
116Connection::Connection()
117 : db_(NULL),
118 page_size_(0),
119 cache_size_(0),
120 exclusive_locking_(false),
121 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50122 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16123 in_memory_(false),
[email protected]41a97c812013-02-07 02:35:38124 poisoned_(false),
[email protected]49dc4f22012-10-17 17:41:16125 error_delegate_(NULL) {
[email protected]e5ffd0e42009-09-11 21:30:56126}
127
128Connection::~Connection() {
129 Close();
130}
131
[email protected]a3ef4832013-02-02 05:12:33132bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02133 if (!histogram_tag_.empty()) {
134 int64 size_64 = 0;
135 if (file_util::GetFileSize(path, &size_64)) {
136 size_t sample = static_cast<size_t>(size_64 / 1024);
137 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
138 base::HistogramBase* histogram =
139 base::Histogram::FactoryGet(
140 full_histogram_name, 1, 1000000, 50,
141 base::HistogramBase::kUmaTargetedHistogramFlag);
142 if (histogram)
143 histogram->Add(sample);
144 }
145 }
146
[email protected]e5ffd0e42009-09-11 21:30:56147#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42148 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56149#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42150 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56151#endif
[email protected]765b44502009-10-02 05:01:42152}
[email protected]e5ffd0e42009-09-11 21:30:56153
[email protected]765b44502009-10-02 05:01:42154bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50155 in_memory_ = true;
[email protected]765b44502009-10-02 05:01:42156 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56157}
158
[email protected]41a97c812013-02-07 02:35:38159void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47160 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
161 // will delete the -journal file. For ChromiumOS or other more
162 // embedded systems, this is probably not appropriate, whereas on
163 // desktop it might make some sense.
164
[email protected]4b350052012-02-24 20:40:48165 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48166
[email protected]41a97c812013-02-07 02:35:38167 // Release cached statements.
168 statement_cache_.clear();
169
170 // With cached statements released, in-use statements will remain.
171 // Closing the database while statements are in use is an API
172 // violation, except for forced close (which happens from within a
173 // statement's error handler).
174 DCHECK(forced || open_statements_.empty());
175
176 // Deactivate any outstanding statements so sqlite3_close() works.
177 for (StatementRefSet::iterator i = open_statements_.begin();
178 i != open_statements_.end(); ++i)
179 (*i)->Close(forced);
180 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48181
[email protected]e5ffd0e42009-09-11 21:30:56182 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50183 // Call to AssertIOAllowed() cannot go at the beginning of the function
184 // because Close() must be called from destructor to clean
185 // statement_cache_, it won't cause any disk access and it most probably
186 // will happen on thread not allowing disk access.
187 // TODO([email protected]): This should move to the beginning
188 // of the function. http://crbug.com/136655.
189 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48190 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56191 sqlite3_close(db_);
192 db_ = NULL;
193 }
194}
195
[email protected]41a97c812013-02-07 02:35:38196void Connection::Close() {
197 // If the database was already closed by RazeAndClose(), then no
198 // need to close again. Clear the |poisoned_| bit so that incorrect
199 // API calls are caught.
200 if (poisoned_) {
201 poisoned_ = false;
202 return;
203 }
204
205 CloseInternal(false);
206}
207
[email protected]e5ffd0e42009-09-11 21:30:56208void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50209 AssertIOAllowed();
210
[email protected]e5ffd0e42009-09-11 21:30:56211 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38212 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56213 return;
214 }
215
216 // A statement must be open for the preload command to work. If the meta
217 // table doesn't exist, it probably means this is a new database and there
218 // is nothing to preload (so it's OK we do nothing).
219 if (!DoesTableExist("meta"))
220 return;
221 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59222 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56223 return;
224
[email protected]4176eee4b2011-01-26 14:33:32225#if !defined(USE_SYSTEM_SQLITE)
226 // This function is only defined in Chromium's version of sqlite.
227 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06228 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32229#endif
[email protected]e5ffd0e42009-09-11 21:30:56230}
231
[email protected]8e0c01282012-04-06 19:36:49232// Create an in-memory database with the existing database's page
233// size, then backup that database over the existing database.
234bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50235 AssertIOAllowed();
236
[email protected]8e0c01282012-04-06 19:36:49237 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38238 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49239 return false;
240 }
241
242 if (transaction_nesting_ > 0) {
243 DLOG(FATAL) << "Cannot raze within a transaction";
244 return false;
245 }
246
247 sql::Connection null_db;
248 if (!null_db.OpenInMemory()) {
249 DLOG(FATAL) << "Unable to open in-memory database.";
250 return false;
251 }
252
[email protected]6d42f152012-11-10 00:38:24253 if (page_size_) {
254 // Enforce SQLite restrictions on |page_size_|.
255 DCHECK(!(page_size_ & (page_size_ - 1)))
256 << " page_size_ " << page_size_ << " is not a power of two.";
257 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
258 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04259 const std::string sql =
260 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42261 if (!null_db.Execute(sql.c_str()))
262 return false;
263 }
264
[email protected]6d42f152012-11-10 00:38:24265#if defined(OS_ANDROID)
266 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
267 // in-memory databases do not respect this define.
268 // TODO(shess): Figure out a way to set this without using platform
269 // specific code. AFAICT from sqlite3.c, the only way to do it
270 // would be to create an actual filesystem database, which is
271 // unfortunate.
272 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
273 return false;
274#endif
[email protected]8e0c01282012-04-06 19:36:49275
276 // The page size doesn't take effect until a database has pages, and
277 // at this point the null database has none. Changing the schema
278 // version will create the first page. This will not affect the
279 // schema version in the resulting database, as SQLite's backup
280 // implementation propagates the schema version from the original
281 // connection to the new version of the database, incremented by one
282 // so that other readers see the schema change and act accordingly.
283 if (!null_db.Execute("PRAGMA schema_version = 1"))
284 return false;
285
[email protected]6d42f152012-11-10 00:38:24286 // SQLite tracks the expected number of database pages in the first
287 // page, and if it does not match the total retrieved from a
288 // filesystem call, treats the database as corrupt. This situation
289 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
290 // used to hint to SQLite to soldier on in that case, specifically
291 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
292 // sqlite3.c lockBtree().]
293 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
294 // page_size" can be used to query such a database.
295 ScopedWritableSchema writable_schema(db_);
296
[email protected]8e0c01282012-04-06 19:36:49297 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
298 null_db.db_, "main");
299 if (!backup) {
300 DLOG(FATAL) << "Unable to start sqlite3_backup().";
301 return false;
302 }
303
304 // -1 backs up the entire database.
305 int rc = sqlite3_backup_step(backup, -1);
306 int pages = sqlite3_backup_pagecount(backup);
307 sqlite3_backup_finish(backup);
308
309 // The destination database was locked.
310 if (rc == SQLITE_BUSY) {
311 return false;
312 }
313
314 // The entire database should have been backed up.
315 if (rc != SQLITE_DONE) {
316 DLOG(FATAL) << "Unable to copy entire null database.";
317 return false;
318 }
319
320 // Exactly one page should have been backed up. If this breaks,
321 // check this function to make sure assumptions aren't being broken.
322 DCHECK_EQ(pages, 1);
323
324 return true;
325}
326
327bool Connection::RazeWithTimout(base::TimeDelta timeout) {
328 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38329 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49330 return false;
331 }
332
333 ScopedBusyTimeout busy_timeout(db_);
334 busy_timeout.SetTimeout(timeout);
335 return Raze();
336}
337
[email protected]41a97c812013-02-07 02:35:38338bool Connection::RazeAndClose() {
339 if (!db_) {
340 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
341 return false;
342 }
343
344 // Raze() cannot run in a transaction.
345 while (transaction_nesting_) {
346 RollbackTransaction();
347 }
348
349 bool result = Raze();
350
351 CloseInternal(true);
352
353 // Mark the database so that future API calls fail appropriately,
354 // but don't DCHECK (because after calling this function they are
355 // expected to fail).
356 poisoned_ = true;
357
358 return result;
359}
360
[email protected]e5ffd0e42009-09-11 21:30:56361bool Connection::BeginTransaction() {
362 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33363 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56364
365 // When we're going to rollback, fail on this begin and don't actually
366 // mark us as entering the nested transaction.
367 return false;
368 }
369
370 bool success = true;
371 if (!transaction_nesting_) {
372 needs_rollback_ = false;
373
374 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59375 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56376 return false;
377 }
378 transaction_nesting_++;
379 return success;
380}
381
382void Connection::RollbackTransaction() {
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;
386 }
387
388 transaction_nesting_--;
389
390 if (transaction_nesting_ > 0) {
391 // Mark the outermost transaction as needing rollback.
392 needs_rollback_ = true;
393 return;
394 }
395
396 DoRollback();
397}
398
399bool Connection::CommitTransaction() {
400 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38401 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56402 return false;
403 }
404 transaction_nesting_--;
405
406 if (transaction_nesting_ > 0) {
407 // Mark any nested transactions as failing after we've already got one.
408 return !needs_rollback_;
409 }
410
411 if (needs_rollback_) {
412 DoRollback();
413 return false;
414 }
415
416 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56417 return commit.Run();
418}
419
[email protected]eff1fa522011-12-12 23:50:59420int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50421 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38422 if (!db_) {
423 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
424 return SQLITE_ERROR;
425 }
[email protected]eff1fa522011-12-12 23:50:59426 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
427}
428
429bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38430 if (!db_) {
431 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
432 return false;
433 }
434
[email protected]eff1fa522011-12-12 23:50:59435 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00436 if (error != SQLITE_OK)
437 error = OnSqliteError(error, NULL);
438
[email protected]28fe0ff2012-02-25 00:40:33439 // This needs to be a FATAL log because the error case of arriving here is
440 // that there's a malformed SQL statement. This can arise in development if
441 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59442 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33443 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59444 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56445}
446
[email protected]5b96f3772010-09-28 16:30:57447bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38448 if (!db_) {
449 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57450 return false;
[email protected]41a97c812013-02-07 02:35:38451 }
[email protected]5b96f3772010-09-28 16:30:57452
453 ScopedBusyTimeout busy_timeout(db_);
454 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59455 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57456}
457
[email protected]e5ffd0e42009-09-11 21:30:56458bool Connection::HasCachedStatement(const StatementID& id) const {
459 return statement_cache_.find(id) != statement_cache_.end();
460}
461
462scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
463 const StatementID& id,
464 const char* sql) {
465 CachedStatementMap::iterator i = statement_cache_.find(id);
466 if (i != statement_cache_.end()) {
467 // Statement is in the cache. It should still be active (we're the only
468 // one invalidating cached statements, and we'll remove it from the cache
469 // if we do that. Make sure we reset it before giving out the cached one in
470 // case it still has some stuff bound.
471 DCHECK(i->second->is_valid());
472 sqlite3_reset(i->second->stmt());
473 return i->second;
474 }
475
476 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
477 if (statement->is_valid())
478 statement_cache_[id] = statement; // Only cache valid statements.
479 return statement;
480}
481
482scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
483 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50484 AssertIOAllowed();
485
[email protected]41a97c812013-02-07 02:35:38486 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56487 if (!db_)
[email protected]41a97c812013-02-07 02:35:38488 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56489
490 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00491 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
492 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59493 // This is evidence of a syntax error in the incoming SQL.
494 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00495
496 // It could also be database corruption.
497 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38498 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56499 }
[email protected]41a97c812013-02-07 02:35:38500 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56501}
502
[email protected]2eec0a22012-07-24 01:59:58503scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
504 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38505 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58506 if (!db_)
[email protected]41a97c812013-02-07 02:35:38507 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58508
509 sqlite3_stmt* stmt = NULL;
510 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
511 if (rc != SQLITE_OK) {
512 // This is evidence of a syntax error in the incoming SQL.
513 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38514 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58515 }
[email protected]41a97c812013-02-07 02:35:38516 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58517}
518
[email protected]eff1fa522011-12-12 23:50:59519bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50520 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38521 if (!db_) {
522 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
523 return false;
524 }
525
[email protected]eff1fa522011-12-12 23:50:59526 sqlite3_stmt* stmt = NULL;
527 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
528 return false;
529
530 sqlite3_finalize(stmt);
531 return true;
532}
533
[email protected]1ed78a32009-09-15 20:24:17534bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53535 return DoesTableOrIndexExist(table_name, "table");
536}
537
538bool Connection::DoesIndexExist(const char* index_name) const {
539 return DoesTableOrIndexExist(index_name, "index");
540}
541
542bool Connection::DoesTableOrIndexExist(
543 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58544 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
545 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53546 statement.BindString(0, type);
547 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33548
[email protected]e5ffd0e42009-09-11 21:30:56549 return statement.Step(); // Table exists if any row was returned.
550}
551
552bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17553 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56554 std::string sql("PRAGMA TABLE_INFO(");
555 sql.append(table_name);
556 sql.append(")");
557
[email protected]2eec0a22012-07-24 01:59:58558 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56559 while (statement.Step()) {
560 if (!statement.ColumnString(1).compare(column_name))
561 return true;
562 }
563 return false;
564}
565
566int64 Connection::GetLastInsertRowId() const {
567 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38568 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56569 return 0;
570 }
571 return sqlite3_last_insert_rowid(db_);
572}
573
[email protected]1ed78a32009-09-15 20:24:17574int Connection::GetLastChangeCount() const {
575 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38576 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17577 return 0;
578 }
579 return sqlite3_changes(db_);
580}
581
[email protected]e5ffd0e42009-09-11 21:30:56582int Connection::GetErrorCode() const {
583 if (!db_)
584 return SQLITE_ERROR;
585 return sqlite3_errcode(db_);
586}
587
[email protected]767718e52010-09-21 23:18:49588int Connection::GetLastErrno() const {
589 if (!db_)
590 return -1;
591
592 int err = 0;
593 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
594 return -2;
595
596 return err;
597}
598
[email protected]e5ffd0e42009-09-11 21:30:56599const char* Connection::GetErrorMessage() const {
600 if (!db_)
601 return "sql::Connection has no connection.";
602 return sqlite3_errmsg(db_);
603}
604
[email protected]765b44502009-10-02 05:01:42605bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50606 AssertIOAllowed();
607
[email protected]9cfbc922009-11-17 20:13:17608 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59609 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17610 return false;
611 }
612
[email protected]41a97c812013-02-07 02:35:38613 // If |poisoned_| is set, it means an error handler called
614 // RazeAndClose(). Until regular Close() is called, the caller
615 // should be treating the database as open, but is_open() currently
616 // only considers the sqlite3 handle's state.
617 // TODO(shess): Revise is_open() to consider poisoned_, and review
618 // to see if any non-testing code even depends on it.
619 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
620
[email protected]765b44502009-10-02 05:01:42621 int err = sqlite3_open(file_name.c_str(), &db_);
622 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50623 // Histogram failures specific to initial open for debugging
624 // purposes.
625 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
626
[email protected]765b44502009-10-02 05:01:42627 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29628 Close();
[email protected]765b44502009-10-02 05:01:42629 db_ = NULL;
630 return false;
631 }
632
[email protected]bd2ccdb4a2012-12-07 22:14:50633 // sqlite3_open() does not actually read the database file (unless a
634 // hot journal is found). Successfully executing this pragma on an
635 // existing database requires a valid header on page 1.
636 // TODO(shess): For now, just probing to see what the lay of the
637 // land is. If it's mostly SQLITE_NOTADB, then the database should
638 // be razed.
639 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
640 if (err != SQLITE_OK)
641 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
642
[email protected]658f8332010-09-18 04:40:43643 // Enable extended result codes to provide more color on I/O errors.
644 // Not having extended result codes is not a fatal problem, as
645 // Chromium code does not attempt to handle I/O errors anyhow. The
646 // current implementation always returns SQLITE_OK, the DCHECK is to
647 // quickly notify someone if SQLite changes.
648 err = sqlite3_extended_result_codes(db_, 1);
649 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
650
[email protected]5b96f3772010-09-28 16:30:57651 // If indicated, lock up the database before doing anything else, so
652 // that the following code doesn't have to deal with locking.
653 // TODO(shess): This code is brittle. Find the cases where code
654 // doesn't request |exclusive_locking_| and audit that it does the
655 // right thing with SQLITE_BUSY, and that it doesn't make
656 // assumptions about who might change things in the database.
657 // http://crbug.com/56559
658 if (exclusive_locking_) {
659 // TODO(shess): This should probably be a full CHECK(). Code
660 // which requests exclusive locking but doesn't get it is almost
661 // certain to be ill-tested.
662 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59663 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57664 }
665
[email protected]4e179ba2012-03-17 16:06:47666 // http://www.sqlite.org/pragma.html#pragma_journal_mode
667 // DELETE (default) - delete -journal file to commit.
668 // TRUNCATE - truncate -journal file to commit.
669 // PERSIST - zero out header of -journal file to commit.
670 // journal_size_limit provides size to trim to in PERSIST.
671 // TODO(shess): Figure out if PERSIST and journal_size_limit really
672 // matter. In theory, it keeps pages pre-allocated, so if
673 // transactions usually fit, it should be faster.
674 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
675 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
676
[email protected]c68ce172011-11-24 22:30:27677 const base::TimeDelta kBusyTimeout =
678 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
679
[email protected]765b44502009-10-02 05:01:42680 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57681 // Enforce SQLite restrictions on |page_size_|.
682 DCHECK(!(page_size_ & (page_size_ - 1)))
683 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24684 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57685 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04686 const std::string sql =
687 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]5b96f3772010-09-28 16:30:57688 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59689 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42690 }
691
692 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:04693 const std::string sql =
694 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]5b96f3772010-09-28 16:30:57695 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59696 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42697 }
698
[email protected]6e0b1442011-08-09 23:23:58699 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59700 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58701 Close();
702 return false;
703 }
704
[email protected]765b44502009-10-02 05:01:42705 return true;
706}
707
[email protected]e5ffd0e42009-09-11 21:30:56708void Connection::DoRollback() {
709 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59710 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05711 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56712}
713
714void Connection::StatementRefCreated(StatementRef* ref) {
715 DCHECK(open_statements_.find(ref) == open_statements_.end());
716 open_statements_.insert(ref);
717}
718
719void Connection::StatementRefDeleted(StatementRef* ref) {
720 StatementRefSet::iterator i = open_statements_.find(ref);
721 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59722 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56723 else
724 open_statements_.erase(i);
725}
726
[email protected]210ce0af2013-05-15 09:10:39727void Connection::AddTaggedHistogram(const std::string& name,
728 size_t sample) const {
729 if (histogram_tag_.empty())
730 return;
731
732 // TODO(shess): The histogram macros create a bit of static storage
733 // for caching the histogram object. This code shouldn't execute
734 // often enough for such caching to be crucial. If it becomes an
735 // issue, the object could be cached alongside histogram_prefix_.
736 std::string full_histogram_name = name + "." + histogram_tag_;
737 base::HistogramBase* histogram =
738 base::SparseHistogram::FactoryGet(
739 full_histogram_name,
740 base::HistogramBase::kUmaTargetedHistogramFlag);
741 if (histogram)
742 histogram->Add(sample);
743}
744
[email protected]faa604e2009-09-25 22:38:59745int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]210ce0af2013-05-15 09:10:39746 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
747 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:14748
749 // Always log the error.
750 LOG(ERROR) << "sqlite error " << err
751 << ", errno " << GetLastErrno()
752 << ": " << GetErrorMessage();
753
[email protected]c3881b372013-05-17 08:39:46754 if (!error_callback_.is_null()) {
755 error_callback_.Run(err, stmt);
756 return err;
757 }
758
759 // TODO(shess): Remove |error_delegate_| once everything is
760 // converted to |error_callback_|.
[email protected]faa604e2009-09-25 22:38:59761 if (error_delegate_.get())
762 return error_delegate_->OnError(err, this, stmt);
[email protected]c088e3a32013-01-03 23:59:14763
[email protected]faa604e2009-09-25 22:38:59764 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59765 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59766 return err;
767}
768
[email protected]e5ffd0e42009-09-11 21:30:56769} // namespace sql