blob: 07e6af222cea8e08547af253b4dbe40ee86689d1 [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]e5ffd0e42009-09-11 21:30:569#include "base/file_path.h"
10#include "base/logging.h"
11#include "base/string_util.h"
[email protected]f0a54b22011-07-19 18:40:2112#include "base/stringprintf.h"
[email protected]d55194ca2010-03-11 18:25:4513#include "base/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2114#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0315#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5616
[email protected]5b96f3772010-09-28 16:30:5717namespace {
18
19// Spin for up to a second waiting for the lock to clear when setting
20// up the database.
21// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2722const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5723
24class ScopedBusyTimeout {
25 public:
26 explicit ScopedBusyTimeout(sqlite3* db)
27 : db_(db) {
28 }
29 ~ScopedBusyTimeout() {
30 sqlite3_busy_timeout(db_, 0);
31 }
32
33 int SetTimeout(base::TimeDelta timeout) {
34 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
35 return sqlite3_busy_timeout(db_,
36 static_cast<int>(timeout.InMilliseconds()));
37 }
38
39 private:
40 sqlite3* db_;
41};
42
43} // namespace
44
[email protected]e5ffd0e42009-09-11 21:30:5645namespace sql {
46
47bool StatementID::operator<(const StatementID& other) const {
48 if (number_ != other.number_)
49 return number_ < other.number_;
50 return strcmp(str_, other.str_) < 0;
51}
52
[email protected]d4799a32010-09-28 22:54:5853ErrorDelegate::ErrorDelegate() {
54}
55
56ErrorDelegate::~ErrorDelegate() {
57}
58
[email protected]e5ffd0e42009-09-11 21:30:5659Connection::StatementRef::StatementRef()
60 : connection_(NULL),
61 stmt_(NULL) {
62}
63
64Connection::StatementRef::StatementRef(Connection* connection,
65 sqlite3_stmt* stmt)
66 : connection_(connection),
67 stmt_(stmt) {
68 connection_->StatementRefCreated(this);
69}
70
71Connection::StatementRef::~StatementRef() {
72 if (connection_)
73 connection_->StatementRefDeleted(this);
74 Close();
75}
76
77void Connection::StatementRef::Close() {
78 if (stmt_) {
79 sqlite3_finalize(stmt_);
80 stmt_ = NULL;
81 }
82 connection_ = NULL; // The connection may be getting deleted.
83}
84
85Connection::Connection()
86 : db_(NULL),
87 page_size_(0),
88 cache_size_(0),
89 exclusive_locking_(false),
90 transaction_nesting_(0),
91 needs_rollback_(false) {
92}
93
94Connection::~Connection() {
95 Close();
96}
97
[email protected]765b44502009-10-02 05:01:4298bool Connection::Open(const FilePath& path) {
[email protected]e5ffd0e42009-09-11 21:30:5699#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42100 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56101#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42102 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56103#endif
[email protected]765b44502009-10-02 05:01:42104}
[email protected]e5ffd0e42009-09-11 21:30:56105
[email protected]765b44502009-10-02 05:01:42106bool Connection::OpenInMemory() {
107 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56108}
109
110void Connection::Close() {
[email protected]4b350052012-02-24 20:40:48111 // sqlite3_close() needs all prepared statements to be finalized.
112 // Release all cached statements, then assert that the client has
113 // released all statements.
[email protected]e5ffd0e42009-09-11 21:30:56114 statement_cache_.clear();
115 DCHECK(open_statements_.empty());
[email protected]4b350052012-02-24 20:40:48116
117 // Additionally clear the prepared statements, because they contain
118 // weak references to this connection. This case has come up when
119 // error-handling code is hit in production.
120 ClearCache();
121
[email protected]e5ffd0e42009-09-11 21:30:56122 if (db_) {
[email protected]e48e05152011-09-14 06:37:46123 // TODO(shess): Some additional code to debug http://crbug.com/95527 .
124 // If you are reading this due to link errors or something, it can
125 // be safely removed.
126#if defined(HAS_SQLITE3_95527)
127 unsigned int nTouched = 0;
128 sqlite3_95527(db_, &nTouched);
129
130 // If a VERY large amount of memory was touched, crash. This
131 // should never happen.
132 // TODO(shess): Pull this in. It should be page_size * page_cache
133 // or something like that, 4M or 16M. For now it's just to
134 // prevent optimization.
135 CHECK_LT(nTouched, 1000*1000*1000U);
136#endif
[email protected]4b350052012-02-24 20:40:48137
138 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56139 sqlite3_close(db_);
140 db_ = NULL;
141 }
142}
143
144void Connection::Preload() {
145 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59146 DLOG(FATAL) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56147 return;
148 }
149
150 // A statement must be open for the preload command to work. If the meta
151 // table doesn't exist, it probably means this is a new database and there
152 // is nothing to preload (so it's OK we do nothing).
153 if (!DoesTableExist("meta"))
154 return;
155 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59156 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56157 return;
158
[email protected]4176eee4b2011-01-26 14:33:32159#if !defined(USE_SYSTEM_SQLITE)
160 // This function is only defined in Chromium's version of sqlite.
161 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06162 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32163#endif
[email protected]e5ffd0e42009-09-11 21:30:56164}
165
166bool Connection::BeginTransaction() {
167 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33168 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56169
170 // When we're going to rollback, fail on this begin and don't actually
171 // mark us as entering the nested transaction.
172 return false;
173 }
174
175 bool success = true;
176 if (!transaction_nesting_) {
177 needs_rollback_ = false;
178
179 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59180 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56181 return false;
182 }
183 transaction_nesting_++;
184 return success;
185}
186
187void Connection::RollbackTransaction() {
188 if (!transaction_nesting_) {
[email protected]eff1fa522011-12-12 23:50:59189 DLOG(FATAL) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56190 return;
191 }
192
193 transaction_nesting_--;
194
195 if (transaction_nesting_ > 0) {
196 // Mark the outermost transaction as needing rollback.
197 needs_rollback_ = true;
198 return;
199 }
200
201 DoRollback();
202}
203
204bool Connection::CommitTransaction() {
205 if (!transaction_nesting_) {
[email protected]eff1fa522011-12-12 23:50:59206 DLOG(FATAL) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56207 return false;
208 }
209 transaction_nesting_--;
210
211 if (transaction_nesting_ > 0) {
212 // Mark any nested transactions as failing after we've already got one.
213 return !needs_rollback_;
214 }
215
216 if (needs_rollback_) {
217 DoRollback();
218 return false;
219 }
220
221 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56222 return commit.Run();
223}
224
[email protected]eff1fa522011-12-12 23:50:59225int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]e5ffd0e42009-09-11 21:30:56226 if (!db_)
227 return false;
[email protected]eff1fa522011-12-12 23:50:59228 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
229}
230
231bool Connection::Execute(const char* sql) {
232 int error = ExecuteAndReturnErrorCode(sql);
[email protected]28fe0ff2012-02-25 00:40:33233 // This needs to be a FATAL log because the error case of arriving here is
234 // that there's a malformed SQL statement. This can arise in development if
235 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59236 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33237 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59238 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56239}
240
[email protected]5b96f3772010-09-28 16:30:57241bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
242 if (!db_)
243 return false;
244
245 ScopedBusyTimeout busy_timeout(db_);
246 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59247 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57248}
249
[email protected]e5ffd0e42009-09-11 21:30:56250bool Connection::HasCachedStatement(const StatementID& id) const {
251 return statement_cache_.find(id) != statement_cache_.end();
252}
253
254scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
255 const StatementID& id,
256 const char* sql) {
257 CachedStatementMap::iterator i = statement_cache_.find(id);
258 if (i != statement_cache_.end()) {
259 // Statement is in the cache. It should still be active (we're the only
260 // one invalidating cached statements, and we'll remove it from the cache
261 // if we do that. Make sure we reset it before giving out the cached one in
262 // case it still has some stuff bound.
263 DCHECK(i->second->is_valid());
264 sqlite3_reset(i->second->stmt());
265 return i->second;
266 }
267
268 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
269 if (statement->is_valid())
270 statement_cache_[id] = statement; // Only cache valid statements.
271 return statement;
272}
273
274scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
275 const char* sql) {
276 if (!db_)
277 return new StatementRef(this, NULL); // Return inactive statement.
278
279 sqlite3_stmt* stmt = NULL;
280 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59281 // This is evidence of a syntax error in the incoming SQL.
282 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]e5ffd0e42009-09-11 21:30:56283 return new StatementRef(this, NULL);
284 }
285 return new StatementRef(this, stmt);
286}
287
[email protected]eff1fa522011-12-12 23:50:59288bool Connection::IsSQLValid(const char* sql) {
289 sqlite3_stmt* stmt = NULL;
290 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
291 return false;
292
293 sqlite3_finalize(stmt);
294 return true;
295}
296
[email protected]1ed78a32009-09-15 20:24:17297bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53298 return DoesTableOrIndexExist(table_name, "table");
299}
300
301bool Connection::DoesIndexExist(const char* index_name) const {
302 return DoesTableOrIndexExist(index_name, "index");
303}
304
305bool Connection::DoesTableOrIndexExist(
306 const char* name, const char* type) const {
[email protected]1ed78a32009-09-15 20:24:17307 // GetUniqueStatement can't be const since statements may modify the
308 // database, but we know ours doesn't modify it, so the cast is safe.
309 Statement statement(const_cast<Connection*>(this)->GetUniqueStatement(
[email protected]e5ffd0e42009-09-11 21:30:56310 "SELECT name FROM sqlite_master "
[email protected]e2cadec82011-12-13 02:00:53311 "WHERE type=? AND name=?"));
312 statement.BindString(0, type);
313 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33314
[email protected]e5ffd0e42009-09-11 21:30:56315 return statement.Step(); // Table exists if any row was returned.
316}
317
318bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17319 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56320 std::string sql("PRAGMA TABLE_INFO(");
321 sql.append(table_name);
322 sql.append(")");
323
[email protected]1ed78a32009-09-15 20:24:17324 // Our SQL is non-mutating, so this cast is OK.
325 Statement statement(const_cast<Connection*>(this)->GetUniqueStatement(
326 sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56327
328 while (statement.Step()) {
329 if (!statement.ColumnString(1).compare(column_name))
330 return true;
331 }
332 return false;
333}
334
335int64 Connection::GetLastInsertRowId() const {
336 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59337 DLOG(FATAL) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56338 return 0;
339 }
340 return sqlite3_last_insert_rowid(db_);
341}
342
[email protected]1ed78a32009-09-15 20:24:17343int Connection::GetLastChangeCount() const {
344 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59345 DLOG(FATAL) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17346 return 0;
347 }
348 return sqlite3_changes(db_);
349}
350
[email protected]e5ffd0e42009-09-11 21:30:56351int Connection::GetErrorCode() const {
352 if (!db_)
353 return SQLITE_ERROR;
354 return sqlite3_errcode(db_);
355}
356
[email protected]767718e52010-09-21 23:18:49357int Connection::GetLastErrno() const {
358 if (!db_)
359 return -1;
360
361 int err = 0;
362 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
363 return -2;
364
365 return err;
366}
367
[email protected]e5ffd0e42009-09-11 21:30:56368const char* Connection::GetErrorMessage() const {
369 if (!db_)
370 return "sql::Connection has no connection.";
371 return sqlite3_errmsg(db_);
372}
373
[email protected]765b44502009-10-02 05:01:42374bool Connection::OpenInternal(const std::string& file_name) {
[email protected]9cfbc922009-11-17 20:13:17375 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59376 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17377 return false;
378 }
379
[email protected]765b44502009-10-02 05:01:42380 int err = sqlite3_open(file_name.c_str(), &db_);
381 if (err != SQLITE_OK) {
382 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29383 Close();
[email protected]765b44502009-10-02 05:01:42384 db_ = NULL;
385 return false;
386 }
387
[email protected]658f8332010-09-18 04:40:43388 // Enable extended result codes to provide more color on I/O errors.
389 // Not having extended result codes is not a fatal problem, as
390 // Chromium code does not attempt to handle I/O errors anyhow. The
391 // current implementation always returns SQLITE_OK, the DCHECK is to
392 // quickly notify someone if SQLite changes.
393 err = sqlite3_extended_result_codes(db_, 1);
394 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
395
[email protected]5b96f3772010-09-28 16:30:57396 // If indicated, lock up the database before doing anything else, so
397 // that the following code doesn't have to deal with locking.
398 // TODO(shess): This code is brittle. Find the cases where code
399 // doesn't request |exclusive_locking_| and audit that it does the
400 // right thing with SQLITE_BUSY, and that it doesn't make
401 // assumptions about who might change things in the database.
402 // http://crbug.com/56559
403 if (exclusive_locking_) {
404 // TODO(shess): This should probably be a full CHECK(). Code
405 // which requests exclusive locking but doesn't get it is almost
406 // certain to be ill-tested.
407 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59408 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57409 }
410
[email protected]c68ce172011-11-24 22:30:27411 const base::TimeDelta kBusyTimeout =
412 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
413
[email protected]765b44502009-10-02 05:01:42414 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57415 // Enforce SQLite restrictions on |page_size_|.
416 DCHECK(!(page_size_ & (page_size_ - 1)))
417 << " page_size_ " << page_size_ << " is not a power of two.";
418 static const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
419 DCHECK_LE(page_size_, kSqliteMaxPageSize);
420 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
421 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59422 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42423 }
424
425 if (cache_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57426 const std::string sql = StringPrintf("PRAGMA cache_size=%d", cache_size_);
427 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59428 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42429 }
430
[email protected]6e0b1442011-08-09 23:23:58431 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59432 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58433 Close();
434 return false;
435 }
436
[email protected]765b44502009-10-02 05:01:42437 return true;
438}
439
[email protected]e5ffd0e42009-09-11 21:30:56440void Connection::DoRollback() {
441 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59442 rollback.Run();
[email protected]e5ffd0e42009-09-11 21:30:56443}
444
445void Connection::StatementRefCreated(StatementRef* ref) {
446 DCHECK(open_statements_.find(ref) == open_statements_.end());
447 open_statements_.insert(ref);
448}
449
450void Connection::StatementRefDeleted(StatementRef* ref) {
451 StatementRefSet::iterator i = open_statements_.find(ref);
452 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59453 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56454 else
455 open_statements_.erase(i);
456}
457
458void Connection::ClearCache() {
459 statement_cache_.clear();
460
461 // The cache clear will get most statements. There may be still be references
462 // to some statements that are held by others (including one-shot statements).
463 // This will deactivate them so they can't be used again.
464 for (StatementRefSet::iterator i = open_statements_.begin();
465 i != open_statements_.end(); ++i)
466 (*i)->Close();
467}
468
[email protected]faa604e2009-09-25 22:38:59469int Connection::OnSqliteError(int err, sql::Statement *stmt) {
470 if (error_delegate_.get())
471 return error_delegate_->OnError(err, this, stmt);
472 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59473 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59474 return err;
475}
476
[email protected]e5ffd0e42009-09-11 21:30:56477} // namespace sql