oatpp / oatpp-sqlite

SQLite adapter for oatpp ORM.
https://oatpp.io/
Apache License 2.0
23 stars 18 forks source link

How to properly enable foreign_keys support #22

Open nyyakko opened 1 month ago

nyyakko commented 1 month ago

Anyone cares to shed a light on how to enable foreign_keys with this library? I've tried doing the following:

OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::provider::Provider<oatpp::sqlite::Connection>>, dbConnectionProvider)([] {
    auto connectionProvider = std::make_shared<oatpp::sqlite::ConnectionProvider>("database.sqlite");
    auto result = sqlite3_exec(connectionProvider->get().object.get()->getHandle(), "PRAGMA foreign_keys=ON;", nullptr, nullptr, nullptr);
    assert(result == SQLITE_OK && "ERROR ENABLING foreign_keys");
    return oatpp::sqlite::ConnectionPool::createShared(connectionProvider, 10, std::chrono::seconds(5));
}());

without success. if anyone could help me with this I'd be glad.

nyyakko commented 1 month ago

Let me elabore a bit better on what I'm trying to achieve here. I have two tables:

CREATE TABLE "child" (
    "id" INTEGER NOT NULL,
    "parentId" INTEGER NOT NULL REFERENCES parent ON DELETE CASCADE,
    PRIMARY KEY ("id" AUTOINCREMENT)
);

CREATE TABLE "parent" (
    "id" INTEGER NOT NULL,
    PRIMARY KEY ("id" AUTOINCREMENT)
);

Making that when I delete the parent table, the child table is automatically deleted together in a cascade fashion. The thing is that thats not what happening currently. I did a quick research and learned that sqlite disables the foreign_keys pragma for backward compatibility, which, as far as I understand (firs time playing around with databases), would actually make possible for me to achieve the behavior I want.

so the question here really is about how I can enable that pragma so I can achieve the behavior I want? Is there any other way to achieve this? Is it documented?