Skip to content

Commit 928a4af

Browse files
[jdbc] Try to unwrap any java.sql.Connection instance for dispatch purposes (#206)
1 parent 26f6c71 commit 928a4af

3 files changed

Lines changed: 23 additions & 12 deletions

File tree

src/toucan2/jdbc.clj

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,12 @@
2424
"com.mysql.cj.MysqlConnection"])
2525
(require 'toucan2.jdbc.mysql-mariadb))
2626

27-
;;; c3p0 and Hikari integration: when we encounter a wrapped connection pool connection, dispatch off of the class of
28-
;;; connection it wraps
29-
(doseq [pool-connection-class-name ["com.mchange.v2.c3p0.impl.NewProxyConnection"
30-
"com.zaxxer.hikari.pool.HikariProxyConnection"]]
31-
(when-let [pool-connection-class (class-for-name pool-connection-class-name)]
32-
(extend pool-connection-class
33-
protocols/IDispatchValue
34-
{:dispatch-value (fn [^java.sql.Wrapper conn]
35-
(try
36-
(protocols/dispatch-value (.unwrap conn java.sql.Connection))
37-
(catch Throwable _
38-
pool-connection-class)))})))
27+
;;; c3p0 and Hikari integration, or any other library that wraps real SQL connections: when we encounter a wrapped
28+
;;; connection, dispatch off of the class of connection it wraps
29+
(extend java.sql.Connection
30+
protocols/IDispatchValue
31+
{:dispatch-value (fn [^java.sql.Wrapper conn]
32+
(try
33+
(type (.unwrap conn java.sql.Connection))
34+
(catch Throwable _
35+
(type conn))))})

src/toucan2/tools/identity_query.clj

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,14 @@
7474
;;;; Identity connection
7575

7676
(deftype ^:no-doc IdentityConnection []
77+
java.sql.Wrapper
78+
(isWrapperFor [_this klass]
79+
(= klass java.sql.Connection))
80+
(unwrap [this klass]
81+
(if (.isWrapperFor this klass)
82+
this
83+
(throw (ex-info (str "IdentityConnection is not the wrapper for " klass) {}))))
84+
7785
pretty/PrettyPrintable
7886
(pretty [_this]
7987
(list `->IdentityConnection)))

test/toucan2/tools/identity_query_test.clj

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
[toucan2.tools.identity-query :as identity-query]
1111
[toucan2.tools.named-query :as tools.named-query]))
1212

13+
(set! *warn-on-reflection* true)
14+
1315
(deftest ^:parallel query-test
1416
(is (= [[1 2]
1517
[:a :b]]
@@ -81,6 +83,10 @@
8183
(testing "Return plain rows, not instances"
8284
(is (not (instance/instance? (first results))))))))
8385

86+
(deftest ^:parallel can-unwrap-identity-connection
87+
(let [conn (identity-query/->IdentityConnection)]
88+
(is (identical? conn (.unwrap ^java.sql.Wrapper conn java.sql.Connection)))))
89+
8490
;; (deftest ^:parallel insert-test
8591
;; (testing "Can we use identity-query with insert?"
8692
;; (is (= [(instance/instance :venues {:a 1})]

0 commit comments

Comments
 (0)