1 // Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
2 // Use of this source code is governed by a apache 2.0 license that can be
3 // found in the LICENSE file.
5 #include "src/sqlite_connection.h"
11 #include <boost/optional.hpp>
16 #include "src/sqlite_statement.h"
17 #include "src/utils/logging.h"
21 SQLiteConnection::SQLiteConnection(std::string path, bool readonly)
22 : path_(std::move(path)), db_(nullptr) {
23 if (!Connect(readonly))
24 LOG(ERROR) << "Failed to connect db";
27 SQLiteConnection::~SQLiteConnection() {
31 bool SQLiteConnection::Connect(bool readonly) {
34 flags = SQLITE_OPEN_READONLY;
36 flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
39 int r = sqlite3_open_v2(path_.c_str(), &db, flags, nullptr);
41 LOG(ERROR) << "Failed to open sqlite3 db("
42 << path_ << "). Error code: " << r;
47 r = sqlite3_exec(db, "PRAGMA foreign_keys=ON", nullptr, nullptr, nullptr);
49 LOG(ERROR) << "Failed to enable foreign key support: " << r;
54 bool SQLiteConnection::Disconnect() {
56 sqlite3_close_v2(db_);
62 bool SQLiteConnection::Execute(const std::string& command) {
64 LOG(ERROR) << "Invalid SQLite connection";
68 int r = sqlite3_exec(db_, command.c_str(), nullptr, nullptr, nullptr);
70 LOG(ERROR) << "Execute command(" << command << ") failed: "
78 bool SQLiteConnection::BeginTransaction() {
79 return Execute("BEGIN EXCLUSIVE");
82 bool SQLiteConnection::CommitTransaction() {
83 return Execute("COMMIT");
86 bool SQLiteConnection::RollbackTransaction() {
87 return Execute("ROLLBACK");
90 std::string SQLiteConnection::GetErrorMessage() const {
91 return sqlite3_errmsg(db_);
94 std::shared_ptr<SQLStatement> SQLiteConnection::PrepareStatement(
95 const std::string& query) {
97 LOG(ERROR) << "Invalid SQLite connection";
102 int r = sqlite3_prepare_v2(db_, query.c_str(), query.length(), &stmt,
104 if (r != SQLITE_OK) {
105 LOG(ERROR) << "sqlite3_prepare_v2() failed: " << GetErrorMessage();
108 return std::shared_ptr<SQLStatement>(new SQLiteStatement(this, stmt));
111 bool SQLiteConnection::IsValid() {
117 } // namespace capmgr