aboutsummaryrefslogtreecommitdiff
path: root/src/sql/SqlExec.cpp
blob: bdb0fbd527a537499883a40ab5530d5d8519361e (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
#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);
            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);
        }
        
        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({});
    }
}