From f217e86038650835c0bf69bc25e903457ccb92d4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 1 Apr 2019 22:19:02 -0700 Subject: [PATCH] Address #2 by adding rs/as-arrays --- src/next/jdbc/result_set.clj | 26 +++++++++++++++++++++++++- test/next/jdbc_test.clj | 4 +++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/next/jdbc/result_set.clj b/src/next/jdbc/result_set.clj index 6f23d1f..2a7eb80 100644 --- a/src/next/jdbc/result_set.clj +++ b/src/next/jdbc/result_set.clj @@ -31,6 +31,10 @@ (.getColumnLabel rsmeta i))) idxs)))) +(defprotocol ColumnarResultSet + (column-names [this]) + (row-values [this])) + (defn- mapify-result-set "Given a result set, return an object that wraps the current row as a hash map. Note that a result set is mutable and the current row will change behind @@ -76,7 +80,27 @@ (seq (mapv (fn [^Integer i] (clojure.lang.MapEntry. (nth @cols (dec i)) (.getObject rs i))) - (range 1 (inc (count @cols))))))))) + (range 1 (inc (count @cols)))))) + + ColumnarResultSet + (column-names [this] @cols) + (row-values [this] + (mapv (fn [^Integer i] (.getObject rs i)) + (range 1 (inc (count @cols)))))))) + +(defn as-arrays + "A reducing function that can be used on a result set to produce an + array-based representation, where the first element is a vector of the + column names in the result set, and subsequent elements are vectors of + the rows from the result set. + + It should be used with a nil initial value: + + (reduce rs/as-arrays nil (reducible! con sql-params))" + [result rs-map] + (if result + (conj result (row-values rs-map)) + (conj [(column-names rs-map)] (row-values rs-map)))) (defn- reduce-stmt "Execute the PreparedStatement, attempt to get either its ResultSet or diff --git a/test/next/jdbc_test.clj b/test/next/jdbc_test.clj index 8183c77..88e16b3 100644 --- a/test/next/jdbc_test.clj +++ b/test/next/jdbc_test.clj @@ -149,4 +149,6 @@ (execute! con ["select * from fruit where name = ?" "Pear"]) (delete! con :fruit {:id 1}) - (update! con :fruit {:appearance "Brown"} {:name "Banana"})) + (update! con :fruit {:appearance "Brown"} {:name "Banana"}) + + (reduce rs/as-arrays nil (reducible! con ["select * from fruit"])))