r2dbc-pool
r2dbc-pool copied to clipboard
Simplify getting connections from ConnectionFactory
Feature Request
Is your feature request related to a problem? Please describe
It seems a recommended pattern for working with a ConnectionFactory
is to write something like
Flux.usingWhen(
connectionFactory.create(),
connection -> connection.createStatement(...).execute(),
Connection::close)
)
Before working with r2dbc, I had some experience with Hibernate Reactive and they expose a pattern like this:
sessionFactory.withSession(
session -> /// do something with the session
)
where the user doesn't have to worry about creating or closing the session. Would it be possible to add something similar to the ConnectionFactory
interface.
Describe the solution you'd like
Perhaps the solution method could look something like:
default Flux<Result> withConnection(Function<Connection, Publisher<? extends Result>> connectionClosure){
return Flux.usingWhen(
connectionFactory.create(),
connectionClosure,
Connection::close
);
}
Describe alternatives you've considered
The alternative is to continue using the boilerplate above wherever we need to work with a connection.
Teachability, Documentation, Adoption, Migration Strategy
If introduced, this would not replace any methods already declared in the ConnectionFactory interface and could potentially be introduced as a default method in the interface so that each implementation of ConnectionFactory would not need to write it.
I also wondered whether this would be a good enhancement for R2DBC Pool. I moved the ticket into the Pool project because the SPI Spec doesn't depend on Project Reactor while the Pool implementation has a direct dependency on Project Reactor.
Would you want to craft a pull request that introduces methods returning Mono
/Flux
on the ConnectionPool
class? withConnection
/withConnectionMany
might be good candidates naming-wise.
Sure. I can take a stab at it. Just need to get approval from my employer to do it.