Skip to content

Commit c5bf2b1

Browse files
committed
Added event on connection loss
1 parent 65c7301 commit c5bf2b1

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

async_postgres.lua

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,15 @@ function Client:runQuery(query)
291291
self.conn:setArrayResult(false)
292292
end
293293

294+
if not ok then
295+
local success, retry = xpcall(function() return self:onEnd() end, self.errorHandler)
296+
if success and retry then
297+
self.queries:prepend(query)
298+
self:processQueue() -- just in case if we somehow already reconnected
299+
return
300+
end
301+
end
302+
294303
xpcall(query.callback, self.errorHandler, ok, result, errdata)
295304
self:processQueue()
296305
end
@@ -457,6 +466,8 @@ function Client:close(wait)
457466
self.conn = nil
458467
self.closed = true
459468
collectgarbage() -- collect PGconn so it will be closed
469+
470+
xpcall(function() return self:onEnd() end, self.errorHandler)
460471
end
461472

462473
--- Returns number of queued queries (does not includes currently executing query)
@@ -658,6 +669,13 @@ function Client:onError(message)
658669
return ErrorNoHaltWithStack(message)
659670
end
660671

672+
--- This **event** function is called whenever connection to the server is lost/closed.
673+
---
674+
--- You can set it to your own function to handle connection loss.
675+
---@return boolean? return true if you want to retry last query
676+
function Client:onEnd()
677+
end
678+
661679
--- Creates a new client with given connection url
662680
--- ```lua
663681
--- local client = async_postgres.Client("postgresql://user:password@localhost:5432/database")

0 commit comments

Comments
 (0)