aboutsummaryrefslogtreecommitdiff
path: root/src/sql/SqlExec.cpp
blob: 52d953fc4d692082dd4fa84c41b6727761a8873e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "../../include/odhtdb/sql/SqlExec.hpp"
#include "../../include/odhtdb/Log.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);
            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";
            throw SqlExecException(errMsg);
        }
        
#ifdef ODHTDB_SQL_DEBUG
        Log::debug("Executing sql exec: %s; args(%u): ", sqlite3_sql(stmt), args.size());
        usize i = 0;
        for(const SqlArg &arg : args)
        {
            Log::debug("arg(%u): %s", i, arg.toString().c_str());
            ++i;
        }
#endif
        
        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);
                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);
            throw SqlExecException(errMsg);
        }
    }
    
    void SqlExec::exec()
    {
        execWithArgs({});
    }
}