Verified Commit 3a1439f2 authored by WorldTeacher's avatar WorldTeacher
Browse files

fix(database): enhance clearBookCache to safely manage dependencies and improve logging

parent 2376e19a
Loading
Loading
Loading
Loading
+58 −2
Original line number Diff line number Diff line
@@ -1668,8 +1668,64 @@ end

---Database:clearBookCache.
function Database:clearBookCache()
    self.conn:exec("DELETE FROM book_cache")
    local sql_steps = {
        -- Clear synced/history tables that depend on book_cache_id and can be
        -- safely rebuilt on next sync.
        "DELETE FROM synced_annotations",
        "DELETE FROM synced_bookmarks",
        "DELETE FROM rating_sync_history",
        "DELETE FROM book_metadata",

        -- Keep cache rows that are still referenced by pending queues so we do
        -- not break foreign-key constraints and do not lose pending work.
        [[
            DELETE FROM book_cache
            WHERE id NOT IN (
                SELECT book_cache_id FROM pending_annotations
                UNION
                SELECT book_cache_id FROM pending_ratings
                UNION
                SELECT book_cache_id FROM pending_bookmarks
            )
        ]],
    }

    local before = self:getBookCacheStats().total

    local ok_begin, begin_res = pcall(self.conn.exec, self.conn, "BEGIN")
    if not ok_begin or begin_res ~= SQ3.OK then
        self.plugin:logErr("BookloreSync Database: clearBookCache BEGIN failed:", self.conn:errmsg())
        return false
    end

    for _, sql in ipairs(sql_steps) do
        local ok_exec, exec_res = pcall(self.conn.exec, self.conn, sql)
        if not ok_exec or exec_res ~= SQ3.OK then
            pcall(self.conn.exec, self.conn, "ROLLBACK")
            self.plugin:logErr("BookloreSync Database: clearBookCache failed:", self.conn:errmsg(), "SQL:", sql)
            return false
        end
    end

    local ok_commit, commit_res = pcall(self.conn.exec, self.conn, "COMMIT")
    if not ok_commit or commit_res ~= SQ3.OK then
        pcall(self.conn.exec, self.conn, "ROLLBACK")
        self.plugin:logErr("BookloreSync Database: clearBookCache COMMIT failed:", self.conn:errmsg())
        return false
    end

    local after = self:getBookCacheStats().total
    local cleared = math.max(0, before - after)
    if after > 0 then
        self.plugin:logInfo(
            "BookloreSync Database: Book cache cleared partially; retained",
            tostring(after),
            "rows referenced by pending queues"
        )
    else
        self.plugin:logInfo("BookloreSync Database: Book cache cleared")
    end
    self.plugin:logDbg("BookloreSync Database: clearBookCache stats", "before=", tostring(before), "after=", tostring(after), "cleared=", tostring(cleared))
    return true
end