sqlitedatabasebackend.cpp 12.1 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
SqliteDatabaseBackend::SqliteDatabaseBackend()
Marco Bubke's avatar
Marco Bubke committed
52 53
    : m_databaseHandle(nullptr),
      m_cachedTextEncoding(Utf8)
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
{
}

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

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
109
                                      &m_databaseHandle,
110 111 112 113 114 115 116 117 118 119 120 121 122
                                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
                                      NULL);

    checkDatabaseCouldBeOpened(resultCode);

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

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

void SqliteDatabaseBackend::setPragmaValue(const Utf8String &pragmaKey, const Utf8String &newPragmaValue)
{
128 129 130
    SqliteReadWriteStatement statement(Utf8StringLiteral("PRAGMA ") + pragmaKey + Utf8StringLiteral("='") + newPragmaValue + Utf8StringLiteral("'"), *this);
    statement.step();
    Utf8String pragmeValueInDatabase = toValue<Utf8String>(Utf8StringLiteral("PRAGMA ") + pragmaKey);
131 132 133 134

    checkPragmaValue(pragmeValueInDatabase, newPragmaValue);
}

135
Utf8String SqliteDatabaseBackend::pragmaValue(const Utf8String &pragma)
136
{
137
    return toValue<Utf8String>(Utf8StringLiteral("PRAGMA ") + pragma);
138 139 140 141 142 143 144
}

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

145
JournalMode SqliteDatabaseBackend::journalMode()
146 147 148 149 150 151 152 153 154 155 156 157
{
    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
158
    return m_cachedTextEncoding;
159 160 161 162 163
}


Utf8StringVector SqliteDatabaseBackend::columnNames(const Utf8String &tableName)
{
164
    SqliteReadWriteStatement statement(Utf8StringLiteral("SELECT * FROM ") + tableName, *this);
165 166 167 168 169 170 171 172 173 174 175 176 177
    return statement.columnNames();
}

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

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

178 179 180 181 182 183
void SqliteDatabaseBackend::execute(const Utf8String &sqlStatementUtf8)
{
    SqliteReadWriteStatement statement(sqlStatementUtf8, *this);
    statement.step();
}

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

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

    checkDatabaseClosing(resultCode);

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

}

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

void SqliteDatabaseBackend::closeWithoutException()
{
Marco Bubke's avatar
Marco Bubke committed
203 204 205
    if (m_databaseHandle) {
        int resultCode = sqlite3_close_v2(m_databaseHandle);
        m_databaseHandle = nullptr;
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
        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
236
    m_cachedTextEncoding = pragmaToTextEncoding(pragmaValue(Utf8StringLiteral("encoding")));
237 238 239 240
}

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

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)
350
        throwExceptionStatic("SqliteDatabaseBackend::pragmaToJournalMode: pragma can't be transformed in a journal mode enumeration!");
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

    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)
371
        throwExceptionStatic("SqliteDatabaseBackend::pragmaToTextEncoding: pragma can't be transformed in a text encoding enumeration!");
372 373 374 375

    return static_cast<TextEncoding>(index);
}

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

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

389 390 391 392 393 394 395 396 397 398
template <typename Type>
Type SqliteDatabaseBackend::toValue(const Utf8String &sqlStatementUtf8)
{
    SqliteReadWriteStatement statement(sqlStatementUtf8, *this);

    statement.next();

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

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