sqlite.cpp 2.29 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <migraphx/sqlite.hpp>
#include <migraphx/manage_ptr.hpp>
#include <migraphx/errors.hpp>
#include <sqlite3.h>
#include <algorithm>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {

using sqlite3_ptr = MIGRAPHX_MANAGE_PTR(sqlite3*, sqlite3_close);

struct sqlite_impl
{
    sqlite3* get() const { return ptr.get(); }
    void open(const fs::path& p, int flags)
    {
        sqlite3* ptr_tmp = nullptr;
Paul's avatar
Format  
Paul committed
18
19
20
        int rc           = sqlite3_open_v2(p.string().c_str(), &ptr_tmp, flags, nullptr);
        ptr              = sqlite3_ptr{ptr_tmp};
        if(rc != 0)
Paul's avatar
Paul committed
21
22
23
            MIGRAPHX_THROW("error opening " + p.string() + ": " + error_message());
    }

Paul's avatar
Format  
Paul committed
24
25
    template <class F>
    void exec(const char* sql, F f)
Paul's avatar
Paul committed
26
27
28
29
    {
        auto callback = [](void* obj, auto... xs) -> int {
            try
            {
Paul's avatar
Paul committed
30
                const auto* g = static_cast<const F*>(obj);
Paul's avatar
Paul committed
31
32
33
34
35
36
37
38
39
                (*g)(xs...);
                return 0;
            }
            catch(...)
            {
                return -1;
            }
        };
        int rc = sqlite3_exec(get(), sql, callback, &f, nullptr);
Paul's avatar
Format  
Paul committed
40
        if(rc != 0)
Paul's avatar
Paul committed
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
            MIGRAPHX_THROW(error_message());
    }

    std::string error_message() const
    {
        std::string msg = "sqlite3: ";
        return msg + sqlite3_errmsg(get());
    }
    sqlite3_ptr ptr;
};

sqlite sqlite::read(const fs::path& p)
{
    sqlite r;
    r.impl = std::make_shared<sqlite_impl>();
    r.impl->open(p, SQLITE_OPEN_READONLY);
    return r;
}

sqlite sqlite::write(const fs::path& p)
{
    sqlite r;
    r.impl = std::make_shared<sqlite_impl>();
    r.impl->open(p, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
    return r;
}

std::vector<std::unordered_map<std::string, std::string>> sqlite::execute(const std::string& s)
{
    std::vector<std::unordered_map<std::string, std::string>> result;
    impl->exec(s.c_str(), [&](int n, char** texts, char** names) {
        std::unordered_map<std::string, std::string> row;
        row.reserve(n);
Paul's avatar
Format  
Paul committed
74
75
76
77
78
79
        std::transform(
            names,
            names + n,
            texts,
            std::inserter(row, row.begin()),
            [&](const char* name, const char* text) { return std::make_pair(name, text); });
Paul's avatar
Paul committed
80
81
82
83
84
85
86
        result.push_back(row);
    });
    return result;
}

} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx