aboutsummaryrefslogtreecommitdiff
path: root/src/sql/SqlExec.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/sql/SqlExec.cpp')
-rw-r--r--src/sql/SqlExec.cpp72
1 files changed, 72 insertions, 0 deletions
diff --git a/src/sql/SqlExec.cpp b/src/sql/SqlExec.cpp
new file mode 100644
index 0000000..732b2f1
--- /dev/null
+++ b/src/sql/SqlExec.cpp
@@ -0,0 +1,72 @@
+#include "../../include/odhtdb/sql/SqlExec.hpp"
+#include <sqlite3.h>
+
+namespace odhtdb
+{
+ SqlExec::SqlExec(sqlite3 *_db, const char *sql) :
+ db(_db),
+ stmt(nullptr)
+ {
+ int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr);
+ if(rc != SQLITE_OK)
+ {
+ std::string errMsg = "Failed to prepare sqlite statement, error: ";
+ errMsg += sqlite3_errmsg(db);
+ sqlite3_exec(db, "ROLLBACK", 0, 0, 0);
+ throw SqlExecException(errMsg);
+ }
+ }
+
+ SqlExec::~SqlExec()
+ {
+ sqlite3_finalize(stmt);
+ }
+
+ void SqlExec::execWithArgs(std::initializer_list<SqlArg> args)
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+
+ sqlite3_reset(stmt);
+ sqlite3_clear_bindings(stmt);
+
+ int numParams = sqlite3_bind_parameter_count(stmt);
+ if(args.size() != numParams)
+ {
+ std::string errMsg = "Failed to prepare sqlite statement, error: Sql has ";
+ errMsg += std::to_string(numParams);
+ errMsg += " parameters, got ";
+ errMsg += std::to_string(args.size());
+ errMsg += " arguments";
+ sqlite3_exec(db, "ROLLBACK", 0, 0, 0);
+ throw SqlExecException(errMsg);
+ }
+
+ int paramIndex = 1;
+ for(const SqlArg &arg : args)
+ {
+ int rc = arg.bind(stmt, paramIndex);
+ if(rc != SQLITE_OK)
+ {
+ std::string errMsg = "Failed to bind param, error code: ";
+ errMsg += std::to_string(rc);
+ sqlite3_exec(db, "ROLLBACK", 0, 0, 0);
+ throw SqlExecException(errMsg);
+ }
+ ++paramIndex;
+ }
+
+ int rc = sqlite3_step(stmt);
+ if(rc != SQLITE_DONE)
+ {
+ std::string errMsg = "Failed to perform sql exec, error: ";
+ errMsg += sqlite3_errmsg(db);
+ sqlite3_exec(db, "ROLLBACK", 0, 0, 0);
+ throw SqlExecException(errMsg);
+ }
+ }
+
+ void SqlExec::exec()
+ {
+ execWithArgs({});
+ }
+}