[odb-users] ODB + SQLite savepoints

Dieter Govaerts dieter.govaerts at bricsys.com
Fri Jul 1 02:59:02 EDT 2016


Hi Tiago,

> Looking at the documentation I don't see anything that mentions the ability
> to use SQLite savepoints with ODB (maybe I missed something?). Is there
> such functionality?

It's easy to write something yourself. This is what I use:

class Savepoint
{
public:
    Savepoint(odb::database& db)
        : m_db(db), m_name(newName()), m_released(false)
    {
        std::stringstream ss;
        ss << "SAVEPOINT '" << m_name << "'";
        db.execute(ss.str());
    }
    ~Savepoint()
    {
        release();
    }

    void release()
    {
        if (m_released)
            return;
        std::stringstream ss;
        ss << "RELEASE SAVEPOINT '" << m_name << "'";
        m_db.execute(ss.str());
        m_released = true;
    }
    void rollbackTo()
    {
        if (m_released)
            return;
        std::stringstream ss;
        ss << "ROLLBACK TO SAVEPOINT '" << m_name << "'";
        m_db.execute(ss.str());
    }

    class Guard
    {
    public:
        Guard(Savepoint& sp) : m_sp(sp), m_dismissed(false) {}
        ~Guard() { if (!m_dismissed) m_sp.rollbackTo(); }
        void dismiss() { m_dismissed = true; }

    private:
        Savepoint& m_sp;
        bool m_dismissed;
    };

private:
    static std::string newName()
    {
        static boost::uuids::random_generator rand_gen;
        return boost::uuids::to_string(rand_gen());
    }

private:
    odb::database& m_db;
    std::string m_name;
    bool m_released;
};

You can implement the newName() function in any way you like. I used boost uuids for unique names.

Dieter





More information about the odb-users mailing list