Adding sqlite custom function to Qt application

I am trying to add a custom sqlite3 function regexpto my Qt application (as recommended by this answer ). But as soon as I call the function sqlite3_create_function, I get the message The program has unexpectedly finished.When I debug, it completes the segmentation error in sqlite3_mutex_enter. Below is an MWE apology for the absolute file paths.

The implementation regexpin my code is this site ; it also fails with the function msign here . Various checks driver()->handle()are direct from Qt docs.

By the way, I used select sqlite_version();to determine that Qt 5.5 uses the SQL version 3.8.8.2. I found this version by looking at old commits in the Qt GitHub repository.

MWE.pro

QT       += core gui
TARGET = MWE
TEMPLATE = app
QT += sql
SOURCES += main.cpp \
    D:\Qt\Qt5.5.0\5.5\Src\3rdparty\sqlite\sqlite3.c

HEADERS  += D:\Qt\Qt5.5.0\5.5\Src\3rdparty\sqlite\sqlite3.h

main.cpp

#include <QtSql>

#include "D:/Qt/Qt5.5.0/5.5/Src/3rdparty/sqlite/sqlite3.h"

void qtregexp(sqlite3_context* ctx, int argc, sqlite3_value** argv)
{
    QRegExp regex;
    QString str1((const char*)sqlite3_value_text(argv[0]));
    QString str2((const char*)sqlite3_value_text(argv[1]));

    regex.setPattern(str1);
    regex.setCaseSensitivity(Qt::CaseInsensitive);

    bool b = str2.contains(regex);

    if (b)
    {
        sqlite3_result_int(ctx, 1);
    }
    else
    {
        sqlite3_result_int(ctx, 0);
    }
}

int main(int argc, char *argv[])
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("my.db");
    db.open();

    QVariant v = db.driver()->handle();
    if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*")==0) {
        sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());
        if (db_handle != 0) { // check that it is not NULL
            // This shows that the database handle is generally valid:
            qDebug() << sqlite3_db_filename(db_handle, "main");
            sqlite3_create_function(db_handle, "regexp", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, &qtregexp, NULL, NULL);
            qDebug() << "This won't be reached."

            QSqlQuery query;
            query.prepare("select regexp('p$','tap');");
            query.exec();
            query.next();
            qDebug() << query.value(0).toString();
        }
    }
    db.close();
}
+4
source share
1 answer

You need to call sqlite3_initialize()after receiving the database descriptor from Qt, according to this forum post .

    ...
    sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());
    if (db_handle != 0) { // check that it is not NULL
        sqlite3_initialize();
    ...

This solves the problem.

+5
source

Source: https://habr.com/ru/post/1621279/


All Articles