Fix static analysis issues
[platform/core/base/bundle.git] / tizen-database / database.hpp
index 492af5f..2ed94fa 100644 (file)
@@ -47,73 +47,147 @@ void for_(F func) {
   for_(func, std::make_index_sequence<N>());
 }
 
-using DbType = std::optional<std::variant<int, double, std::string,
+using DbType = std::optional<std::variant<int64_t, double, std::string,
     std::vector<unsigned char>>>;
 
+class DbException : public std::runtime_error {
+ public:
+  explicit DbException(const std::string& msg, int code = SQLITE_ERROR)
+      : std::runtime_error(msg), code_(code) {
+  }
+
+  DbException(const std::string& msg, int code, const std::string& file,
+      int line) : std::runtime_error(msg), code_(code) {
+    msg_ = msg + " at " + file + ":" + std::to_string(line);
+  }
+
+  int code() const {
+    return code_;
+  }
+
+  const char* msg() const {
+    if (msg_.empty())
+      return what();
+    return msg_.c_str();
+  }
+
+ private:
+  int code_;
+  std::string msg_;
+};
+
 class AutoDbType {
  public:
   AutoDbType() = default;
-  AutoDbType(DbType db_type) : db_type_(db_type) {}
+  explicit AutoDbType(DbType db_type, int real_type)
+      : db_type_(db_type), real_type_(real_type) {}
+
+  int GetType() const {
+    return real_type_;
+  }
 
   explicit operator int () {
     if (!db_type_)
-      throw std::runtime_error("invalid type conversion from nullopt to int");
-    return std::get<int>(*db_type_);
+      throw DbException("invalid type conversion from nullopt to int");
+    if (real_type_ != SQLITE_INTEGER)
+      throw DbException("invalid type conversion to int");
+
+    return std::get<int64_t>(*db_type_);
+  }
+
+  explicit operator int64_t () {
+    if (!db_type_)
+      throw DbException("invalid type conversion from nullopt to int64_t");
+    if (real_type_ != SQLITE_INTEGER)
+      throw DbException("invalid type conversion to int64_t");
+
+    return std::get<int64_t>(*db_type_);
   }
 
   explicit operator std::string () {
     if (!db_type_) {
-      throw std::runtime_error(
+      throw DbException(
           "invalid type conversion from nullopt to string");
     }
 
+    if (real_type_ != SQLITE_TEXT)
+      throw DbException("invalid type conversion to string");
+
     return std::get<std::string>(*db_type_);
   }
 
   explicit operator double () {
     if (!db_type_) {
-      throw std::runtime_error(
+      throw DbException(
           "invalid type conversion from nullopt to double");
     }
 
+    if (real_type_ != SQLITE_FLOAT)
+      throw DbException("invalid type conversion to double");
+
     return std::get<double>(*db_type_);
   }
 
   explicit operator std::vector<unsigned char> () {
     if (!db_type_) {
-      throw std::runtime_error(
+      throw DbException(
           "invalid type conversion from nullopt to std::vector<unsigned char>");
     }
 
+    if (real_type_ != SQLITE_BLOB)
+      throw DbException("invalid type conversion to std::vector<unsigned char>");
+
     return std::get<std::vector<unsigned char>>(*db_type_);
   }
 
   operator std::optional<int> () {
     if (!db_type_)
       return std::nullopt;
-    return std::get<int>(*db_type_);
+    if (real_type_ != SQLITE_INTEGER)
+      throw DbException("invalid type conversion to int");
+
+    return std::get<int64_t>(*db_type_);
+  }
+
+  operator std::optional<int64_t> () {
+    if (!db_type_)
+      return std::nullopt;
+    if (real_type_ != SQLITE_INTEGER)
+      throw DbException("invalid type conversion to int64_t");
+
+    return std::get<int64_t>(*db_type_);
   }
 
   operator std::optional<std::string> () {
     if (!db_type_)
       return std::nullopt;
+    if (real_type_ != SQLITE_TEXT)
+      throw DbException("invalid type conversion to string");
+
     return std::get<std::string>(*db_type_);
   }
 
   operator std::optional<double> () {
     if (!db_type_)
       return std::nullopt;
+    if (real_type_ != SQLITE_FLOAT)
+      throw DbException("invalid type conversion to double");
+
     return std::get<double>(*db_type_);
   }
 
   operator std::optional<std::vector<unsigned char>> () {
     if (!db_type_)
       return std::nullopt;
+    if (real_type_ != SQLITE_BLOB)
+      throw DbException("invalid type conversion to std::vector<unsigned char>");
+
     return std::get<std::vector<unsigned char>>(*db_type_);
   }
 
  private:
   DbType db_type_;
+  int real_type_ = SQLITE_NULL;
 };
 
 using _ = AutoDbType;
@@ -141,10 +215,10 @@ class Database {
       return *this;
     }
 
-    TransactionGuard(sqlite3* db) : db_(db) {
-      if (sqlite3_exec(db, "BEGIN DEFERRED", nullptr, nullptr, nullptr)
-          != SQLITE_OK) {
-        throw std::runtime_error("begin transaction failed");
+    explicit TransactionGuard(sqlite3* db) : db_(db) {
+      int r = sqlite3_exec(db, "BEGIN DEFERRED", nullptr, nullptr, nullptr);
+      if (r != SQLITE_OK) {
+        throw DbException("begin transaction failed", r);
       }
     }
 
@@ -171,12 +245,33 @@ class Database {
    public:
     Sql(std::string query) : query_(std::move(query)) {}
 
+    Sql& Bind(const char* val) {
+      if (val == nullptr) {
+        bindings_.push_back(DbType(std::nullopt));
+      } else {
+        std::string str = val;
+        if (empty_string_as_null_ && str.empty())
+          bindings_.push_back(DbType(std::nullopt));
+        else
+          bindings_.push_back(DbType(std::move(str)));
+      }
+      return *this;
+    }
+
     Sql& Bind(std::string val) {
-      bindings_.push_back(DbType(std::move(val)));
+      if (empty_string_as_null_ && val.empty())
+        bindings_.push_back(DbType(std::nullopt));
+      else
+        bindings_.push_back(DbType(std::move(val)));
       return *this;
     }
 
     Sql& Bind(int val) {
+      bindings_.push_back(DbType(static_cast<int64_t>(val)));
+      return *this;
+    }
+
+    Sql& Bind(int64_t val) {
       bindings_.push_back(DbType(val));
       return *this;
     }
@@ -187,7 +282,10 @@ class Database {
     }
 
     Sql& Bind(std::vector<unsigned char> val) {
-      bindings_.push_back(DbType(std::move(val)));
+      if (empty_vector_as_null_ && val.empty())
+        bindings_.push_back(DbType(std::nullopt));
+      else
+        bindings_.push_back(DbType(std::move(val)));
       return *this;
     }
 
@@ -196,12 +294,33 @@ class Database {
       return *this;
     }
 
+    Sql& Bind(int pos, const char* val) {
+      if (val == nullptr) {
+        binding_map_[pos] = DbType(std::nullopt);
+      } else {
+        std::string str = val;
+        if (empty_string_as_null_ && str.empty())
+          binding_map_[pos] = DbType(std::nullopt);
+        else
+          binding_map_[pos] = DbType(std::move(str));
+      }
+      return *this;
+    }
+
     Sql& Bind(int pos, std::string val) {
-      binding_map_[pos] = DbType(std::move(val));
+      if (empty_string_as_null_ && val.empty())
+        binding_map_[pos] = DbType(std::nullopt);
+      else
+        binding_map_[pos] = DbType(std::move(val));
       return *this;
     }
 
     Sql& Bind(int pos, int val) {
+      binding_map_[pos] = DbType(static_cast<int64_t>(val));
+      return *this;
+    }
+
+    Sql& Bind(int pos, int64_t val) {
       binding_map_[pos] = DbType(val);
       return *this;
     }
@@ -212,7 +331,10 @@ class Database {
     }
 
     Sql& Bind(int pos, std::vector<unsigned char> val) {
-      binding_map_[pos] = DbType(std::move(val));
+      if (empty_vector_as_null_ && val.empty())
+        binding_map_[pos] = DbType(std::nullopt);
+      else
+        binding_map_[pos] = DbType(std::move(val));
       return *this;
     }
 
@@ -221,12 +343,33 @@ class Database {
       return *this;
     }
 
+    Sql& Bind(std::string name, const char* val) {
+      if (val == nullptr) {
+        binding_name_map_[std::move(name)] = DbType(std::nullopt);
+      } else {
+        std::string str = val;
+        if (empty_string_as_null_ && str.empty())
+          binding_name_map_[std::move(name)] = DbType(std::nullopt);
+        else
+          binding_name_map_[std::move(name)] = DbType(std::move(str));
+      }
+      return *this;
+    }
+
     Sql& Bind(std::string name, std::string val) {
-      binding_name_map_[std::move(name)] = DbType(std::move(val));
+      if (empty_string_as_null_ && val.empty())
+        binding_name_map_[std::move(name)] = DbType(std::nullopt);
+      else
+        binding_name_map_[std::move(name)] = DbType(std::move(val));
       return *this;
     }
 
     Sql& Bind(std::string name, int val) {
+      binding_name_map_[std::move(name)] = DbType(static_cast<int64_t>(val));
+      return *this;
+    }
+
+    Sql& Bind(std::string name, int64_t val) {
       binding_name_map_[std::move(name)] = DbType(val);
       return *this;
     }
@@ -237,7 +380,10 @@ class Database {
     }
 
     Sql& Bind(std::string name, std::vector<unsigned char> val) {
-      binding_name_map_[std::move(name)] = DbType(std::move(val));
+      if (empty_vector_as_null_ && val.empty())
+        binding_name_map_[std::move(name)] = DbType(std::nullopt);
+      else
+        binding_name_map_[std::move(name)] = DbType(std::move(val));
       return *this;
     }
 
@@ -262,11 +408,32 @@ class Database {
       return query_;
     }
 
+    Sql& SetEmptyStringAsNull(bool as_null) {
+      empty_string_as_null_ = as_null;
+      return *this;
+    }
+
+    Sql& SetEmptyVectorAsNull(bool as_null) {
+      empty_vector_as_null_ = as_null;
+      return *this;
+    }
+
+    Sql& Reset() {
+      bindings_.clear();
+      binding_map_.clear();
+      binding_name_map_.clear();
+      empty_string_as_null_ = false;
+      empty_vector_as_null_ = false;
+      return *this;
+    }
+
    private:
     std::string query_;
     std::vector<DbType> bindings_;
     std::map<int, DbType> binding_map_;
     std::map<std::string, DbType> binding_name_map_;
+    bool empty_string_as_null_ = false;
+    bool empty_vector_as_null_ = false;
   };
 
   class Result {
@@ -283,6 +450,8 @@ class Database {
     Result(Result&& r) noexcept {
       stmt_ = r.stmt_;
       r.stmt_ = nullptr;
+      query_ = std::move(r.query_);
+      is_done_ = r.is_done_;
     }
 
     Result& operator = (Result&& r) noexcept {
@@ -291,6 +460,8 @@ class Database {
           sqlite3_finalize(stmt_);
         stmt_ = r.stmt_;
         r.stmt_ = nullptr;
+        query_ = std::move(r.query_);
+        is_done_ = r.is_done_;
       }
 
       return *this;
@@ -298,7 +469,17 @@ class Database {
 
     class Record {
      public:
-      Record(const sqlite3_stmt* stmt) : stmt_(stmt) {}
+      explicit Record(const sqlite3_stmt* stmt) : stmt_(stmt) {}
+
+      std::optional<std::string> GetString(int pos) const {
+        sqlite3_stmt* stmt = const_cast<sqlite3_stmt*>(stmt_);
+        const char* text = reinterpret_cast<const char*>(
+            sqlite3_column_text(stmt, pos));
+        if (!text)
+          return std::nullopt;
+
+        return text;
+      }
 
       AutoDbType Get(int pos) const {
         sqlite3_stmt* stmt = const_cast<sqlite3_stmt*>(stmt_);
@@ -309,7 +490,7 @@ class Database {
           dbt = DbType(reinterpret_cast<const char*>(
               sqlite3_column_text(stmt, pos)));
         } else if (type == SQLITE_INTEGER) {
-          dbt = DbType(sqlite3_column_int(stmt, pos));
+          dbt = DbType(static_cast<int64_t>(sqlite3_column_int64(stmt, pos)));
         } else if (type == SQLITE_FLOAT) {
           dbt = DbType(sqlite3_column_double(stmt, pos));
         } else if (type == SQLITE_BLOB) {
@@ -318,17 +499,17 @@ class Database {
           int len = sqlite3_column_bytes(stmt, pos);
 
           if (!val || len < 0) {
-            throw std::runtime_error("invalid blob");;
+            throw DbException("invalid blob");;
           } else {
             dbt = DbType(std::vector<unsigned char>(val, val + len));
           }
         } else if (type == SQLITE_NULL) {
           dbt = DbType(std::nullopt);
         } else {
-          throw std::runtime_error("invalid column type");
+          throw DbException("invalid column type", type);
         }
 
-        return AutoDbType(dbt);
+        return AutoDbType(dbt, type);
       }
 
       template <typename ...Types>
@@ -348,7 +529,7 @@ class Database {
 
     class Iterator {
      public:
-      Iterator(sqlite3_stmt* stmt) : stmt_(stmt) {}
+      explicit Iterator(sqlite3_stmt* stmt) : stmt_(stmt) {}
 
       Record operator*() { return Record(stmt_); }
 
@@ -367,6 +548,8 @@ class Database {
     };
 
     Iterator begin() const {
+      if (is_done_)
+        return Iterator(nullptr);
       return Iterator(stmt_);
     }
 
@@ -374,19 +557,19 @@ class Database {
       return Iterator(nullptr);
     }
 
-    explicit operator bool() {
+    operator bool() const {
       if (stmt_ == nullptr)
         return false;
       return true;
     }
 
-    explicit operator int() {
+    explicit operator int() const {
       if (db_ == nullptr)
         return SQLITE_ERROR;
       return sqlite3_errcode(db_);
     }
 
-    operator const char*() {
+    explicit operator const char*() const {
       if (db_ == nullptr)
         return "";
       return sqlite3_errmsg(db_);
@@ -445,24 +628,43 @@ class Database {
       return std::nullopt;
     }
 
+    sqlite3_stmt* GetRaw() const {
+      return stmt_;
+    }
+
+    const std::string& GetQuery() const {
+      return query_;
+    }
+
+    void SetDone(bool is_done) {
+      is_done_ = is_done;
+    }
+
+    size_t GetColumnCount() const {
+      return sqlite3_column_count(stmt_);
+    }
+
    private:
     friend class Database;
-    Result(sqlite3_stmt* stmt, sqlite3* db) : stmt_(stmt), db_(db) {}
+    Result(sqlite3_stmt* stmt, sqlite3* db, std::string query, bool is_done)
+        : stmt_(stmt), db_(db), query_(std::move(query)), is_done_(is_done) {}
 
     sqlite3_stmt* stmt_ = nullptr;
     sqlite3* db_ = nullptr;
+    std::string query_;
+    bool is_done_ = false;
   };
 
   Database(std::string db, int flags) {
     int r = sqlite3_open_v2(db.c_str(), &db_, flags, nullptr);
     if (r != SQLITE_OK)
-      throw std::runtime_error("open failed");
+      throw DbException("open failed", r);
   }
 
   Database(std::string db, int flags, std::function<bool(int)> busy_handler) {
     int r = sqlite3_open_v2(db.c_str(), &db_, flags, nullptr);
     if (r != SQLITE_OK)
-      throw std::runtime_error("sqlite3_open_v2() failed");
+      throw DbException("sqlite3_open_v2() failed", r);
 
     busy_handler_ = std::move(busy_handler);
     r = sqlite3_busy_handler(db_, [](void* data, int count) {
@@ -474,7 +676,7 @@ class Database {
 
     if (r != SQLITE_OK) {
       sqlite3_close_v2(db_);
-      throw std::runtime_error("sqlite3_busy_handler() failed");
+      throw DbException("sqlite3_busy_handler() failed", r);
     }
   }
 
@@ -492,7 +694,7 @@ class Database {
     db.db_ = nullptr;
   }
 
-  explicit operator bool() {
+  explicit operator bool() const {
     if (db_ == nullptr)
       return false;
     return true;
@@ -509,19 +711,31 @@ class Database {
     return *this;
   }
 
-  TransactionGuard CreateTransactionGuard() {
+  TransactionGuard CreateTransactionGuard() const {
     return TransactionGuard(db_);
   }
 
+  Result Prepare(const Sql& sql) const {
+    if (!db_)
+      throw DbException("Not opened");
+
+    sqlite3_stmt* stmt = nullptr;
+    int r = sqlite3_prepare_v2(db_, sql.GetQuery().c_str(),
+        -1, &stmt, nullptr);
+    if (r != SQLITE_OK)
+      return { nullptr, nullptr, "", true };
+    return { stmt, db_, sql.GetQuery(), false };
+  }
+
   Result Exec(const Sql& sql) const {
     if (!db_)
-      throw std::runtime_error("Not opened");
+      throw DbException("Not opened");
 
     sqlite3_stmt* stmt = nullptr;
     int r = sqlite3_prepare_v2(db_, sql.GetQuery().c_str(),
         -1, &stmt, nullptr);
     if (r != SQLITE_OK) {
-      return { nullptr, nullptr };
+      return { nullptr, nullptr, "", true };
     }
 
     std::unique_ptr<sqlite3_stmt, decltype(sqlite3_finalize)*> stmt_auto(stmt,
@@ -538,16 +752,70 @@ class Database {
     for (const auto& i : sql.GetBindingNameMap()) {
       int pos = sqlite3_bind_parameter_index(stmt, i.first.c_str());
       if (pos == 0)
-        throw std::runtime_error("Invalid binding");
+        throw DbException("Invalid binding");
       Bind(pos, i.second, stmt);
     }
 
     r = sqlite3_step(stmt);
     if (r != SQLITE_ROW && r != SQLITE_DONE) {
-      return { nullptr, db_ };
+      return { nullptr, db_, "", true };
+    }
+
+    return { stmt_auto.release(), db_, sql.GetQuery(),
+        r == SQLITE_DONE ? true : false };
+  }
+
+  bool Exec(const Sql& sql, Result& previous_stmt) const {
+    if (sql.GetQuery() != previous_stmt.GetQuery())
+      throw DbException("Query is different");
+
+    sqlite3_stmt* stmt = previous_stmt.GetRaw();
+    if (!stmt)
+      return false;
+
+    int r = sqlite3_reset(stmt);
+    if (r != SQLITE_ROW && r != SQLITE_DONE && r != SQLITE_OK)
+      return false;
+
+    int pos = 1;
+    for (const auto& i : sql.GetBindings()) {
+      Bind(pos++, i, stmt);
     }
 
-    return { stmt_auto.release(), db_ };
+    for (const auto& i : sql.GetBindingMap()) {
+      Bind(i.first, i.second, stmt);
+    }
+
+    for (const auto& i : sql.GetBindingNameMap()) {
+      int pos = sqlite3_bind_parameter_index(stmt, i.first.c_str());
+      if (pos == 0)
+        throw DbException("Invalid binding");
+      Bind(pos, i.second, stmt);
+    }
+
+    r = sqlite3_step(stmt);
+    if (r != SQLITE_ROW && r != SQLITE_DONE)
+      return false;
+
+    previous_stmt.SetDone(r == SQLITE_DONE ? true : false);
+    return true;
+  }
+
+  void OneStepExec(const Sql& sql) const {
+    char* errmsg = nullptr;
+    int ret = sqlite3_exec(db_, sql.GetQuery().c_str(), nullptr, nullptr,
+        &errmsg);
+    if (ret != SQLITE_OK) {
+      std::unique_ptr<char, decltype(sqlite3_free)*> errmsg_auto(
+          errmsg, sqlite3_free);
+      throw DbException(errmsg);
+    }
+  }
+
+  sqlite3* GetRaw() const {
+    if (!db_)
+      throw DbException("Not opened");
+    return db_;
   }
 
  private:
@@ -556,7 +824,7 @@ class Database {
     if (!type) {
       r = sqlite3_bind_null(stmt, pos);
       if (r != SQLITE_OK) {
-        throw std::runtime_error("Invalid binding");
+        throw DbException("Invalid binding", r);
       }
 
       return;
@@ -565,8 +833,8 @@ class Database {
     if (const std::string* pstr = std::get_if<std::string>(&(*type))) {
       r = sqlite3_bind_text(stmt, pos, (*pstr).c_str(), -1,
           SQLITE_TRANSIENT);
-    } else if (const int* pint = std::get_if<int>(&(*type))) {
-      r = sqlite3_bind_int(stmt, pos, (*pint));
+    } else if (const int64_t* pint = std::get_if<int64_t>(&(*type))) {
+      r = sqlite3_bind_int64(stmt, pos, (*pint));
     } else if (const double* pdouble = std::get_if<double>(&(*type))) {
       r = sqlite3_bind_double(stmt, pos, (*pdouble));
     } else if (const std::vector<unsigned char>* pvector =
@@ -578,7 +846,7 @@ class Database {
     }
 
     if (r != SQLITE_OK) {
-      throw std::runtime_error("Invalid binding");
+      throw DbException("Invalid binding");
     }
   }