aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/sqlite/sqlitebasestatement.h
blob: c96fb3faded2a718090dcd7915aefafbb1bd2576 (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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#pragma once

#include "sqliteglobal.h"

#include "sqliteblob.h"
#include "sqliteexception.h"
#include "sqlitevalue.h"

#include <utils/smallstringvector.h>

#include <utils/optional.h>
#include <utils/span.h>

#include <cstdint>
#include <functional>
#include <memory>
#include <tuple>
#include <type_traits>

using std::int64_t;

struct sqlite3_stmt;
struct sqlite3;

namespace Sqlite {

class Database;
class DatabaseBackend;

enum class Type : char { Invalid, Integer, Float, Text, Blob, Null };

class SQLITE_EXPORT BaseStatement
{
public:
    explicit BaseStatement(Utils::SmallStringView sqlStatement, Database &database);

    BaseStatement(const BaseStatement &) = delete;
    BaseStatement &operator=(const BaseStatement &) = delete;

    static void deleteCompiledStatement(sqlite3_stmt *m_compiledStatement);

    bool next() const;
    void step() const;
    void reset() const;

    Type fetchType(int column) const;
    int fetchIntValue(int column) const;
    long fetchLongValue(int column) const;
    long long fetchLongLongValue(int column) const;
    double fetchDoubleValue(int column) const;
    Utils::SmallStringView fetchSmallStringViewValue(int column) const;
    ValueView fetchValueView(int column) const;
    BlobView fetchBlobValue(int column) const;
    template<typename Type>
    Type fetchValue(int column) const;
    int columnCount() const;

    void bind(int index, NullValue);
    void bind(int index, int value);
    void bind(int index, long long value);
    void bind(int index, double value);
    void bind(int index, void *pointer);
    void bind(int index, Utils::span<int> values);
    void bind(int index, Utils::span<long long> values);
    void bind(int index, Utils::span<double> values);
    void bind(int index, Utils::span<const char *> values);
    void bind(int index, Utils::SmallStringView value);
    void bind(int index, const Value &value);
    void bind(int index, BlobView blobView);

    void bind(int index, uint value) { bind(index, static_cast<long long>(value)); }

    void bind(int index, long value)
    {
        bind(index, static_cast<long long>(value));
    }

    void prepare(Utils::SmallStringView sqlStatement);
    void waitForUnlockNotify() const;

    sqlite3 *sqliteDatabaseHandle() const;

    [[noreturn]] void checkForStepError(int resultCode) const;
    [[noreturn]] void checkForResetError(int resultCode) const;
    [[noreturn]] void checkForPrepareError(int resultCode) const;
    [[noreturn]] void checkForBindingError(int resultCode) const;
    void setIfIsReadyToFetchValues(int resultCode) const;
    void checkColumnCount(int columnCount) const;
    void checkBindingName(int index) const;
    void setBindingParameterCount();
    void setColumnCount();
    bool isReadOnlyStatement() const;
    [[noreturn]] void throwStatementIsBusy(const char *whatHasHappened) const;
    [[noreturn]] void throwStatementHasError(const char *whatHasHappened) const;
    [[noreturn]] void throwStatementIsMisused(const char *whatHasHappened) const;
    [[noreturn]] void throwInputOutputError(const char *whatHasHappened) const;
    [[noreturn]] void throwConstraintPreventsModification(const char *whatHasHappened) const;
    [[noreturn]] void throwNoValuesToFetch(const char *whatHasHappened) const;
    [[noreturn]] void throwInvalidColumnFetched(const char *whatHasHappened) const;
    [[noreturn]] void throwBindingIndexIsOutOfRange(const char *whatHasHappened) const;
    [[noreturn]] void throwWrongBingingName(const char *whatHasHappened) const;
    [[noreturn]] void throwUnknowError(const char *whatHasHappened) const;
    [[noreturn]] void throwBingingTooBig(const char *whatHasHappened) const;
    [[noreturn]] void throwTooBig(const char *whatHasHappened) const;
    [[noreturn]] void throwSchemaChangeError(const char *whatHasHappened) const;
    [[noreturn]] void throwCannotWriteToReadOnlyConnection(const char *whatHasHappened) const;
    [[noreturn]] void throwProtocolError(const char *whatHasHappened) const;
    [[noreturn]] void throwDatabaseExceedsMaximumFileSize(const char *whatHasHappened) const;
    [[noreturn]] void throwDataTypeMismatch(const char *whatHasHappened) const;
    [[noreturn]] void throwConnectionIsLocked(const char *whatHasHappened) const;
    [[noreturn]] void throwExecutionInterrupted(const char *whatHasHappened) const;
    [[noreturn]] void throwDatabaseIsCorrupt(const char *whatHasHappened) const;
    [[noreturn]] void throwCannotOpen(const char *whatHasHappened) const;

    QString columnName(int column) const;

    Database &database() const;

protected:
    ~BaseStatement() = default;

private:
    std::unique_ptr<sqlite3_stmt, void (*)(sqlite3_stmt *)> m_compiledStatement;
    Database &m_database;
    int m_bindingParameterCount;
    int m_columnCount;
};

template <> SQLITE_EXPORT int BaseStatement::fetchValue<int>(int column) const;
template <> SQLITE_EXPORT long BaseStatement::fetchValue<long>(int column) const;
template <> SQLITE_EXPORT long long BaseStatement::fetchValue<long long>(int column) const;
template <> SQLITE_EXPORT double BaseStatement::fetchValue<double>(int column) const;
extern template SQLITE_EXPORT Utils::SmallStringView BaseStatement::fetchValue<Utils::SmallStringView>(int column) const;
extern template SQLITE_EXPORT Utils::SmallString BaseStatement::fetchValue<Utils::SmallString>(int column) const;
extern template SQLITE_EXPORT Utils::PathString BaseStatement::fetchValue<Utils::PathString>(int column) const;

template<typename BaseStatement, int ResultCount>
class StatementImplementation : public BaseStatement
{

public:
    using BaseStatement::BaseStatement;

    void execute()
    {
        Resetter resetter{*this};
        BaseStatement::next();
        resetter.reset();
    }

    void bindValues() {}

    template<typename... ValueType>
    void bindValues(const ValueType&... values)
    {
        int index = 0;
        (BaseStatement::bind(++index, values), ...);
    }

    template<typename... ValueType>
    void write(const ValueType&... values)
    {
        Resetter resetter{*this};
        bindValues(values...);
        BaseStatement::next();
        resetter.reset();
    }

    template<typename ResultType>
    std::vector<ResultType> values(std::size_t reserveSize)
    {
        Resetter resetter{*this};
        std::vector<ResultType> resultValues;
        resultValues.reserve(std::max(reserveSize, m_maximumResultCount));

        while (BaseStatement::next())
            emplaceBackValues(resultValues);

        setMaximumResultCount(resultValues.size());

        resetter.reset();

        return resultValues;
    }

    template<typename ResultType, typename... QueryTypes>
    auto values(std::size_t reserveSize, const QueryTypes &...queryValues)
    {
        Resetter resetter{*this};
        std::vector<ResultType> resultValues;
        resultValues.reserve(std::max(reserveSize, m_maximumResultCount));

        bindValues(queryValues...);

        while (BaseStatement::next())
            emplaceBackValues(resultValues);

        setMaximumResultCount(resultValues.size());

        resetter.reset();

        return resultValues;
    }

    template<typename ResultType, typename... QueryTypes>
    auto value(const QueryTypes &...queryValues)
    {
        Resetter resetter{*this};
        Utils::optional<ResultType> resultValue;

        bindValues(queryValues...);

        if (BaseStatement::next())
            resultValue = assignValue<Utils::optional<ResultType>>();

        resetter.reset();

        return resultValue;
    }

    template<typename Type>
    static auto toValue(Utils::SmallStringView sqlStatement, Database &database)
    {
        StatementImplementation statement(sqlStatement, database);

        statement.checkColumnCount(1);

        statement.next();

        return statement.template fetchValue<Type>(0);
    }

    template<typename Callable, typename... QueryTypes>
    void readCallback(Callable &&callable, const QueryTypes &...queryValues)
    {
        Resetter resetter{*this};

        bindValues(queryValues...);

        while (BaseStatement::next()) {
            auto control = callCallable(callable);

            if (control == CallbackControl::Abort)
                break;
        }

        resetter.reset();
    }

    template<int ResultTypeCount = 1, typename Container, typename... QueryTypes>
    void readTo(Container &container, const QueryTypes &...queryValues)
    {
        Resetter resetter{*this};

        bindValues(queryValues...);

        while (BaseStatement::next())
            emplaceBackValues(container);

        resetter.reset();
    }

protected:
    ~StatementImplementation() = default;

private:
    struct Resetter
    {
        Resetter(StatementImplementation &statement)
            : statement(statement)
        {}

        void reset()
        {
            try {
                statement.reset();
            } catch (...) {
                shouldReset = false;
                throw;
            }

            shouldReset = false;
        }

        ~Resetter() noexcept
        {
            try {
                if (shouldReset)
                    statement.reset();
            } catch (...) {
            }
        }

        StatementImplementation &statement;
        bool shouldReset = true;
    };

    struct ValueGetter
    {
        ValueGetter(StatementImplementation &statement, int column)
            : statement(statement)
            , column(column)
        {}

        operator int() { return statement.fetchIntValue(column); }
        operator long() { return statement.fetchLongValue(column); }
        operator long long() { return statement.fetchLongLongValue(column); }
        operator double() { return statement.fetchDoubleValue(column); }
        operator Utils::SmallStringView() { return statement.fetchSmallStringViewValue(column); }
        operator BlobView() { return statement.fetchBlobValue(column); }
        operator ValueView() { return statement.fetchValueView(column); }

        StatementImplementation &statement;
        int column;
    };

    template<typename ContainerType, int... ColumnIndices>
    void emplaceBackValues(ContainerType &container, std::integer_sequence<int, ColumnIndices...>)
    {
        container.emplace_back(ValueGetter(*this, ColumnIndices)...);
    }

    template<typename ContainerType>
    void emplaceBackValues(ContainerType &container)
    {
        emplaceBackValues(container, std::make_integer_sequence<int, ResultCount>{});
    }

    template <typename ResultOptionalType,
              int... ColumnIndices>
    ResultOptionalType assignValue(std::integer_sequence<int, ColumnIndices...>)
    {
        return ResultOptionalType(Utils::in_place, ValueGetter(*this, ColumnIndices)...);
    }

    template<typename ResultOptionalType>
    ResultOptionalType assignValue()
    {
        return assignValue<ResultOptionalType>(std::make_integer_sequence<int, ResultCount>{});
    }

    template<typename Callable, int... ColumnIndices>
    CallbackControl callCallable(Callable &&callable, std::integer_sequence<int, ColumnIndices...>)
    {
        return std::invoke(callable, ValueGetter(*this, ColumnIndices)...);
    }

    template<typename Callable>
    CallbackControl callCallable(Callable &&callable)
    {
        return callCallable(callable, std::make_integer_sequence<int, ResultCount>{});
    }

    void setMaximumResultCount(std::size_t count)
    {
        m_maximumResultCount = std::max(m_maximumResultCount, count);
    }

public:
    std::size_t m_maximumResultCount = 0;
};

} // namespace Sqlite