|
@@ -0,0 +1,93 @@
|
|
|
|
|
+#include "sqlitedb.h"
|
|
|
|
|
+
|
|
|
|
|
+#include <iostream>
|
|
|
|
|
+#include <sstream>
|
|
|
|
|
+#include <sqlite3.h>
|
|
|
|
|
+
|
|
|
|
|
+SqliteDb::SqliteDb(const std::string& dbPath)
|
|
|
|
|
+{
|
|
|
|
|
+ open(dbPath);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+SqliteDb::~SqliteDb()
|
|
|
|
|
+{
|
|
|
|
|
+ close();
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+bool SqliteDb::execute(const std::string &sql)
|
|
|
|
|
+{
|
|
|
|
|
+ std::ignore = sql;
|
|
|
|
|
+ return false;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+std::string SqliteDb::readTable(const std::string &table, const std::vector<Param>& params)
|
|
|
|
|
+{
|
|
|
|
|
+ std::string sql = "SELECT * FROM " + table;
|
|
|
|
|
+
|
|
|
|
|
+ std::stringstream clause;
|
|
|
|
|
+ std::string separator = "";
|
|
|
|
|
+ for (const auto& [param, value] : params)
|
|
|
|
|
+ {
|
|
|
|
|
+ clause << separator << param << "=" << value;
|
|
|
|
|
+ separator = " AND ";
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ clause.seekp(-5, std::ios_base::end);
|
|
|
|
|
+ if (!params.empty())
|
|
|
|
|
+ sql += " WHERE " + clause.str();
|
|
|
|
|
+
|
|
|
|
|
+ sqlite3_stmt* stmt;
|
|
|
|
|
+
|
|
|
|
|
+ int rc = sqlite3_prepare_v2(mDb, sql.c_str(), -1, &stmt, nullptr);
|
|
|
|
|
+ if (rc != SQLITE_OK) {
|
|
|
|
|
+ return std::string("SQL error: ") + sqlite3_errmsg(mDb);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ int colCount = sqlite3_column_count(stmt);
|
|
|
|
|
+
|
|
|
|
|
+ std::stringstream res;
|
|
|
|
|
+
|
|
|
|
|
+ res << "[";
|
|
|
|
|
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
|
|
|
+ separator = "";
|
|
|
|
|
+ res << "{";
|
|
|
|
|
+ for (int i = 0; i < colCount; i++) {
|
|
|
|
|
+ const char* colName = sqlite3_column_name(stmt, i);
|
|
|
|
|
+ const char* declType = sqlite3_column_decltype(stmt, i);
|
|
|
|
|
+ const char* colValue = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
|
|
|
|
|
+ std::string type( declType );
|
|
|
|
|
+ bool needQuote = (type == "TEXT" || type == "DATE" || !colValue);
|
|
|
|
|
+
|
|
|
|
|
+ res << separator << colName << ":";
|
|
|
|
|
+ if(needQuote)
|
|
|
|
|
+ res << "\"";
|
|
|
|
|
+ res << (colValue ? colValue : "null");
|
|
|
|
|
+ if(needQuote)
|
|
|
|
|
+ res << "\"";
|
|
|
|
|
+
|
|
|
|
|
+ separator = ",";
|
|
|
|
|
+ }
|
|
|
|
|
+ res << "},";
|
|
|
|
|
+ }
|
|
|
|
|
+ res.seekp(-1, std::ios_base::end);
|
|
|
|
|
+ res << "]";
|
|
|
|
|
+
|
|
|
|
|
+ sqlite3_finalize(stmt);
|
|
|
|
|
+
|
|
|
|
|
+ return res.str();
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+void SqliteDb::open(const std::string &dbPath)
|
|
|
|
|
+{
|
|
|
|
|
+ char *zErrMsg = 0;
|
|
|
|
|
+ int rc = sqlite3_open(dbPath.c_str(), &mDb);
|
|
|
|
|
+ if (rc) {
|
|
|
|
|
+ std::cerr << "Can't open database: " << sqlite3_errmsg(mDb) << std::endl;
|
|
|
|
|
+ sqlite3_free(zErrMsg);
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+void SqliteDb::close()
|
|
|
|
|
+{
|
|
|
|
|
+ sqlite3_close(mDb);
|
|
|
|
|
+}
|