aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/sqlite/sqlitesessions.cpp
blob: 8517c0f2c3213773eb1456bf9b0b2c91385192f0 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "sqlitesessions.h"
#include "sqlitereadstatement.h"
#include "sqlitesessionchangeset.h"
#include "sqlitetable.h"

#include <sqlite.h>

#include <memory>

namespace Sqlite {

namespace {

void checkResultCode(int resultCode, const source_location &sourceLocation)
{
    switch (resultCode) {
    case SQLITE_NOMEM:
        throw std::bad_alloc();
    case SQLITE_SCHEMA:
        throw CannotApplyChangeSet(sourceLocation);
    case SQLITE_MISUSE:
        throw ChangeSetIsMisused(sourceLocation);
    }

    if (resultCode != SQLITE_OK)
        throw UnknowError({}, sourceLocation);
}

int xConflict(void *, int conflict, sqlite3_changeset_iter *)
{
    switch (conflict) {
    case SQLITE_CHANGESET_DATA:
        return SQLITE_CHANGESET_REPLACE;
    case SQLITE_CHANGESET_NOTFOUND:
        return SQLITE_CHANGESET_OMIT;
    case SQLITE_CHANGESET_CONFLICT:
        return SQLITE_CHANGESET_REPLACE;
    case SQLITE_CHANGESET_CONSTRAINT:
        return SQLITE_CHANGESET_OMIT;
    case SQLITE_CHANGESET_FOREIGN_KEY:
        return SQLITE_CHANGESET_OMIT;
    }

    return SQLITE_CHANGESET_ABORT;
}
} // namespace

void Sessions::attachTables(const Utils::SmallStringVector &tableNames,
                            const source_location &sourceLocation)
{
    for (Utils::SmallStringView tableName : tableNames) {
        int resultCode = sqlite3session_attach(session.get(), std::string(tableName).c_str());
        checkResultCode(resultCode, sourceLocation);
    }
}

Sessions::~Sessions() = default;

void Sessions::setAttachedTables(Utils::SmallStringVector tables)
{
    tableNames = std::move(tables);
}

void Sessions::create(const source_location &sourceLocation)
{
    sqlite3_session *newSession = nullptr;
    int resultCode = sqlite3session_create(database.backend().sqliteDatabaseHandle(sourceLocation),
                                           std::string(databaseName).c_str(),
                                           &newSession);
    session.reset(newSession);

    checkResultCode(resultCode, sourceLocation);

    attachTables(tableNames, sourceLocation);
}

void Sessions::commit(const source_location &sourceLocation)
{
    if (session && !sqlite3session_isempty(session.get())) {
        SessionChangeSet changeSet{*this};

        insertSession.write(sourceLocation, changeSet.asBlobView());
    }

    session.reset();
}

void Sessions::rollback()
{
    session.reset();
}

void Internal::SessionsBase::createSessionTable(Database &database,
                                                const source_location &sourceLocation)
{
    Sqlite::Table table;
    table.setUseIfNotExists(true);
    table.setName(sessionsTableName);
    table.addColumn("id", Sqlite::ColumnType::Integer, {Sqlite::PrimaryKey{AutoIncrement::Yes}});
    table.addColumn("changeset", Sqlite::ColumnType::Blob);

    table.initialize(database, sourceLocation);
}

void Sessions::revert(const source_location &sourceLocation)
{
    ReadStatement<1> selectChangeSets{Utils::PathString::join({"SELECT changeset FROM ",
                                                               sessionsTableName,
                                                               " ORDER BY id DESC"}),
                                      database,
                                      sourceLocation};

    auto changeSets = selectChangeSets.values<SessionChangeSet, 1024>(sourceLocation);

    for (auto &changeSet : changeSets) {
        int resultCode = sqlite3changeset_apply_v2(database.backend().sqliteDatabaseHandle(
                                                       sourceLocation),
                                                   changeSet.size(),
                                                   changeSet.data(),
                                                   nullptr,
                                                   xConflict,
                                                   nullptr,
                                                   nullptr,
                                                   nullptr,
                                                   SQLITE_CHANGESETAPPLY_INVERT
                                                       | SQLITE_CHANGESETAPPLY_NOSAVEPOINT);
        checkResultCode(resultCode, sourceLocation);
    }
}

void Sessions::apply(const source_location &sourceLocation)
{
    ReadStatement<1> selectChangeSets{Utils::PathString::join({"SELECT changeset FROM ",
                                                               sessionsTableName,
                                                               " ORDER BY id"}),
                                      database,
                                      sourceLocation};

    auto changeSets = selectChangeSets.values<SessionChangeSet, 1024>(sourceLocation);

    for (auto &changeSet : changeSets) {
        int resultCode = sqlite3changeset_apply_v2(database.backend().sqliteDatabaseHandle(
                                                       sourceLocation),
                                                   changeSet.size(),
                                                   changeSet.data(),
                                                   nullptr,
                                                   xConflict,
                                                   nullptr,
                                                   nullptr,
                                                   nullptr,
                                                   SQLITE_CHANGESETAPPLY_NOSAVEPOINT);
        checkResultCode(resultCode, sourceLocation);
    }
}

void Sessions::applyAndUpdateSessions(const source_location &sourceLocation)
{
    create(sourceLocation);
    apply(sourceLocation);
    deleteAll(sourceLocation);
    commit(sourceLocation);
}

void Sessions::deleteAll(const source_location &sourceLocation)
{
    WriteStatement<0>{Utils::SmallString::join({"DELETE FROM ", sessionsTableName}),
                      database,
                      sourceLocation}
        .execute(sourceLocation);
}

SessionChangeSets Sessions::changeSets(const source_location &sourceLocation) const
{
    ReadStatement<1> selectChangeSets{Utils::PathString::join({"SELECT changeset FROM ",
                                                               sessionsTableName,
                                                               " ORDER BY id DESC"}),
                                      database,
                                      sourceLocation};

    return selectChangeSets.values<SessionChangeSet, 1024>(sourceLocation);
}

void Sessions::Deleter::operator()(sqlite3_session *session)
{
    sqlite3session_delete(session);
}

} // namespace Sqlite