sqlite_orm icon indicating copy to clipboard operation
sqlite_orm copied to clipboard

Add non-const getters to iterator

Open kiwixz opened this issue 2 years ago • 2 comments

Iterator has const operators since #685 (see here).

This makes it impossible to do in-place update (modify the value and pass it to update) when iterating the database. I think we should add non-const overloads.

Thanks!

kiwixz avatar Jun 03 '22 20:06 kiwixz

hi. Can you provide a small code snippet to repro it please?

fnc12 avatar Jun 04 '22 03:06 fnc12

Sure ! Here you go:

struct S {
    int id;
    int value;
    int some_other_information;
};

void f() {
    auto db = make_storage(path,
                        make_table("currency",
                                    make_column("id", &S::id, primary_key()),
                                    make_column("value", &S::code),
                                    make_column("some_other_information", &S::some_other_information)));

    for (auto& s : db.iterate<S>()) {
        // get a new value here for the id, so we want to update it in database
        int new_value = 42;

        // easy way (not working, s is actually a const&)
        s.value = new_value;
        db.update(s);

        // longer way (working)
        db.update(S{s.id, new_value, s.some_other_information});
    }
}

kiwixz avatar Jun 04 '22 09:06 kiwixz

@kiwixz BTW you can use const_cast which will make the work. Why don't you use this approach?

fnc12 avatar Oct 10 '23 16:10 fnc12

I would not want to do that, if I'm allowed to modify the value then it should not be returned to me as a const&. const_cast says "I dont care if I'm not supposed to, I will modify this anyway".

kiwixz avatar Oct 10 '23 17:10 kiwixz

PR https://github.com/fnc12/sqlite_orm/pull/1229

fnc12 avatar Oct 10 '23 18:10 fnc12

merged. Please check dev branch. Also it will be merged into master on the next release

fnc12 avatar Oct 11 '23 06:10 fnc12

Works great, thanks!

kiwixz avatar Oct 11 '23 09:10 kiwixz