seancorfield / next-jdbc

A modern low-level Clojure wrapper for JDBC-based access to databases.
https://cljdoc.org/d/com.github.seancorfield/next.jdbc/
Eclipse Public License 1.0
755 stars 90 forks source link

gettin-started: validate HikariCP pool #180

Closed holyjak closed 2 years ago

holyjak commented 2 years ago

Fix #179 by improving the docs

seancorfield commented 2 years ago

I'm trying to navigate the c3p0 code to see how it works in this respect. It looks like it tries to create a pool as soon as it can, and resets/recreates it as each property is set into the initially empty object... but that seems a bit improbable so I need to study it further.

I'm going to use my own wording for this, but I'll leave this PR open until I actually commit something.

Here's what I have so far:

You will generally want to create the connection pooled datasource at the start of your program (and close it before you exit, although that's not really important since it'll be cleaned up when the JVM shuts down):

(defn -main [& args]
  ;; db-spec is options to HikariDataSource and must include :username
  (with-open [^HikariDataSource ds (connection/->pool HikariDataSource db-spec)]
    ;; this code ensures a validation check is performed on the datasource:
    (.close (jdbc/get-connection ds))
    ;; otherwise that validation check is deferred until the first connection
    ;; is requested in a regular operation:
    (jdbc/execute! ds ...)
    (jdbc/execute! ds ...)
    (do-other-stuff ds args)
    (into [] (map :column) (jdbc/plan ds ...))))
;; or:
(defn -main [& args]
  ;; db-spec is options to ComboPooledDataSource with :user etc
  (with-open [^PooledDataSource ds (connection/->pool ComboPooledDataSource db-spec)]
    (jdbc/execute! ds ...)
    (jdbc/execute! ds ...)
...
seancorfield commented 2 years ago

OK, the c3p0 code works in essentially the same way as the HikariCP code -- the validation isn't performed until the pool manager is created, which doesn't normally happen until the first connection is requested (or various other methods are called that depend on a pool manager existing).

So I'm going to update the docs in a generic way to show that .close trick for both connection pools.

seancorfield commented 2 years ago

Documentation updated here https://github.com/seancorfield/next-jdbc/commit/f4f743b94f973318a5cd18d860b1ef5f5d4b840d