sqlitedatabasebackend.cpp 12.3 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 {

Nikolai Kosjar's avatar
Nikolai Kosjar committed
51
QTC_THREAD_LOCAL SqliteDatabaseBackend *sqliteDatabaseBackend = nullptr;
52 53

SqliteDatabaseBackend::SqliteDatabaseBackend()
Marco Bubke's avatar
Marco Bubke committed
54 55
    : m_databaseHandle(nullptr),
      m_cachedTextEncoding(Utf8)
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
{
    sqliteDatabaseBackend = this;
}

SqliteDatabaseBackend::~SqliteDatabaseBackend()
{
    closeWithoutException();
    sqliteDatabaseBackend = nullptr;
}

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);
}

void SqliteDatabaseBackend::open(const QString &databaseFilePath)
{
    checkCanOpenDatabase(databaseFilePath);

    QByteArray databaseUtf8Path = databaseFilePath.toUtf8();
    int resultCode = sqlite3_open_v2(databaseUtf8Path.data(),
Marco Bubke's avatar
Marco Bubke committed
113
                                      &m_databaseHandle,
114 115 116 117 118 119 120 121 122 123 124 125 126 127
                                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
                                      NULL);

    checkDatabaseCouldBeOpened(resultCode);

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

sqlite3 *SqliteDatabaseBackend::sqliteDatabaseHandle()
{
    checkDatabaseBackendIsNotNull();
    checkDatabaseHandleIsNotNull();
Marco Bubke's avatar
Marco Bubke committed
128
    return threadLocalInstance()->m_databaseHandle;
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
}

void SqliteDatabaseBackend::setPragmaValue(const Utf8String &pragmaKey, const Utf8String &newPragmaValue)
{
    SqliteReadWriteStatement::execute(Utf8StringLiteral("PRAGMA ") + pragmaKey + Utf8StringLiteral("='") + newPragmaValue + Utf8StringLiteral("'"));
    Utf8String pragmeValueInDatabase = SqliteReadWriteStatement::toValue<Utf8String>(Utf8StringLiteral("PRAGMA ") + pragmaKey);

    checkPragmaValue(pragmeValueInDatabase, newPragmaValue);
}

Utf8String SqliteDatabaseBackend::pragmaValue(const Utf8String &pragma) const
{
    return SqliteReadWriteStatement::toValue<Utf8String>(Utf8StringLiteral("PRAGMA ") + pragma);
}

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

JournalMode SqliteDatabaseBackend::journalMode() const
{
    return pragmaToJournalMode(pragmaValue(Utf8StringLiteral("journal_mode")));
}

void SqliteDatabaseBackend::setTextEncoding(TextEncoding textEncoding)
{
    setPragmaValue(Utf8StringLiteral("encoding"), textEncodingToPragma(textEncoding));
    cacheTextEncoding();
}

TextEncoding SqliteDatabaseBackend::textEncoding()
{
Marco Bubke's avatar
Marco Bubke committed
162
    return m_cachedTextEncoding;
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
}


Utf8StringVector SqliteDatabaseBackend::columnNames(const Utf8String &tableName)
{
    SqliteReadStatement statement(Utf8StringLiteral("SELECT * FROM ") + tableName);
    return statement.columnNames();
}

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

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

void SqliteDatabaseBackend::close()
{
    checkForOpenDatabaseWhichCanBeClosed();

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

    checkDatabaseClosing(resultCode);

Marco Bubke's avatar
Marco Bubke committed
190
    m_databaseHandle = nullptr;
191 192 193 194 195 196 197 198 199 200 201

}

SqliteDatabaseBackend *SqliteDatabaseBackend::threadLocalInstance()
{
    checkDatabaseBackendIsNotNull();
    return sqliteDatabaseBackend;
}

bool SqliteDatabaseBackend::databaseIsOpen() const
{
Marco Bubke's avatar
Marco Bubke committed
202
    return m_databaseHandle != nullptr;
203 204 205 206
}

void SqliteDatabaseBackend::closeWithoutException()
{
Marco Bubke's avatar
Marco Bubke committed
207 208 209
    if (m_databaseHandle) {
        int resultCode = sqlite3_close_v2(m_databaseHandle);
        m_databaseHandle = nullptr;
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
        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()
{
Marco Bubke's avatar
Marco Bubke committed
240
    m_cachedTextEncoding = pragmaToTextEncoding(pragmaValue(Utf8StringLiteral("encoding")));
241 242 243 244
}

void SqliteDatabaseBackend::checkForOpenDatabaseWhichCanBeClosed()
{
Marco Bubke's avatar
Marco Bubke committed
245
    if (m_databaseHandle == nullptr)
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
        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!");
    }
}

void SqliteDatabaseBackend::checkCanOpenDatabase(const QString &databaseFilePath)
{
    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()));
    }
}

void SqliteDatabaseBackend::checkPragmaValue(const Utf8String &databaseValue, const Utf8String &expectedValue)
{
    if (databaseValue != expectedValue)
        throwException("SqliteDatabaseBackend::setPragmaValue: pragma value is not set!");
}

void SqliteDatabaseBackend::checkDatabaseHandleIsNotNull()
{
Marco Bubke's avatar
Marco Bubke committed
285
    if (sqliteDatabaseBackend->m_databaseHandle == nullptr)
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
        throwException("SqliteDatabaseBackend: database is not open!");
}

void SqliteDatabaseBackend::checkDatabaseBackendIsNotNull()
{
    if (sqliteDatabaseBackend == nullptr)
        throwException("SqliteDatabaseBackend: database backend is not initialized!");
}

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!");
}

int SqliteDatabaseBackend::indexOfPragma(const Utf8String pragma, const Utf8String pragmas[], size_t pragmaCount)
{
    for (unsigned int index = 0; index < pragmaCount; index++) {
        if (pragma == pragmas[index])
            return int(index);
    }

    return -1;

}

static const Utf8String journalModeStrings[] = {
    Utf8StringLiteral("delete"),
    Utf8StringLiteral("truncate"),
    Utf8StringLiteral("persist"),
    Utf8StringLiteral("memory"),
    Utf8StringLiteral("wal")
};

const Utf8String &SqliteDatabaseBackend::journalModeToPragma(JournalMode journalMode)
{
    return journalModeStrings[int(journalMode)];
}

JournalMode SqliteDatabaseBackend::pragmaToJournalMode(const Utf8String &pragma)
{
    int index = indexOfPragma(pragma, journalModeStrings, SIZE_OF_BYTEARRAY_ARRAY(journalModeStrings));

    if (index < 0)
        throwException("SqliteDatabaseBackend::pragmaToJournalMode: pragma can't be transformed in a journal mode enumeration!");

    return static_cast<JournalMode>(index);
}

static const Utf8String textEncodingStrings[] = {
    Utf8StringLiteral("UTF-8"),
    Utf8StringLiteral("UTF-16le"),
    Utf8StringLiteral("UTF-16be")
};

const Utf8String &SqliteDatabaseBackend::textEncodingToPragma(TextEncoding textEncoding)
{
    return textEncodingStrings[textEncoding];
}

TextEncoding SqliteDatabaseBackend::pragmaToTextEncoding(const Utf8String &pragma)
{
    int index = indexOfPragma(pragma, textEncodingStrings, SIZE_OF_BYTEARRAY_ARRAY(textEncodingStrings));

    if (index < 0)
        throwException("SqliteDatabaseBackend::pragmaToTextEncoding: pragma can't be transformed in a text encoding enumeration!");

    return static_cast<TextEncoding>(index);
}

void SqliteDatabaseBackend::throwException(const char *whatHasHappens)
{
Marco Bubke's avatar
Marco Bubke committed
388 389
    if (sqliteDatabaseBackend && sqliteDatabaseBackend->m_databaseHandle)
        throw SqliteException(whatHasHappens, sqlite3_errmsg(sqliteDatabaseBackend->m_databaseHandle));
390 391 392
    else
        throw SqliteException(whatHasHappens);
}
Marco Bubke's avatar
Marco Bubke committed
393 394

} // namespace Sqlite