aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/sqlite3/sqlite.cpp
blob: 98e498f76b33c49e39e6f86788ae8b9c151e7a4b (plain) (blame)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include "sqlite.h"

#include <util/generic/singleton.h>
#include <util/generic/scope.h>

#include <cstdlib>

using namespace NSQLite;

namespace {
    struct TSQLiteInit {
        inline TSQLiteInit() {
            int ret = sqlite3_config(SQLITE_CONFIG_MULTITHREAD);

            if (ret != SQLITE_OK) {
                ythrow TSQLiteError(ret) << "init failure";
            }
        }

        static inline void Ensure() {
            Singleton<TSQLiteInit>();
        }
    };
}

namespace NSQLite {
    TSQLiteError::TSQLiteError(sqlite3* hndl)
        : ErrorCode(sqlite3_errcode(hndl))
    {
        *this << sqlite3_errmsg(hndl) << ". ";
    }

    TSQLiteError::TSQLiteError(int rc)
        : ErrorCode(rc)
    {
        *this << sqlite3_errstr(rc) << " (" << rc << "). ";
    }

    TSQLiteDB::TSQLiteDB(const TString& path) {
        TSQLiteInit::Ensure();

        sqlite3* db = nullptr;
        const int rc = sqlite3_open(path.data(), &db);

        H_.Reset(db);

        if (rc) {
            ythrow TSQLiteError(Handle()) << "can not init db " << path.Quote();
        }
    }

    TSQLiteDB::TSQLiteDB(const TString& path, int flags) {
        TSQLiteInit::Ensure();

        sqlite3* db = nullptr;
        const int rc = sqlite3_open_v2(path.data(), &db, flags, nullptr);

        H_.Reset(db);

        if (rc) {
            ythrow TSQLiteError(Handle()) << "can not init db " << path.Quote();
        }
    }

    sqlite3* TSQLiteDB::Handle() const noexcept {
        return H_.Get();
    }

    size_t TSQLiteDB::RowsAffected() const noexcept {
        return static_cast<size_t>(sqlite3_changes(H_.Get()));
    }

    TSQLiteStatement::TSQLiteStatement(TSQLiteDB& db, const TString& s)
        : S_(s)
    {
        if (!S_.empty() && S_[S_.size() - 1] != ';') {
            S_ += ';';
        }

        sqlite3_stmt* st = nullptr;
        const char* tail = nullptr;
        const int rc = sqlite3_prepare_v2(db.Handle(), S_.data(), S_.size() + 1, &st, &tail);

        H_.Reset(st);

        if (rc != SQLITE_OK) {
            ythrow TSQLiteError(db.Handle()) << "can not prepare " << S_.Quote();
        }
    }

    void TSQLiteStatement::Execute() {
        while (Step()) {
        }

        Reset();
    }

    TSQLiteStatement& TSQLiteStatement::Bind(size_t idx, i64 val) {
        sqlite3_bind_int64(Handle(), idx, val);
        return *this;
    }

    TSQLiteStatement& TSQLiteStatement::Bind(size_t idx, int val) {
        sqlite3_bind_int(Handle(), idx, val);
        return *this;
    }

    TSQLiteStatement& TSQLiteStatement::Bind(size_t idx) {
        sqlite3_bind_null(Handle(), idx);
        return *this;
    }

    TSQLiteStatement& TSQLiteStatement::Bind(size_t idx, double val) {
        sqlite3_bind_double(Handle(), idx, val);
        return *this;
    }

    void TSQLiteStatement::BindText(size_t idx, const char* text, size_t len, TFreeFunc func) {
        sqlite3_bind_text(Handle(), idx, text, len, func);
    }

    TSQLiteStatement& TSQLiteStatement::Bind(size_t idx, TStringBuf str) {
        BindText(idx, str.data(), str.size(), SQLITE_STATIC);
        return *this;
    }

    TSQLiteStatement& TSQLiteStatement::BindBlob(size_t idx, TStringBuf blob) {
        sqlite3_bind_blob(Handle(), idx, blob.data(), blob.size(), SQLITE_STATIC);
        return *this;
    }

    size_t TSQLiteStatement::BoundNamePosition(TStringBuf name) const noexcept {
        return sqlite3_bind_parameter_index(Handle(), name.data());
    }

    size_t TSQLiteStatement::BoundParameterCount() const noexcept {
        return sqlite3_bind_parameter_count(Handle());
    }

    const char* TSQLiteStatement::BoundParameterName(size_t idx) const noexcept {
        return sqlite3_bind_parameter_name(Handle(), idx);
    }

    sqlite3_stmt* TSQLiteStatement::Handle() const noexcept {
        return H_.Get();
    }

    bool TSQLiteStatement::Step() {
        const int rc = sqlite3_step(Handle());

        switch (rc) {
            case SQLITE_ROW:
                return true;

            case SQLITE_DONE:
                return false;

            default:
                break;
        }

        char* stmt = rc == SQLITE_CONSTRAINT ? sqlite3_expanded_sql(Handle()) : nullptr;
        Y_DEFER {
            if (stmt != nullptr) {
                sqlite3_free(reinterpret_cast<void*>(stmt));
                stmt = nullptr;
            }
        };
        if (stmt != nullptr) {
            ythrow TSQLiteError(rc) << "step failed: " << stmt;
        } else {
            ythrow TSQLiteError(rc) << "step failed";
        }
    }

    i64 TSQLiteStatement::ColumnInt64(size_t idx) {
        return sqlite3_column_int64(Handle(), idx);
    }

    double TSQLiteStatement::ColumnDouble(size_t idx) {
        return sqlite3_column_double(Handle(), idx);
    }

    TStringBuf TSQLiteStatement::ColumnText(size_t idx) {
        return reinterpret_cast<const char*>(sqlite3_column_text(Handle(), idx));
    }

    TStringBuf TSQLiteStatement::ColumnBlob(size_t idx) {
        const void* blob = sqlite3_column_blob(Handle(), idx);
        size_t size = sqlite3_column_bytes(Handle(), idx);
        return TStringBuf(static_cast<const char*>(blob), size);
    }

    void TSQLiteStatement::ColumnAccept(size_t idx, ISQLiteColumnVisitor& visitor) {
        const auto columnType = sqlite3_column_type(Handle(), idx);
        switch (columnType) {
        case SQLITE_INTEGER:
            visitor.OnColumnInt64(ColumnInt64(idx));
            break;
        case SQLITE_FLOAT:
            visitor.OnColumnDouble(ColumnDouble(idx));
            break;
        case SQLITE_TEXT:
            visitor.OnColumnText(ColumnText(idx));
            break;
        case SQLITE_BLOB:
            visitor.OnColumnBlob(ColumnBlob(idx));
            break;
        case SQLITE_NULL:
            visitor.OnColumnNull();
            break;
        }
    }

    size_t TSQLiteStatement::ColumnCount() const noexcept {
        return static_cast<size_t>(sqlite3_column_count(Handle()));
    }

    TStringBuf TSQLiteStatement::ColumnName(size_t idx) const noexcept {
        return sqlite3_column_name(Handle(), idx);
    }

    void TSQLiteStatement::Reset() {
        const int rc = sqlite3_reset(Handle());

        if (rc != SQLITE_OK) {
            ythrow TSQLiteError(rc) << "reset failed";
        }
    }

    void TSQLiteStatement::ResetHard() {
        (void)sqlite3_reset(Handle());
    }

    void TSQLiteStatement::ClearBindings() noexcept {
        // No error is documented.
        // sqlite3.c's code always returns SQLITE_OK.
        (void)sqlite3_clear_bindings(Handle());
    }

    TSQLiteTransaction::TSQLiteTransaction(TSQLiteDB& db)
        : Db(&db)
    {
        Execute("BEGIN TRANSACTION");
    }

    TSQLiteTransaction::~TSQLiteTransaction() {
        if (Db) {
            Rollback();
        }
    }

    void TSQLiteTransaction::Commit() {
        Execute("COMMIT TRANSACTION");
        Db = nullptr;
    }

    void TSQLiteTransaction::Rollback() {
        Execute("ROLLBACK TRANSACTION");
        Db = nullptr;
    }

    void TSQLiteTransaction::Execute(const TString& query) {
        Y_ENSURE(Db, "Transaction is already ended");
        TSQLiteStatement st(*Db, query);
        st.Execute();
    }

    TSimpleDB::TSimpleDB(const TString& path)
        : TSQLiteDB(path)
        , Start_(*this, "begin transaction")
        , End_(*this, "end transaction")
    {
    }

    void TSimpleDB::Execute(const TString& statement) {
        TSQLiteStatement(*this, statement).Execute();
    }

    void TSimpleDB::Acquire() {
        Start_.Execute();
    }

    void TSimpleDB::Release() {
        End_.Execute();
    }

}