sqlite_orm icon indicating copy to clipboard operation
sqlite_orm copied to clipboard

Distinguish `sync_schema_result::dropped_and_recreated` with and without backup

Open HansH opened this issue 4 months ago • 0 comments

See this example:

#include <iostream>
#include <sqlite_orm/sqlite_orm.h>
#include <string>

using namespace sqlite_orm;

struct MyTableRecord {
    int id = 0;
    std::string name;
};

int main() {
    {
        auto storage = make_storage("db.sqlite",
            make_table("MyTable",
               make_column("id", &MyTableRecord::id)));
        storage.sync_schema(true);
        storage.insert(MyTableRecord{1, ""});
        storage.insert(MyTableRecord{2, ""});
    }
    {
        std::cout << "When adding a primary key:\n";
        auto storage = make_storage("db.sqlite",
            make_table("MyTable",
               make_column("id", &MyTableRecord::id, primary_key())));
        for (auto& [tableName, result] : storage.sync_schema(true)) {
            std::cout << tableName << ": " << result << std::endl;
        }
        auto allRecords = storage.get_all<MyTableRecord>();
        for (auto& record : storage.get_all<MyTableRecord>()) {
            std::cout << record.id <<std::endl;
        }
    }
    {
        std::cout << "When adding a non-null column without default value:\n";
        auto storage = make_storage("db.sqlite",
            make_table("MyTable",
               make_column("id", &MyTableRecord::id, primary_key()),
               make_column("name", &MyTableRecord::name)));
        for (auto& [tableName, result] : storage.sync_schema(true)) {
            std::cout << tableName << ": " << result << std::endl;
        }
        for (auto& record : storage.iterate<MyTableRecord>()) {
            std::cout << record.id <<std::endl;
        }
    }

    return 0;
}

This outputs:

When adding a primary key:
MyTable: old table dropped and recreated
1
2
When adding a non-null column without default value:
MyTable: old table dropped and recreated

Note that in both cases sync_schema returns sync_schema_result::dropped_and_recreated for MyTable. In the first case the table is backed up and we don't lose data. But in the second case the data is lost.

sync_schema_simulate returns the same. We would like to be able to use sync_schema_simulate to ensure that we don't lose data when the database scheme is updated. But if both cases return the same, that is not possible. Am I missing something?

I think it would make sense if the sync_schema_result enum had two different options for these two cases. But that would break the API of the library, so I'm not sure if that is a change you are willing to make.

HansH avatar Oct 15 '25 14:10 HansH