Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a custom sqlite function to a Qt application

Tags:

sqlite

qt

I am trying to add a custom sqlite3 regexp function into my Qt application (as recommended by this answer). But as soon as I call the sqlite3_create_function function, I get the message The program has unexpectedly finished. When I debug, it terminates in a segmentation fault in sqlite3_mutex_enter. There is a MWE below, with apologies for the absolute file paths.

The regexp implementation in my code is from this site; it also fails with the msign function here. The various checks of driver()->handle() are straight from the Qt docs.

Incidentally, I used select sqlite_version(); to determine that Qt 5.5 uses sqlite version 3.8.8.2. I found that version by looking through 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();
}
like image 517
adam.baker Avatar asked Dec 22 '15 11:12

adam.baker


1 Answers

You need to call sqlite3_initialize() after you get the database handle 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 issue.

like image 59
adam.baker Avatar answered Nov 13 '22 03:11

adam.baker