#include "sql/connection.h"
#include <string.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "sql/statement.h"
#include "third_party/sqlite/sqlite3.h"
namespace {
const int kBusyTimeoutSeconds = 1;
class ScopedBusyTimeout {
public:
explicit ScopedBusyTimeout(sqlite3* db)
: db_(db) {
}
~ScopedBusyTimeout() {
sqlite3_busy_timeout(db_, 0);
}
int SetTimeout(base::TimeDelta timeout) {
DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
return sqlite3_busy_timeout(db_,
static_cast<int>(timeout.InMilliseconds()));
}
private:
sqlite3* db_;
};
}
namespace sql {
bool StatementID::operator<(const StatementID& other) const {
if (number_ != other.number_)
return number_ < other.number_;
return strcmp(str_, other.str_) < 0;
}
ErrorDelegate::ErrorDelegate() {
}
ErrorDelegate::~ErrorDelegate() {
}
Connection::StatementRef::StatementRef()
: connection_(NULL),
stmt_(NULL) {
}
Connection::StatementRef::StatementRef(sqlite3_stmt* stmt)
: connection_(NULL),
stmt_(stmt) {
}
Connection::StatementRef::StatementRef(Connection* connection,
sqlite3_stmt* stmt)
: connection_(connection),
stmt_(stmt) {
connection_->StatementRefCreated(this);
}
Connection::StatementRef::~StatementRef() {
if (connection_)
connection_->StatementRefDeleted(this);
Close();
}
void Connection::StatementRef::Close() {
if (stmt_) {
AssertIOAllowed();
sqlite3_finalize(stmt_);
stmt_ = NULL;
}
connection_ = NULL;
}
Connection::Connection()
: db_(NULL),
page_size_(0),
cache_size_(0),
exclusive_locking_(false),
transaction_nesting_(0),
needs_rollback_(false),
in_memory_(false) {
}
Connection::~Connection() {
Close();
}
bool Connection::Open(const FilePath& path) {
#if defined(OS_WIN)
return OpenInternal(WideToUTF8(path.value()));
#elif defined(OS_POSIX)
return OpenInternal(path.value());
#endif
}
bool Connection::OpenInMemory() {
in_memory_ = true;
return OpenInternal(":memory:");
}
void Connection::Close() {
statement_cache_.clear();
DCHECK(open_statements_.empty());
ClearCache();
if (db_) {
AssertIOAllowed();
sqlite3_close(db_);
db_ = NULL;
}
}
void Connection::Preload() {
AssertIOAllowed();
if (!db_) {
DLOG(FATAL) << "Cannot preload null db";
return;
}
if (!DoesTableExist("meta"))
return;
Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
if (!dummy.Step())
return;
#if !defined(USE_SYSTEM_SQLITE)
sqlite3_preload(db_);
#endif
}
bool Connection::Raze() {
AssertIOAllowed();
if (!db_) {
DLOG(FATAL) << "Cannot raze null db";
return false;
}
if (transaction_nesting_ > 0) {
DLOG(FATAL) << "Cannot raze within a transaction";
return false;
}
sql::Connection null_db;
if (!null_db.OpenInMemory()) {
DLOG(FATAL) << "Unable to open in-memory database.";
return false;
}
{
Statement s(GetUniqueStatement("PRAGMA page_size"));
if (!s.Step())
return false;
const std::string sql = StringPrintf("PRAGMA page_size=%d",
s.ColumnInt(0));
if (!null_db.Execute(sql.c_str()))
return false;
}
{
Statement s(GetUniqueStatement("PRAGMA auto_vacuum"));
if (!s.Step())
return false;
const std::string sql = StringPrintf("PRAGMA auto_vacuum=%d",
s.ColumnInt(0));
if (!null_db.Execute(sql.c_str()))
return false;
}
if (!null_db.Execute("PRAGMA schema_version = 1"))
return false;
sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
null_db.db_, "main");
if (!backup) {
DLOG(FATAL) << "Unable to start sqlite3_backup().";
return false;
}
int rc = sqlite3_backup_step(backup, -1);
int pages = sqlite3_backup_pagecount(backup);
sqlite3_backup_finish(backup);
if (rc == SQLITE_BUSY) {
return false;
}
if (rc != SQLITE_DONE) {
DLOG(FATAL) << "Unable to copy entire null database.";
return false;
}
DCHECK_EQ(pages, 1);
return true;
}
bool Connection::RazeWithTimout(base::TimeDelta timeout) {
if (!db_) {
DLOG(FATAL) << "Cannot raze null db";
return false;
}
ScopedBusyTimeout busy_timeout(db_);
busy_timeout.SetTimeout(timeout);
return Raze();
}
bool Connection::BeginTransaction() {
if (needs_rollback_) {
DCHECK_GT(transaction_nesting_, 0);
return false;
}
bool success = true;
if (!transaction_nesting_) {
needs_rollback_ = false;
Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
if (!begin.Run())
return false;
}
transaction_nesting_++;
return success;
}
void Connection::RollbackTransaction() {
if (!transaction_nesting_) {
DLOG(FATAL) << "Rolling back a nonexistent transaction";
return;
}
transaction_nesting_--;
if (transaction_nesting_ > 0) {
needs_rollback_ = true;
return;
}
DoRollback();
}
bool Connection::CommitTransaction() {
if (!transaction_nesting_) {
DLOG(FATAL) << "Rolling back a nonexistent transaction";
return false;
}
transaction_nesting_--;
if (transaction_nesting_ > 0) {
return !needs_rollback_;
}
if (needs_rollback_) {
DoRollback();
return false;
}
Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
return commit.Run();
}
int Connection::ExecuteAndReturnErrorCode(const char* sql) {
AssertIOAllowed();
if (!db_)
return false;
return sqlite3_exec(db_, sql, NULL, NULL, NULL);
}
bool Connection::Execute(const char* sql) {
int error = ExecuteAndReturnErrorCode(sql);
if (error == SQLITE_ERROR)
DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
return error == SQLITE_OK;
}
bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
if (!db_)
return false;
ScopedBusyTimeout busy_timeout(db_);
busy_timeout.SetTimeout(timeout);
return Execute(sql);
}
bool Connection::HasCachedStatement(const StatementID& id) const {
return statement_cache_.find(id) != statement_cache_.end();
}
scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
const StatementID& id,
const char* sql) {
CachedStatementMap::iterator i = statement_cache_.find(id);
if (i != statement_cache_.end()) {
DCHECK(i->second->is_valid());
sqlite3_reset(i->second->stmt());
return i->second;
}
scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
if (statement->is_valid())
statement_cache_[id] = statement;
return statement;
}
scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
const char* sql) {
AssertIOAllowed();
if (!db_)
return new StatementRef();
sqlite3_stmt* stmt = NULL;
if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK) {
DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
return new StatementRef();
}
return new StatementRef(this, stmt);
}
scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
const char* sql) const {
if (!db_)
return new StatementRef();
sqlite3_stmt* stmt = NULL;
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
return new StatementRef();
}
return new StatementRef(stmt);
}
bool Connection::IsSQLValid(const char* sql) {
AssertIOAllowed();
sqlite3_stmt* stmt = NULL;
if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
return false;
sqlite3_finalize(stmt);
return true;
}
bool Connection::DoesTableExist(const char* table_name) const {
return DoesTableOrIndexExist(table_name, "table");
}
bool Connection::DoesIndexExist(const char* index_name) const {
return DoesTableOrIndexExist(index_name, "index");
}
bool Connection::DoesTableOrIndexExist(
const char* name, const char* type) const {
const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
Statement statement(GetUntrackedStatement(kSql));
statement.BindString(0, type);
statement.BindString(1, name);
return statement.Step();
}
bool Connection::DoesColumnExist(const char* table_name,
const char* column_name) const {
std::string sql("PRAGMA TABLE_INFO(");
sql.append(table_name);
sql.append(")");
Statement statement(GetUntrackedStatement(sql.c_str()));
while (statement.Step()) {
if (!statement.ColumnString(1).compare(column_name))
return true;
}
return false;
}
int64 Connection::GetLastInsertRowId() const {
if (!db_) {
DLOG(FATAL) << "Illegal use of connection without a db";
return 0;
}
return sqlite3_last_insert_rowid(db_);
}
int Connection::GetLastChangeCount() const {
if (!db_) {
DLOG(FATAL) << "Illegal use of connection without a db";
return 0;
}
return sqlite3_changes(db_);
}
int Connection::GetErrorCode() const {
if (!db_)
return SQLITE_ERROR;
return sqlite3_errcode(db_);
}
int Connection::GetLastErrno() const {
if (!db_)
return -1;
int err = 0;
if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
return -2;
return err;
}
const char* Connection::GetErrorMessage() const {
if (!db_)
return "sql::Connection has no connection.";
return sqlite3_errmsg(db_);
}
bool Connection::OpenInternal(const std::string& file_name) {
AssertIOAllowed();
if (db_) {
DLOG(FATAL) << "sql::Connection is already open.";
return false;
}
int err = sqlite3_open(file_name.c_str(), &db_);
if (err != SQLITE_OK) {
OnSqliteError(err, NULL);
Close();
db_ = NULL;
return false;
}
err = sqlite3_extended_result_codes(db_, 1);
DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
if (exclusive_locking_) {
if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
}
ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
const base::TimeDelta kBusyTimeout =
base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
if (page_size_ != 0) {
DCHECK(!(page_size_ & (page_size_ - 1)))
<< " page_size_ " << page_size_ << " is not a power of two.";
static const int kSqliteMaxPageSize = 32768;
DCHECK_LE(page_size_, kSqliteMaxPageSize);
const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
}
if (cache_size_ != 0) {
const std::string sql = StringPrintf("PRAGMA cache_size=%d", cache_size_);
if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
}
if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
Close();
return false;
}
return true;
}
void Connection::DoRollback() {
Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
rollback.Run();
needs_rollback_ = false;
}
void Connection::StatementRefCreated(StatementRef* ref) {
DCHECK(open_statements_.find(ref) == open_statements_.end());
open_statements_.insert(ref);
}
void Connection::StatementRefDeleted(StatementRef* ref) {
StatementRefSet::iterator i = open_statements_.find(ref);
if (i == open_statements_.end())
DLOG(FATAL) << "Could not find statement";
else
open_statements_.erase(i);
}
void Connection::ClearCache() {
statement_cache_.clear();
for (StatementRefSet::iterator i = open_statements_.begin();
i != open_statements_.end(); ++i)
(*i)->Close();
}
int Connection::OnSqliteError(int err, sql::Statement *stmt) {
if (error_delegate_.get())
return error_delegate_->OnError(err, this, stmt);
DLOG(FATAL) << GetErrorMessage();
return err;
}
}