I am working on an S4 class that contains a DBIConnection
to a database in one of its slots. When the S4 object is initiated, I pass the constructor an open connection, which is stored in the connection
slot.
setClass(
"MyClass",
slots = c(
connection = "DBIConnection"
),
prototype = list(
connection = NULL,
)
)
Now I am wondering how I should handle closing it when the object is removed. For now, I have defined a disconnect
method for the class that calls DBI::dbDiscconnect
on the connection. But that requires a user to call it explicitly. (Note: I _have_ getters & setters, but omitted them here for brevity.)
setGeneric("disconnect", function(x) {
standardGeneric("disconnect")
})
setMethod("disconnect", signature = "MyClass", function(x) {
DBI::dbDisconnect(x@connection)
})
Is there a way to call DBI::dbDisconnect
automatically when an instance of MyClass
is removed? I have been going through the documentation of the withr
package, which allows the definition of deferred functions that are executed e.g. when the parent frame / environment is closed (much in the spirit of the on.exit() base R function).
But I don't understand whether a function (e.g. dbDisconnect) can be triggered when an S4 object is removed (either during an analysis workflow or at the end of a session). __Any pointers would be great!__
Or maybe I am overthinking this? E.g. the RPostgres documentation states:
Manually disconnecting a connection is not necessary with RPostgres, but still recommended; if you delete the object containing the connection, it will be automatically disconnected during the next GC with a warning.
Perhaps I should just rely on connections being cleaned up automatically? (That could be ok for SQLite and Postgres, but other database engines might complain...)
BTW generally speaking this kind of question about package development is better asked on the bioc-devel mailing list. You will more likely receive useful feedback from other developers there than on this support site which is mostly for discussion about usage of the Bioconductor software.