sqlitedatabasebackend.cpp 11.9 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5 6 7 8 9 10 11
**
** 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
12 13 14
** 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.
15
**
16 17 18 19 20 21 22
** 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.
23 24 25 26 27
**
****************************************************************************/

#include "sqlitedatabasebackend.h"

Marco Bubke's avatar
Marco Bubke committed
28 29 30 31 32
#include "sqliteexception.h"
#include "sqlitereadstatement.h"
#include "sqlitereadwritestatement.h"
#include "sqlitestatement.h"
#include "sqlitewritestatement.h"
33

Marco Bubke's avatar
Marco Bubke committed
34 35
#include <QThread>
#include <QDebug>
36 37 38

#include "okapi_bm25.h"

Marco Bubke's avatar
Marco Bubke committed
39
#include "sqlite3.h"
40

Nikolai Kosjar's avatar
Nikolai Kosjar committed
41 42 43 44 45 46
#if defined(Q_OS_DARWIN) && defined(Q_CC_GNU)
#define QTC_THREAD_LOCAL __thread
#else
#define QTC_THREAD_LOCAL thread_local
#endif

47 48
#define SIZE_OF_BYTEARRAY_ARRAY(array) sizeof(array)/sizeof(QByteArray)

Marco Bubke's avatar
Marco Bubke committed
49 50
namespace Sqlite {

51 52 53
SqliteDatabaseBackend::SqliteDatabaseBackend(SqliteDatabase &database)
    : m_database(database),
      m_databaseHandle(nullptr),
Marco Bubke's avatar
Marco Bubke committed
54
      m_cachedTextEncoding(Utf8)
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
{
}

SqliteDatabaseBackend::~SqliteDatabaseBackend()
{
    closeWithoutException();
}

void SqliteDatabaseBackend::setMmapSize(qint64 defaultSize, qint64 maximumSize)
{
    int resultCode = sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, defaultSize, maximumSize);
    checkMmapSizeIsSet(resultCode);
}

void SqliteDatabaseBackend::activateMultiThreading()
{
    int resultCode = sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
    checkIfMultithreadingIsActivated(resultCode);
}

static void sqliteLog(void*,int errorCode,const char *errorMessage)
{
    qWarning() << sqlite3_errstr(errorCode) << errorMessage;
}

void SqliteDatabaseBackend::activateLogging()
{
    int resultCode = sqlite3_config(SQLITE_CONFIG_LOG, sqliteLog, nullptr);
    checkIfLoogingIsActivated(resultCode);
}

void SqliteDatabaseBackend::initializeSqliteLibrary()
{
    int resultCode = sqlite3_initialize();
    checkInitializeSqliteLibraryWasSuccesful(resultCode);
}

void SqliteDatabaseBackend::shutdownSqliteLibrary()
{
    int resultCode = sqlite3_shutdown();
    checkShutdownSqliteLibraryWasSuccesful(resultCode);
}

void SqliteDatabaseBackend::checkpointFullWalLog()
{
    int resultCode = sqlite3_wal_checkpoint_v2(sqliteDatabaseHandle(), nullptr, SQLITE_CHECKPOINT_FULL, nullptr, nullptr);
    checkIfLogCouldBeCheckpointed(resultCode);
}

104
void SqliteDatabaseBackend::open(Utils::SmallStringView databaseFilePath)
105 106 107
{
    checkCanOpenDatabase(databaseFilePath);

108 109 110 111
    int resultCode = sqlite3_open_v2(databaseFilePath.data(),
                                     &m_databaseHandle,
                                     SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
                                     NULL);
112 113 114 115 116 117 118 119 120 121 122

    checkDatabaseCouldBeOpened(resultCode);

    registerBusyHandler();
    registerRankingFunction();
    cacheTextEncoding();
}

sqlite3 *SqliteDatabaseBackend::sqliteDatabaseHandle()
{
    checkDatabaseHandleIsNotNull();
123
    return m_databaseHandle;
124 125
}

126
void SqliteDatabaseBackend::setPragmaValue(Utils::SmallStringView pragmaKey, Utils::SmallStringView newPragmaValue)
127
{
128
    execute(Utils::SmallString{"PRAGMA ", pragmaKey, "='", newPragmaValue, "'"});
129
    Utils::SmallString pragmeValueInDatabase = toValue<Utils::SmallString>("PRAGMA " + pragmaKey);
130 131 132 133

    checkPragmaValue(pragmeValueInDatabase, newPragmaValue);
}

134
Utils::SmallString SqliteDatabaseBackend::pragmaValue(Utils::SmallStringView pragma)
135
{
136
    return toValue<Utils::SmallString>("PRAGMA " + pragma);
137 138 139 140
}

void SqliteDatabaseBackend::setJournalMode(JournalMode journalMode)
{
141
    setPragmaValue("journal_mode", journalModeToPragma(journalMode));
142 143
}

144
JournalMode SqliteDatabaseBackend::journalMode()
145
{
146
    return pragmaToJournalMode(pragmaValue("journal_mode"));
147 148 149 150
}

void SqliteDatabaseBackend::setTextEncoding(TextEncoding textEncoding)
{
151
    setPragmaValue("encoding", textEncodingToPragma(textEncoding));
152 153 154 155 156
    cacheTextEncoding();
}

TextEncoding SqliteDatabaseBackend::textEncoding()
{
Marco Bubke's avatar
Marco Bubke committed
157
    return m_cachedTextEncoding;
158 159 160
}


161
Utils::SmallStringVector SqliteDatabaseBackend::columnNames(Utils::SmallStringView tableName)
162
{
163
    SqliteReadWriteStatement statement("SELECT * FROM " + tableName, m_database);
164 165 166 167 168 169 170 171 172 173 174 175 176
    return statement.columnNames();
}

int SqliteDatabaseBackend::changesCount()
{
    return sqlite3_changes(sqliteDatabaseHandle());
}

int SqliteDatabaseBackend::totalChangesCount()
{
    return sqlite3_total_changes(sqliteDatabaseHandle());
}

177
void SqliteDatabaseBackend::execute(Utils::SmallStringView sqlStatement)
178
{
179
    SqliteReadWriteStatement statement(sqlStatement, m_database);
180 181 182
    statement.step();
}

183 184 185 186
void SqliteDatabaseBackend::close()
{
    checkForOpenDatabaseWhichCanBeClosed();

Marco Bubke's avatar
Marco Bubke committed
187
    int resultCode = sqlite3_close(m_databaseHandle);
188 189 190

    checkDatabaseClosing(resultCode);

Marco Bubke's avatar
Marco Bubke committed
191
    m_databaseHandle = nullptr;
192 193 194 195 196

}

bool SqliteDatabaseBackend::databaseIsOpen() const
{
Marco Bubke's avatar
Marco Bubke committed
197
    return m_databaseHandle != nullptr;
198 199 200 201
}

void SqliteDatabaseBackend::closeWithoutException()
{
Marco Bubke's avatar
Marco Bubke committed
202 203 204
    if (m_databaseHandle) {
        int resultCode = sqlite3_close_v2(m_databaseHandle);
        m_databaseHandle = nullptr;
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
        if (resultCode != SQLITE_OK)
            qWarning() << "SqliteDatabaseBackend::closeWithoutException: Unexpected error at closing the database!";
    }
}

void SqliteDatabaseBackend::registerBusyHandler()
{
    sqlite3_busy_handler(sqliteDatabaseHandle(), &busyHandlerCallback, nullptr);
}

void SqliteDatabaseBackend::registerRankingFunction()
{
    sqlite3_create_function_v2(sqliteDatabaseHandle(), "okapi_bm25", -1, SQLITE_ANY, 0, okapi_bm25, 0, 0, 0);
    sqlite3_create_function_v2(sqliteDatabaseHandle(), "okapi_bm25f", -1, SQLITE_UTF8, 0, okapi_bm25f, 0, 0, 0);
    sqlite3_create_function_v2(sqliteDatabaseHandle(), "okapi_bm25f_kb", -1, SQLITE_UTF8, 0, okapi_bm25f_kb, 0, 0, 0);
}

int SqliteDatabaseBackend::busyHandlerCallback(void *, int counter)
{
    Q_UNUSED(counter);
#ifdef QT_DEBUG
    //qWarning() << "Busy handler invoked" << counter << "times!";
#endif
    QThread::msleep(10);

    return true;
}

void SqliteDatabaseBackend::cacheTextEncoding()
{
235
    m_cachedTextEncoding = pragmaToTextEncoding(pragmaValue("encoding"));
236 237 238 239
}

void SqliteDatabaseBackend::checkForOpenDatabaseWhichCanBeClosed()
{
Marco Bubke's avatar
Marco Bubke committed
240
    if (m_databaseHandle == nullptr)
241 242 243 244 245 246 247 248 249 250 251
        throwException("SqliteDatabaseBackend::close: database is not open so it can not be closed.");
}

void SqliteDatabaseBackend::checkDatabaseClosing(int resultCode)
{
    switch (resultCode) {
        case SQLITE_OK: return;
        default: throwException("SqliteDatabaseBackend::close: unknown error happens at closing!");
    }
}

252
void SqliteDatabaseBackend::checkCanOpenDatabase(Utils::SmallStringView databaseFilePath)
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
{
    if (databaseFilePath.isEmpty())
        throw SqliteException("SqliteDatabaseBackend::SqliteDatabaseBackend: database cannot be opened:", "database file path is empty!");

    if (databaseIsOpen())
        throw SqliteException("SqliteDatabaseBackend::SqliteDatabaseBackend: database cannot be opened:", "database is already open!");
}

void SqliteDatabaseBackend::checkDatabaseCouldBeOpened(int resultCode)
{
    switch (resultCode) {
        case SQLITE_OK:
            return;
        default:
            closeWithoutException();
            throw SqliteException("SqliteDatabaseBackend::SqliteDatabaseBackend: database cannot be opened:", sqlite3_errmsg(sqliteDatabaseHandle()));
    }
}

272 273
void SqliteDatabaseBackend::checkPragmaValue(Utils::SmallStringView databaseValue,
                                             Utils::SmallStringView expectedValue)
274 275 276 277 278 279 280
{
    if (databaseValue != expectedValue)
        throwException("SqliteDatabaseBackend::setPragmaValue: pragma value is not set!");
}

void SqliteDatabaseBackend::checkDatabaseHandleIsNotNull()
{
281
    if (m_databaseHandle == nullptr)
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
        throwException("SqliteDatabaseBackend: database is not open!");
}

void SqliteDatabaseBackend::checkIfMultithreadingIsActivated(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::activateMultiThreading: multithreading can't be activated!");
}

void SqliteDatabaseBackend::checkIfLoogingIsActivated(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::activateLogging: logging can't be activated!");
}

void SqliteDatabaseBackend::checkMmapSizeIsSet(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::checkMmapSizeIsSet: mmap size can't be changed!");
}

void SqliteDatabaseBackend::checkInitializeSqliteLibraryWasSuccesful(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::initializeSqliteLibrary: SqliteLibrary cannot initialized!");
}

void SqliteDatabaseBackend::checkShutdownSqliteLibraryWasSuccesful(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::shutdownSqliteLibrary: SqliteLibrary cannot be shutdowned!");
}

void SqliteDatabaseBackend::checkIfLogCouldBeCheckpointed(int resultCode)
{
    if (resultCode != SQLITE_OK)
        throwException("SqliteDatabaseBackend::checkpointFullWalLog: WAL log could not be checkpointed!");
}

321 322 323
namespace {
template<std::size_t Size>
int indexOfPragma(Utils::SmallStringView pragma, const Utils::SmallStringView (&pragmas)[Size])
324
{
325
    for (unsigned int index = 0; index < Size; index++) {
326 327 328 329 330
        if (pragma == pragmas[index])
            return int(index);
    }

    return -1;
331
}
332 333
}

334 335 336 337 338 339
constexpr const Utils::SmallStringView journalModeStrings[] = {
    "delete",
    "truncate",
    "persist",
    "memory",
    "wal"
340 341
};

342
Utils::SmallStringView SqliteDatabaseBackend::journalModeToPragma(JournalMode journalMode)
343 344 345 346
{
    return journalModeStrings[int(journalMode)];
}

347
JournalMode SqliteDatabaseBackend::pragmaToJournalMode(Utils::SmallStringView pragma)
348
{
349
    int index = indexOfPragma(pragma, journalModeStrings);
350 351

    if (index < 0)
352
        throwExceptionStatic("SqliteDatabaseBackend::pragmaToJournalMode: pragma can't be transformed in a journal mode enumeration!");
353 354 355 356

    return static_cast<JournalMode>(index);
}

357 358 359 360
constexpr const Utils::SmallStringView textEncodingStrings[] = {
    "UTF-8",
    "UTF-16le",
    "UTF-16be"
361 362
};

363
Utils::SmallStringView SqliteDatabaseBackend::textEncodingToPragma(TextEncoding textEncoding)
364 365 366 367
{
    return textEncodingStrings[textEncoding];
}

368
TextEncoding SqliteDatabaseBackend::pragmaToTextEncoding(Utils::SmallStringView pragma)
369
{
370
    int index = indexOfPragma(pragma, textEncodingStrings);
371 372

    if (index < 0)
373
        throwExceptionStatic("SqliteDatabaseBackend::pragmaToTextEncoding: pragma can't be transformed in a text encoding enumeration!");
374 375 376 377

    return static_cast<TextEncoding>(index);
}

378
void SqliteDatabaseBackend::throwExceptionStatic(const char *whatHasHappens)
379
{
380 381 382 383 384 385 386
    throw SqliteException(whatHasHappens);
}

void SqliteDatabaseBackend::throwException(const char *whatHasHappens) const
{
    if (m_databaseHandle)
        throw SqliteException(whatHasHappens, sqlite3_errmsg(m_databaseHandle));
387 388 389
    else
        throw SqliteException(whatHasHappens);
}
Marco Bubke's avatar
Marco Bubke committed
390

391
template <typename Type>
392
Type SqliteDatabaseBackend::toValue(Utils::SmallStringView sqlStatement)
393
{
394
    SqliteReadWriteStatement statement(sqlStatement, m_database);
395 396 397 398 399 400

    statement.next();

    return statement.value<Type>(0);
}

Marco Bubke's avatar
Marco Bubke committed
401
} // namespace Sqlite