Handle generated keys

This commit is contained in:
Sean Corfield 2019-03-30 23:12:37 -07:00
parent 4741db1453
commit 451a5fbd3b

View file

@ -416,10 +416,14 @@
(defn- reduce-stmt (defn- reduce-stmt
"" ""
[^PreparedStatement stmt f init] [^PreparedStatement stmt f init try-generated-keys?]
(if (.execute stmt) (if-let [^ResultSet rs (if (.execute stmt)
(let [rs (.getResultSet stmt) (.getResultSet stmt)
rs-map (mapify-result-set rs)] (when try-generated-keys?
(try
(.getGeneratedKeys stmt)
(catch Exception _))))]
(let [rs-map (mapify-result-set rs)]
(loop [init' init] (loop [init' init]
(if (.next rs) (if (.next rs)
(let [result (f init' rs-map)] (let [result (f init' rs-map)]
@ -427,7 +431,7 @@
@result @result
(recur result))) (recur result)))
init'))) init')))
(f init (.getUpdateCount stmt)))) (f init {::update-count (.getUpdateCount stmt)})))
(extend-protocol Executable (extend-protocol Executable
Connection Connection
@ -436,7 +440,7 @@
(reify clojure.lang.IReduceInit (reify clojure.lang.IReduceInit
(reduce [_ f init] (reduce [_ f init]
(with-open [stmt (prepare-fn* this sql params factory)] (with-open [stmt (prepare-fn* this sql params factory)]
(reduce-stmt stmt f init)))))) (reduce-stmt stmt f init (:return-keys opts)))))))
DataSource DataSource
(-execute [this [sql & params] opts] (-execute [this [sql & params] opts]
(let [factory (pre-prepare* opts)] (let [factory (pre-prepare* opts)]
@ -444,16 +448,19 @@
(reduce [_ f init] (reduce [_ f init]
(with-open [con (get-connection this opts)] (with-open [con (get-connection this opts)]
(with-open [stmt (prepare-fn* con sql params factory)] (with-open [stmt (prepare-fn* con sql params factory)]
(reduce-stmt stmt f init))))))) (reduce-stmt stmt f init (:return-keys opts))))))))
PreparedStatement PreparedStatement
(-execute [this _ _] (-execute [this _ _]
(reify clojure.lang.IReduceInit (reify clojure.lang.IReduceInit
(reduce [_ f init] (reduce-stmt this f init)))) ;; we can't tell if this PreparedStatement will return generated
;; keys so we pass a truthy value to at least attempt it if we
;; do not get a ResultSet back from the execute call
(reduce [_ f init] (reduce-stmt this f init :maybe-keys))))
Object Object
(-execute [this sql-params opts] (-execute [this sql-params opts]
(-execute (get-datasource this) sql-params opts))) (-execute (get-datasource this) sql-params opts)))
(defn execute! (defn reducible!
"General SQL execution function. "General SQL execution function.
Returns a reducible that, when reduced, runs the SQL and yields the result." Returns a reducible that, when reduced, runs the SQL and yields the result."