feat!: validate DB before execution only if needed (#257)

With this commit, it validates DB in its init phase only if it is
invoked by `:Telescope frecency` or `:FrecencyDelete`.
This commit is contained in:
JINNOUCHI Yasushi 2024-09-05 23:12:25 +09:00 committed by GitHub
parent 7634ec0d2d
commit 1b63e9453d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 12 deletions

View File

@ -24,9 +24,10 @@ local frecency = setmetatable({}, {
return function(...)
if not instance() then
rawset(self, "instance", require("frecency.klass").new(database))
local is_async = key == "delete" or key == "validate_database" or key == "register"
instance():setup(is_async)
end
local is_async = key == "delete" or key == "register" or key == "validate_database"
local need_cleanup = key == "delete" or key == "start"
instance():setup(is_async, need_cleanup)
return instance()[key](instance(), ...)
end
end,

View File

@ -13,7 +13,8 @@ local async = lazy_require "plenary.async" --[[@as FrecencyPlenaryAsync]]
local STATUS = {
NEW = 0,
SETUP_CALLED = 1,
SETUP_FINISHED = 2,
DB_STARTED = 2,
CLEANUP_FINISHED = 3,
}
---@class Frecency
@ -33,23 +34,32 @@ end
---This is called when `:Telescope frecency` is called at the first time.
---@param is_async boolean
---@param need_cleanup boolean
---@return nil
function Frecency:setup(is_async)
if self.status >= STATUS.SETUP_CALLED then
function Frecency:setup(is_async, need_cleanup)
if self.status == STATUS.CLEANUP_FINISHED then
return
end
elseif self.status == STATUS.NEW then
self.status = STATUS.SETUP_CALLED
end
timer.track "frecency.setup() start"
---@async
local function init()
if self.status == STATUS.SETUP_CALLED then
self.database:start()
self.status = STATUS.DB_STARTED
timer.track "DB_STARTED"
end
if self.status == STATUS.DB_STARTED and need_cleanup then
self:assert_db_entries()
if config.auto_validate then
self:validate_database()
end
self.status = STATUS.CLEANUP_FINISHED
timer.track "CLEANUP_FINISHED"
end
timer.track "frecency.setup() finish"
self.status = STATUS.SETUP_FINISHED
end
if is_async then
@ -62,7 +72,6 @@ function Frecency:setup(is_async)
return
end
-- NOTE: This means init() has failed. Try again.
self.status = STATUS.NEW
self:error(status == -1 and "init() never returns during the time" or "init() is interrupted during the time")
end
@ -101,6 +110,18 @@ end
---@param force? boolean
---@return nil
function Frecency:validate_database(force)
self:_validate_database(force)
if self.status == STATUS.DB_STARTED then
self.status = STATUS.CLEANUP_FINISHED
end
timer.track "CLEANUP_FINISHED"
end
---@private
---@async
---@param force? boolean
---@return nil
function Frecency:_validate_database(force)
timer.track "validate_database() start"
local unlinked = self.database:unlinked_entries()
timer.track "validate_database() calculate unlinked"