From f86856275b0456e38ce0c3a5695214518910fe11 Mon Sep 17 00:00:00 2001 From: Juergen Hoetzel Date: Sat, 12 May 2012 17:36:17 +0200 Subject: [PATCH 001/630] add make-cols-unique test case: empty cols Signed-off-by: Sean Corfield --- src/test/clojure/clojure/java/test_utilities.clj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index be743f7f..f7fc5803 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -90,6 +90,7 @@ (deftest test-make-cols-unique (let [make-cols-unique @#'sql/make-cols-unique] + (is (= '() (make-cols-unique '()))) (is (= '("a") (make-cols-unique '("a")))) (is (= '("a" "a_2") (make-cols-unique '("a" "a")))) (is (= '("a" "b" "a_2" "a_3") (make-cols-unique '("a" "b" "a" "a")))) From 8e93bb52a847e84a9404d6f1154950a2e65315ff Mon Sep 17 00:00:00 2001 From: Juergen Hoetzel Date: Sat, 12 May 2012 18:29:39 +0200 Subject: [PATCH 002/630] distinct? throws clojure.lang.ArityException, when applied with no arguments. HSQLDB returns an empty ResultSet when using (.getGeneratedKeys stmt) and no keys are generated. So this Exception is thrown for each record without generated keys. Also rewrite make-cols-unique implementation using high-order functions instead of "low-level" loop/recur. Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 67dcc5df..8878786b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -201,13 +201,9 @@ generated keys are returned (as a map)." } "Given a collection of column names, rename duplicates so that the result is a collection of unique column names." [cols] - (if (apply distinct? cols) + (if (or (not (seq cols)) (apply distinct? cols)) cols - (loop [[col-name :as new-cols] (seq cols) - unique-cols []] - (if (seq new-cols) - (recur (rest new-cols) (conj unique-cols (make-name-unique unique-cols col-name 1))) - unique-cols)))) + (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) (defn resultset-seq "Creates and returns a lazy sequence of maps corresponding to From b424da419f9633d138275ace544014543bc8b77e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 15:23:48 -0700 Subject: [PATCH 003/630] Use empty? instead of not seq --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8878786b..94d399c7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -201,7 +201,7 @@ generated keys are returned (as a map)." } "Given a collection of column names, rename duplicates so that the result is a collection of unique column names." [cols] - (if (or (not (seq cols)) (apply distinct? cols)) + (if (or (empty? cols) (apply distinct? cols)) cols (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) From e0dacd7754260ecc84e1c48675fc613283c7ad31 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 15:34:24 -0700 Subject: [PATCH 004/630] Ensure metadata test works with mysql-str-db --- src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 42afb6e2..6e4fc65d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -343,7 +343,7 @@ (deftest test-metadata (doseq [db (test-specs)] - (when-not (.endsWith ^String (:subprotocol db) "sqlserver") + (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) (let [metadata (sql/with-connection db (into [] From 5401437ff03137f154d089daca3ec243fa133b19 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 15:45:46 -0700 Subject: [PATCH 005/630] Add test for jdbc: prefix (and correct create-test-table to allow for it) --- src/test/clojure/clojure/java/test_jdbc.clj | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 6e4fc65d..bc6c6b0a 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -91,6 +91,9 @@ (def mysql-str-db "mysql://clojure_test:clojure_test@localhost:3306/clojure_test") +(def mysql-jdbc-str-db + "jdbc:mysql://clojure_test:clojure_test@localhost:3306/clojure_test") + (def postgres-str-db "postgres://clojure_test:clojure_test@localhost/clojure_test") @@ -131,7 +134,7 @@ [:appearance "VARCHAR(32)"] [:cost :int] [:grade :real] - :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"^mysql" db))) + :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))) "ENGINE=InnoDB" "")))) (deftest test-create-table From f5d1991f05728f2b5f3017d34b55d4357f966871 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 15:46:08 -0700 Subject: [PATCH 006/630] Strip optional jdbc: prefix before parsing string as URI. --- src/main/clojure/clojure/java/jdbc.clj | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 94d399c7..cd8ef8fa 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -134,6 +134,11 @@ generated keys are returned (as a map)." } {:user (first (str/split user-info #":")) :password (second (str/split user-info #":"))})))) +(defn- strip-jdbc [^String spec] + (if (.startsWith spec "jdbc:") + (.substring spec 5) + spec)) + (defn- get-connection "Creates a connection to a database. db-spec is a map containing values for one of the following parameter sets: @@ -165,7 +170,7 @@ generated keys are returned (as a map)." } (instance? URI db-spec) (get-connection (parse-properties-uri db-spec)) (string? db-spec) - (get-connection (URI. db-spec)) + (get-connection (URI. (strip-jdbc db-spec))) factory (factory (dissoc db-spec :factory)) (and subprotocol subname) From e505ac3cf7b117f5f41c2e6ab028e2a4debfaf42 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 15:46:31 -0700 Subject: [PATCH 007/630] Add 0.2.1 changes and start 0.2.2 changes --- CHANGES.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index 270ba7a3..6adc7060 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,11 @@ +Changes in 0.2.2: +* Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) +* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) + +Changes in 0.2.1: +* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29) +* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30) + Changes in 0.2.0: * Merge internal namespace into main jdbc namespace and update symbol visibility / naming. From fbdf17aa0be67ff1cfd15fcf63871f36f9fa1d64 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 15:55:55 -0700 Subject: [PATCH 008/630] Documentation updates for 0.2.2 release. --- README.md | 9 ++++++--- src/main/clojure/clojure/java/jdbc.clj | 9 ++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 01aebb00..85b02746 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Formerly known as clojure.contrib.sql. Releases and Dependency Information ======================================== -Latest stable release: 0.2.1 +Latest stable release: 0.2.2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -18,14 +18,14 @@ Latest stable release: 0.2.1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: - [org.clojure/java.jdbc "0.2.1"] + [org.clojure/java.jdbc "0.2.2"] [Maven](http://maven.apache.org/) dependency information: org.clojure java.jdbc - 0.2.1 + 0.2.2 @@ -88,6 +88,9 @@ Developer Information Change Log ==================== +* Release 0.2.2 on 2012-06-10 + * Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) + * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) * Release 0.2.1 on 2012-05-10 * Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29) * Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index cd8ef8fa..8cf4a02b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -160,7 +160,14 @@ generated keys are returned (as a map)." } JNDI: :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map" + :environment (optional) a java.util.Map + + URI: + Parsed JDBC connection string - see below + + String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." [{:keys [factory classname subprotocol subname datasource username password From 71df7bebb4dfd013d5abc15eef34482738de5389 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Jun 2012 16:13:38 -0700 Subject: [PATCH 009/630] Fix JDBC-33 and update documentation. --- CHANGES.txt | 1 + README.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 16 ++++++++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 6adc7060..b5439337 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,5 @@ Changes in 0.2.2: +* Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) * Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) diff --git a/README.md b/README.md index 85b02746..ef922ad5 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ Change Log ==================== * Release 0.2.2 on 2012-06-10 + * Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) * Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) * Release 0.2.1 on 2012-05-10 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8cf4a02b..0a04b5ac 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -404,6 +404,18 @@ generated keys are returned (as a map)." } [] (rollback)) +(defn- execute-batch + "Executes a batch of SQL commands and returns a sequence of update counts. + (-2) indicates a single operation operating on an unknown number of rows. + Specifically, Oracle returns that and we must call getUpdateCount() to get + the actual number of rows affected. In general, operations return an array + of update counts, so this may not be a general solution for Oracle..." + [stmt] + (let [result (.executeBatch stmt)] + (if (and (= 1 (count result)) (= -2 (first result))) + (list (.getUpdateCount stmt)) + (seq result)))) + (defn do-commands "Executes SQL commands on the open database connection." [& commands] @@ -411,7 +423,7 @@ generated keys are returned (as a map)." } (doseq [^String cmd commands] (.addBatch stmt cmd)) (transaction - (seq (.executeBatch stmt))))) + (execute-batch stmt)))) (def ^{:private true :doc "Map friendly :concurrency values to ResultSet constants."} @@ -482,7 +494,7 @@ generated keys are returned (as a map)." } (doseq [param-group param-groups] (set-parameters stmt param-group) (.addBatch stmt)) - (transaction* (fn [] (seq (.executeBatch stmt)))))))) + (transaction* (fn [] (execute-batch stmt))))))) (defn create-table-ddl "Given a table name and column specs with an optional table-spec From ffb284804d0fb56f86b2ea4a7c23d884702226c7 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 10 Jun 2012 18:24:28 -0500 Subject: [PATCH 010/630] [maven-release-plugin] prepare release java.jdbc-0.2.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f9c06286..5a067644 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.2.2-SNAPSHOT + 0.2.2 ${project.artifactId} From a2f3f511777c924338216c2112d28c086a4e5eb3 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 10 Jun 2012 18:24:28 -0500 Subject: [PATCH 011/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5a067644..10b56bdb 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.2.2 + 0.2.3-SNAPSHOT ${project.artifactId} From 7f3e6cf389371cddd90a0392a08c95c1f0879f22 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 13 Jun 2012 22:50:12 -0700 Subject: [PATCH 012/630] Tidy up README. --- README.md | 65 ++++++++++++++++++++++++------------------------------- 1 file changed, 28 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index ef922ad5..7c9bf43d 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,6 @@ A Clojure wrapper for JDBC-based access to databases. Formerly known as clojure.contrib.sql. - - Releases and Dependency Information ======================================== @@ -17,43 +15,40 @@ Latest stable release: 0.2.2 * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~) [Leiningen](https://github.com/technomancy/leiningen) dependency information: - - [org.clojure/java.jdbc "0.2.2"] - +```clojure +[org.clojure/java.jdbc "0.2.2"] +``` [Maven](http://maven.apache.org/) dependency information: - - - org.clojure - java.jdbc - 0.2.2 - - - +```xml + + org.clojure + java.jdbc + 0.2.2 + +``` Example Usage ======================================== - - (require '[clojure.java.jdbc :as sql]) - - (def mysql-db {:subprotocol "mysql" - :subname "//127.0.0.1:3306/clojure_test" - :user "clojure_test" - :password "clojure_test"}) - - (sql/with-connection mysql-db - (sql/insert-records :fruit - {:name "Apple" :appearance "rosy" :cost 24} - {:name "Orange" :appearance "round" :cost 49})) - - (sql/with-connection mysql-db - (sql/with-query-results rows - ["SELECT * FROM fruit WHERE appearance = ?" "rosy"] - (:cost (first rows)))) - +```clojure +(require '[clojure.java.jdbc :as sql]) + +(def mysql-db {:subprotocol "mysql" + :subname "//127.0.0.1:3306/clojure_test" + :user "clojure_test" + :password "clojure_test"}) + +(sql/with-connection mysql-db + (sql/insert-records :fruit + {:name "Apple" :appearance "rosy" :cost 24} + {:name "Orange" :appearance "round" :cost 49})) + +(sql/with-connection mysql-db + (sql/with-query-results rows + ["SELECT * FROM fruit WHERE appearance = ?" "rosy"] + (:cost (first rows)))) +``` For more detail see the [generated documentation on github](http://clojure.github.com/java.jdbc/). - - Developer Information ======================================== @@ -83,8 +78,6 @@ Developer Information $ TEST_DBS=mysql,postgres mvn test - - Change Log ==================== @@ -145,8 +138,6 @@ Change Log * Add insert-record function * Clojure 1.3 compatibility - - Copyright and License ======================================== From 30ed894e8ed17d9688e45ba2e283eddb464874e3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 13 Jun 2012 23:48:29 -0700 Subject: [PATCH 013/630] Add :connection-uri option (and tidy up get-connection code) JDBC-34 --- CHANGES.txt | 3 +++ src/main/clojure/clojure/java/jdbc.clj | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index b5439337..524754c1 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,6 @@ +Changes in 0.2.3-SNAPSHOT: +* Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) + Changes in 0.2.2: * Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) * Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 0a04b5ac..ea70b54d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -169,6 +169,7 @@ generated keys are returned (as a map)." } subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." [{:keys [factory + connection-uri classname subprotocol subname datasource username password name environment] @@ -176,25 +177,35 @@ generated keys are returned (as a map)." } (cond (instance? URI db-spec) (get-connection (parse-properties-uri db-spec)) + (string? db-spec) (get-connection (URI. (strip-jdbc db-spec))) + factory (factory (dissoc db-spec :factory)) + + connection-uri + (DriverManager/getConnection connection-uri) + (and subprotocol subname) (let [url (format "jdbc:%s:%s" subprotocol subname) etc (dissoc db-spec :classname :subprotocol :subname) classname (or classname (classnames subprotocol))] (clojure.lang.RT/loadClassForName classname) (DriverManager/getConnection url (as-properties etc))) + (and datasource username password) (.getConnection ^DataSource datasource ^String username ^String password) + datasource (.getConnection ^DataSource datasource) + name (let [env (and environment (Hashtable. ^Map environment)) context (InitialContext. env) ^DataSource datasource (.lookup context ^String name)] (.getConnection datasource)) + :else (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] (throw (IllegalArgumentException. msg))))) From ae5b12c682d62bed5595820c205d744cab228f0e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 15 Jun 2012 20:17:42 -0700 Subject: [PATCH 014/630] Update doc-string for get-connection for JDBC-34 change --- src/main/clojure/clojure/java/jdbc.clj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ea70b54d..6c0f10e7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -162,6 +162,10 @@ generated keys are returned (as a map)." } :name (required) a String or javax.naming.Name :environment (optional) a java.util.Map + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + URI: Parsed JDBC connection string - see below From 76a37f370017d2e0511912d2142c80a427922f41 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 15 Jun 2012 22:45:29 -0700 Subject: [PATCH 015/630] Updated with-connection doc-string and stripped get-connection doc-string. The db-spec documentation was in two places and get-connection had been updated most recently so they were out of sync. Given that get-connection is private, it makes more sense for with-connection to have the definitive documentation and for get-connection to just refer to it. --- src/main/clojure/clojure/java/jdbc.clj | 47 ++++++++------------------ 1 file changed, 14 insertions(+), 33 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6c0f10e7..8e1171ac 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -140,38 +140,8 @@ generated keys are returned (as a map)." } spec)) (defn- get-connection - "Creates a connection to a database. db-spec is a map containing values - for one of the following parameter sets: - - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DriverManager: - :subprotocol (required) a String, the jdbc subprotocol - :subname (required) a String, the jdbc subname - :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties. - - DataSource: - :datasource (required) a javax.sql.DataSource - :username (optional) a String - :password (optional) a String, required if :username is supplied - - JNDI: - :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map - - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - - URI: - Parsed JDBC connection string - see below - - String: - subprotocol://user:password@host:post/subname - An optional prefix of jdbc: is allowed." + "Creates a connection to a database. db-spec is a map containing connection + parameters - see with-connection for full details." [{:keys [factory connection-uri classname subprotocol subname @@ -345,7 +315,18 @@ generated keys are returned (as a map)." } JNDI: :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map" + :environment (optional) a java.util.Map + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + + URI: + Parsed JDBC connection string - see below + + String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." [db-spec & body] `(with-connection* ~db-spec (fn [] ~@body))) From b3f959f2f4a5b75fc0c7da971e0a793227d49ed9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 16 Jun 2012 02:39:28 -0700 Subject: [PATCH 016/630] Allow as-str to process :x.y as a pair of identifiers. --- src/main/clojure/clojure/java/jdbc.clj | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8e1171ac..e603809c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -57,10 +57,18 @@ generated keys are returned (as a map)." } (defn as-str "Given a naming strategy and a keyword, return the keyword as a string per that naming strategy. Given (a naming strategy and) - a string, return it as-is." + a string, return it as-is. + A keyword of the form :x.y is treated as keywords :x and :y, + both are turned into strings via the naming strategy and then + joined back together so :x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." [f x] (if (instance? clojure.lang.Named x) - (f (name x)) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))) (str x))) (defn as-key From d85e1779ee3943374e8761acf988391c6b7246eb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 16 Jun 2012 09:51:54 -0700 Subject: [PATCH 017/630] Unit tests for new as-identifier behavior. --- .../clojure/clojure/java/test_utilities.clj | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index f7fc5803..8024d334 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -27,41 +27,49 @@ (is (= "kw" (sql/as-identifier "kw"))) (is (= "kw" (sql/as-identifier :kw))) (is (= "KW" (sql/as-identifier "KW"))) - (is (= "KW" (sql/as-identifier :KW)))) + (is (= "KW" (sql/as-identifier :KW))) + (is (= "k.w" (sql/as-identifier :k.w)))) (deftest test-as-keyword (is (= :kw (sql/as-keyword "kw"))) (is (= :kw (sql/as-keyword :kw))) (is (= :kw (sql/as-keyword "KW"))) - (is (= :KW (sql/as-keyword :KW)))) + (is (= :KW (sql/as-keyword :KW))) + (is (= :k.w (sql/as-keyword :k.w)))) (deftest test-quoted (is (= "kw" (sql/as-quoted-identifier [ \[ \] ] "kw"))) (is (= "[kw]" (sql/as-quoted-identifier [ \[ \] ] :kw))) (is (= "KW" (sql/as-quoted-identifier \` "KW"))) - (is (= "`KW`" (sql/as-quoted-identifier \` :KW)))) + (is (= "`KW`" (sql/as-quoted-identifier \` :KW))) + (is (= "`k`.`w`" (sql/as-quoted-identifier \` :k.w)))) (def quote-dash { :entity (partial sql/as-quoted-str \`) :keyword #(.replace % "_" "-") }) (deftest test-named (is (= "kw" (sql/as-named-identifier quote-dash "kw"))) (is (= "`kw`" (sql/as-named-identifier quote-dash :kw))) + (is (= "`k`.`w`" (sql/as-named-identifier quote-dash :k.w))) (is (= :K-W (sql/as-named-keyword quote-dash "K_W"))) - (is (= :K_W (sql/as-named-keyword quote-dash :K_W)))) + (is (= :K_W (sql/as-named-keyword quote-dash :K_W))) + (is (= :k.w (sql/as-named-keyword quote-dash :k.w)))) (deftest test-with-quote (sql/with-quoted-identifiers [ \[ \] ] (is (= "kw" (sql/as-identifier "kw"))) (is (= "[kw]" (sql/as-identifier :kw))) (is (= "KW" (sql/as-identifier "KW"))) - (is (= "[KW]" (sql/as-identifier :KW))))) + (is (= "[KW]" (sql/as-identifier :KW))) + (is (= "[k].[w]" (sql/as-identifier :k.w))))) (deftest test-with-naming (sql/with-naming-strategy quote-dash (is (= "kw" (sql/as-identifier "kw"))) (is (= "`kw`" (sql/as-identifier :kw))) + (is (= "`k`.`w`" (sql/as-identifier :k.w))) (is (= :K-W (sql/as-keyword "K_W"))) - (is (= :K_W) (sql/as-keyword :K_W)))) + (is (= :K_W) (sql/as-keyword :K_W)) + (is (= :k.w) (sql/as-keyword :k.w)))) (deftest test-print-update-counts (let [bu-ex (java.sql.BatchUpdateException. (int-array [1 2 3]))] From d0bf0174daa802e34fc4336c2bc32c46f74b8348 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 Jun 2012 14:00:37 -0700 Subject: [PATCH 018/630] Prepare for 0.2.3 release (updated README / CHANGES). --- CHANGES.txt | 3 ++- README.md | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 524754c1..dc665604 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,5 @@ -Changes in 0.2.3-SNAPSHOT: +Changes in 0.2.3: +* as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] * Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) Changes in 0.2.2: diff --git a/README.md b/README.md index 7c9bf43d..0086cdd9 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Formerly known as clojure.contrib.sql. Releases and Dependency Information ======================================== -Latest stable release: 0.2.2 +Latest stable release: 0.2.3 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -16,14 +16,14 @@ Latest stable release: 0.2.2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.2.2"] +[org.clojure/java.jdbc "0.2.3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.2.2 + 0.2.3 ``` @@ -81,6 +81,9 @@ Developer Information Change Log ==================== +* Release 0.2.3 on 2012-06-18 + * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] + * Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) * Release 0.2.2 on 2012-06-10 * Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) * Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) From 776e95da03463c13e003a2f25ef035d9a26a725a Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 18 Jun 2012 16:15:37 -0500 Subject: [PATCH 019/630] [maven-release-plugin] prepare release java.jdbc-0.2.3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 10b56bdb..3be69a24 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.2.3-SNAPSHOT + 0.2.3 ${project.artifactId} From 538acaf4756455fda00068fc59a2b984bbf0b89b Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 18 Jun 2012 16:15:37 -0500 Subject: [PATCH 020/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3be69a24..be67d150 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.2.3 + 0.2.4-SNAPSHOT ${project.artifactId} From 629893eac45050197c37c3e1342de2ad1c232291 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 26 Jun 2012 11:34:00 -0700 Subject: [PATCH 021/630] Remove reflection warning --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e603809c..50db285f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -414,7 +414,7 @@ generated keys are returned (as a map)." } Specifically, Oracle returns that and we must call getUpdateCount() to get the actual number of rows affected. In general, operations return an array of update counts, so this may not be a general solution for Oracle..." - [stmt] + [^Statement stmt] (let [result (.executeBatch stmt)] (if (and (= 1 (count result)) (= -2 (first result))) (list (.getUpdateCount stmt)) From e445aab53f87d59fc64fc7d491bdd885722c1763 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Jul 2012 16:19:07 -0700 Subject: [PATCH 022/630] Add some notes to the README about 3rd party database drivers. --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 0086cdd9..3cf29f88 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,28 @@ Latest stable release: 0.2.3 0.2.3 ``` +You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, +shown as Leiningen dependencies: +```clojure +;; Apache Derby +[org.apache.derby/derby "10.8.1.2"] +;; HSQLDB +[hsqldb/hsqldb "1.8.0.10"] +;; Microsoft SQL Server using the jTDS driver +[net.sourceforge.jtds/jtds "1.2.4"] +;; MySQL +[mysql/mysql-connector-java "5.1.6"] +;; PostgreSQL +[postgresql/postgresql "8.4-702.jdbc4"] +;; SQLite +[org.xerial/sqlite-jdbc "3.7.2"] +``` +For the latest versions, consult the vendor or project websites. clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 3.0 but that +has to be downloaded manually and placed in a Maven repository accessible to your system. For testing, it was installed locally as: +```clojure +;; Microsoft SQL Server JDBC4 Driver 3.0 +[sqljdbc4/sqljdbc4 "3.0"] +``` Example Usage ======================================== From 4e87c30d79db8000b593049aab7dfa41931d3cb2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 12 Aug 2012 23:51:34 -0700 Subject: [PATCH 023/630] Tweak resultset-seq to have identifiers naming strategy passed in. This is in preparation for the new API without dynamic variables. --- src/main/clojure/clojure/java/jdbc.clj | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 50db285f..ea339979 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -216,13 +216,14 @@ generated keys are returned (as a map)." } but it respects the current naming strategy. Duplicate column names are made unique by appending _N before applying the naming strategy (where N is a unique integer)." - [^ResultSet rs] + [^ResultSet rs & {:keys [identifiers] + :or {identifiers *as-key*}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) make-cols-unique - (map (comp keyword *as-key*))) + (map (comp keyword identifiers))) row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As From 09057bf8de166de1ade59ca9ccf65e129f6b4f53 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 10 Sep 2012 16:41:17 -0700 Subject: [PATCH 024/630] Fix JDBC-39 by forcing Boolean column extraction when metadata indicates BOOLEAN type. Since (.getBoolean) seems able to sometimes return a Boolean false that isn't identical to CLojure's false, the result of (.getBoolean) is forced to nil, true or false as appropriate. Additional tests have been added for MySQL only. I have not been able to reproduce the not-a-boolean situation however, to verify that calling the (pure-boolean) function is appropriate. This forms the basis for extracting other columns based on their correct, known SQL type, regardless of other field flags. --- src/main/clojure/clojure/java/jdbc.clj | 22 ++++++- src/test/clojure/clojure/java/test_jdbc.clj | 72 +++++++++++++++------ 2 files changed, 73 insertions(+), 21 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ea339979..82fb3797 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -37,7 +37,7 @@ the number of rows affected, except for a single record insert where any generated keys are returned (as a map)." } clojure.java.jdbc (:import [java.net URI] - [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement] + [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet ResultSetMetaData SQLException Statement] [java.util Hashtable Map Properties] [javax.naming InitialContext Name] [javax.sql DataSource]) @@ -210,6 +210,22 @@ generated keys are returned (as a map)." } cols (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) +(defn- pure-boolean + "Given a Boolean from the database, map it correctly to Clojure's boolean (or nil)." + [b] + (cond (nil? b) nil + (= b true) true + :else false)) + +(defn- column-extractor + "Given a ResultSet and its metadata, return a function that takes a column index and returns the column value. + Currently we only special case BOOLEAN but we may special case others over time." + [^ResultSet rs ^ResultSetMetaData rsmd] + (fn [^Integer i] + (condp = (.getColumnType rsmd i) + java.sql.Types/BOOLEAN (pure-boolean (.getBoolean rs i)) + (.getObject rs i)))) + (defn resultset-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Based on clojure.core/resultset-seq @@ -218,13 +234,13 @@ generated keys are returned (as a map)." } N is a unique integer)." [^ResultSet rs & {:keys [identifiers] :or {identifiers *as-key*}}] - (let [rsmeta (.getMetaData rs) + (let [^ResultSetMetaData rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) make-cols-unique (map (comp keyword identifiers))) - row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) + row-values (fn [] (map (column-extractor rs rsmeta) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index bc6c6b0a..da7ac0bb 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -103,21 +103,31 @@ (for [db test-databases] @(ns-resolve 'clojure.java.test-jdbc (symbol (str (name db) "-db"))))) +;; Utility to detect MySQL database since we do some +;; MySQL-specific tests... + +(defn- mysql? [db] + (let [p (:subprotocol db)] + (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))))) + +;; Fixture to drop known tables before each test + (defn- clean-up "Attempt to drop any test tables before we start a test." [t] (doseq [db (test-specs)] - (sql/with-connection db - (doseq [table [:fruit :fruit2 :veggies :veggies2]] - (try - (sql/drop-table table) - (catch Exception _ - ;; ignore - ))))) + (let [tables [:fruit :fruit2 :veggies :veggies2]] + (sql/with-connection db + (doseq [table (if (mysql? db) (conj tables :booleantest) tables)] + (try + (sql/drop-table table) + (catch Exception _ + ;; ignore + )))))) (t)) (use-fixtures - :each clean-up) + :each clean-up) ;; We start with all tables dropped and each test has to create the tables ;; necessary for it to do its job, and populate it as needed... @@ -126,16 +136,14 @@ "Create a standard test table. Must be inside with-connection. For MySQL, ensure table uses an engine that supports transactions!" [table db] - (let [p (:subprotocol db)] - (sql/create-table - table - [:id :int (if (= "mysql" p) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] - [:name "VARCHAR(32)" (if (= "mysql" p) "" "PRIMARY KEY")] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))) - "ENGINE=InnoDB" "")))) + (sql/create-table + table + [:id :int (if (mysql? db) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] + [:name "VARCHAR(32)" (if (mysql? db) "" "PRIMARY KEY")] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec (if (mysql? db) "ENGINE=InnoDB" ""))) (deftest test-create-table (doseq [db (test-specs)] @@ -344,6 +352,34 @@ (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) +(deftest mysql-boolean-processing + (doseq [db (test-specs)] + (when (mysql? db) + (sql/with-connection db + (sql/create-table + :booleantest + [:id :int "PRIMARY KEY AUTO_INCREMENT"] + [:t "BIT(1) DEFAULT b'1'"] + [:f "BIT(1) DEFAULT b'0'"] + :table-spec "ENGINE=InnoDB") + (let [r (sql/insert-records + :booleantest + {:t 1} + {:f 0})] + (is (= '({:generated_key 1} {:generated_key 2}) r)) + (let [rs (sql/with-query-results res + ["SELECT * FROM booleantest WHERE id = 1"] + (doall res))] + (is (= '({:id 1 :t true :f false}) rs)) + (is (= :valid (if (:t (first rs)) :valid :invalid))) + (is (= :valid (if (:f (first rs)) :invalid :valid)))) + (let [rs (sql/with-query-results res + ["SELECT * FROM booleantest WHERE id = 2"] + (doall res))] + (is (= '({:id 2 :t true :f false}) rs)) + (is (= :valid (if (:t (first rs)) :valid :invalid))) + (is (= :valid (if (:f (first rs)) :invalid :valid))))))))) + (deftest test-metadata (doseq [db (test-specs)] (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) From f144182968198bc16b5fb1db2ef757519752cd28 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 10 Sep 2012 17:20:38 -0700 Subject: [PATCH 025/630] Add recent (snapshot) changes to CHANGES.txt in preparation for next release. --- CHANGES.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index dc665604..d996c367 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,9 @@ +Changes in 0.2.4-SNAPSHOT +* Remove reflection warning from execute-batch +* Add notes to README about 3rd party database driver dependencies +* Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy +* Extract Boolean columns explicitly to avoid byte[] issues in certain situations [JDBC-39](http://dev.clojure.org/jira/browse/JDBC-39) + Changes in 0.2.3: * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] * Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) From 0c509ebf4241dd46d39a536aa979f9231c826286 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 10 Sep 2012 17:42:48 -0700 Subject: [PATCH 026/630] Revert "Fix JDBC-39 by forcing Boolean column extraction when metadata indicates BOOLEAN type." This reverts commit 09057bf8de166de1ade59ca9ccf65e129f6b4f53. --- src/main/clojure/clojure/java/jdbc.clj | 22 +------ src/test/clojure/clojure/java/test_jdbc.clj | 72 ++++++--------------- 2 files changed, 21 insertions(+), 73 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 82fb3797..ea339979 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -37,7 +37,7 @@ the number of rows affected, except for a single record insert where any generated keys are returned (as a map)." } clojure.java.jdbc (:import [java.net URI] - [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet ResultSetMetaData SQLException Statement] + [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement] [java.util Hashtable Map Properties] [javax.naming InitialContext Name] [javax.sql DataSource]) @@ -210,22 +210,6 @@ generated keys are returned (as a map)." } cols (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) -(defn- pure-boolean - "Given a Boolean from the database, map it correctly to Clojure's boolean (or nil)." - [b] - (cond (nil? b) nil - (= b true) true - :else false)) - -(defn- column-extractor - "Given a ResultSet and its metadata, return a function that takes a column index and returns the column value. - Currently we only special case BOOLEAN but we may special case others over time." - [^ResultSet rs ^ResultSetMetaData rsmd] - (fn [^Integer i] - (condp = (.getColumnType rsmd i) - java.sql.Types/BOOLEAN (pure-boolean (.getBoolean rs i)) - (.getObject rs i)))) - (defn resultset-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Based on clojure.core/resultset-seq @@ -234,13 +218,13 @@ generated keys are returned (as a map)." } N is a unique integer)." [^ResultSet rs & {:keys [identifiers] :or {identifiers *as-key*}}] - (let [^ResultSetMetaData rsmeta (.getMetaData rs) + (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) make-cols-unique (map (comp keyword identifiers))) - row-values (fn [] (map (column-extractor rs rsmeta) idxs)) + row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index da7ac0bb..bc6c6b0a 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -103,31 +103,21 @@ (for [db test-databases] @(ns-resolve 'clojure.java.test-jdbc (symbol (str (name db) "-db"))))) -;; Utility to detect MySQL database since we do some -;; MySQL-specific tests... - -(defn- mysql? [db] - (let [p (:subprotocol db)] - (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))))) - -;; Fixture to drop known tables before each test - (defn- clean-up "Attempt to drop any test tables before we start a test." [t] (doseq [db (test-specs)] - (let [tables [:fruit :fruit2 :veggies :veggies2]] - (sql/with-connection db - (doseq [table (if (mysql? db) (conj tables :booleantest) tables)] - (try - (sql/drop-table table) - (catch Exception _ - ;; ignore - )))))) + (sql/with-connection db + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/drop-table table) + (catch Exception _ + ;; ignore + ))))) (t)) (use-fixtures - :each clean-up) + :each clean-up) ;; We start with all tables dropped and each test has to create the tables ;; necessary for it to do its job, and populate it as needed... @@ -136,14 +126,16 @@ "Create a standard test table. Must be inside with-connection. For MySQL, ensure table uses an engine that supports transactions!" [table db] - (sql/create-table - table - [:id :int (if (mysql? db) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] - [:name "VARCHAR(32)" (if (mysql? db) "" "PRIMARY KEY")] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec (if (mysql? db) "ENGINE=InnoDB" ""))) + (let [p (:subprotocol db)] + (sql/create-table + table + [:id :int (if (= "mysql" p) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] + [:name "VARCHAR(32)" (if (= "mysql" p) "" "PRIMARY KEY")] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))) + "ENGINE=InnoDB" "")))) (deftest test-create-table (doseq [db (test-specs)] @@ -352,34 +344,6 @@ (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) -(deftest mysql-boolean-processing - (doseq [db (test-specs)] - (when (mysql? db) - (sql/with-connection db - (sql/create-table - :booleantest - [:id :int "PRIMARY KEY AUTO_INCREMENT"] - [:t "BIT(1) DEFAULT b'1'"] - [:f "BIT(1) DEFAULT b'0'"] - :table-spec "ENGINE=InnoDB") - (let [r (sql/insert-records - :booleantest - {:t 1} - {:f 0})] - (is (= '({:generated_key 1} {:generated_key 2}) r)) - (let [rs (sql/with-query-results res - ["SELECT * FROM booleantest WHERE id = 1"] - (doall res))] - (is (= '({:id 1 :t true :f false}) rs)) - (is (= :valid (if (:t (first rs)) :valid :invalid))) - (is (= :valid (if (:f (first rs)) :invalid :valid)))) - (let [rs (sql/with-query-results res - ["SELECT * FROM booleantest WHERE id = 2"] - (doall res))] - (is (= '({:id 2 :t true :f false}) rs)) - (is (= :valid (if (:t (first rs)) :valid :invalid))) - (is (= :valid (if (:f (first rs)) :invalid :valid))))))))) - (deftest test-metadata (doseq [db (test-specs)] (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) From 1e055c687688db7174b1c935ac6ac4490178f10c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 10 Sep 2012 17:43:46 -0700 Subject: [PATCH 027/630] Remove JDBC-39 fix - since it doesn't work in the field (and slows things down). --- CHANGES.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGES.txt b/CHANGES.txt index d996c367..4d5d541f 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -2,7 +2,6 @@ Changes in 0.2.4-SNAPSHOT * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy -* Extract Boolean columns explicitly to avoid byte[] issues in certain situations [JDBC-39](http://dev.clojure.org/jira/browse/JDBC-39) Changes in 0.2.3: * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] From 3b64ab4edabed2f7de6dc1f0675472ec2a0873e6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 24 Dec 2012 16:42:40 -0800 Subject: [PATCH 028/630] Part of JDBC-20 - add optional SQL generation DSL and tests. --- src/main/clojure/clojure/java/jdbc/sql.clj | 233 +++++++++++++++++++++ src/test/clojure/clojure/java/test_sql.clj | 118 +++++++++++ 2 files changed, 351 insertions(+) create mode 100644 src/main/clojure/clojure/java/jdbc/sql.clj create mode 100644 src/test/clojure/clojure/java/test_sql.clj diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj new file mode 100644 index 00000000..8312082c --- /dev/null +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -0,0 +1,233 @@ +;; Copyright (c) Sean Corfield. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; sql.clj +;; +;; A basic SQL DSL for use with clojure.java.jdbc (or you can use any +;; other SQL DSL you want to...) +;; +;; seancorfield (gmail) +;; December 2012 + +(ns + ^{:author "Sean Corfield", + :doc "An optional DSL for generating SQL. + +Intended to be used with clojure.java.jdbc, this provides a simple DSL - +Domain Specific Language - that generates raw SQL strings. Any other DSL +can be used instead. This DSL is entirely optional and is deliberately +not very sophisticated. It is sufficient to support the delete!, insert! +and update! high-level operations within clojure.java.jdbc directly." } + clojure.java.jdbc.sql + (:require [clojure.string :as str] + [clojure.walk :as walk])) + +;; implementation utilities + +(defn- as-str + "Given a naming strategy and a keyword, return the keyword as a + string per that naming strategy. Given (a naming strategy and) + a string, return it as-is. + A keyword of the form :x.y is treated as keywords :x and :y, + both are turned into strings via the naming strategy and then + joined back together so :x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." + [f x] + (if (instance? clojure.lang.Named x) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))) + (str x))) + +(defn- as-identifier + "Given a keyword, convert it to a string using the current naming + strategy. + Given a string, return it as-is." + [x f-entity] + (as-str f-entity x)) + +(defn- as-quoted-str + "Given a quoting pattern - either a single character or a vector pair of + characters - and a string, return the quoted string: + (as-quoted-str X foo) will return XfooX + (as-quoted-str [A B] foo) will return AfooB" + [q x] + (if (vector? q) + (str (first q) x (last q)) + (str q x q))) + +(defn- col-str [col entities] + (if (map? col) + (let [[k v] (first col)] + (str (as-identifier k entities) " AS " (as-identifier v entities))) + (as-identifier col entities))) + +(defn- table-str [table entities] + (if (map? table) + (let [[k v] (first table)] + (str (as-identifier k entities) " " (as-identifier v entities))) + (as-identifier table entities))) + +(def ^:private entity-symbols + #{"delete" "delete!" + "insert" "insert!" + "select" "join" "where" "order-by" + "update" "update!"}) + +(def ^:private identifier-symbols + #{"query"}) + +(defn- order-direction [col entities] + (if (map? col) + (str (as-identifier (first (keys col)) entities) + " " + (let [dir (first (vals col))] + (get {:asc "ASC" :desc "DESC"} dir dir))) + (str (as-identifier col entities) " ASC"))) + +(defn- insert-multi-row [table columns values entities] + (let [nc (count columns) + vcs (map count values)] + (if (not (apply = nc vcs)) + (throw (IllegalArgumentException. "insert called with inconsistent number of columns / values")) + (into [(str "INSERT INTO " (table-str table entities) " ( " + (str/join ", " (map (fn [col] (col-str col entities)) columns)) + " ) VALUES " + (str/join ", " + (repeat (count values) + (str "( " + (str/join ", " (repeat nc "?")) + " )"))))] + (apply concat values))))) + +(defn- insert-single-row [table row entities] + (let [ks (keys row)] + (into [(str "INSERT INTO " (table-str table entities) " ( " + (str/join ", " (map (fn [col] (col-str col entities)) ks)) + " ) VALUES ( " + (str/join ", " (repeat (count ks) "?")) + " )")] + (vals row)))) + +;; quoting strategy helpers + +(defmacro entities [entities sql] + (walk/postwalk (fn [form] + (if (and (seq? form) + (symbol? (first form)) + (entity-symbols (name (first form)))) + (concat form [:entities entities]) + form)) sql)) + +(defmacro identifiers [identifiers sql] + (walk/postwalk (fn [form] + (if (and (seq? form) + (symbol? (first form)) + (identifier-symbols (name (first form)))) + (concat form [:identifiers identifiers]) + form)) sql)) + +;; some common quoting strategies + +(def as-is identity) +(def lower-case str/lower-case) +(defn quoted [q] (partial as-quoted-str q)) + +;; SQL generation functions + +(defn delete [table [where & params] & {:keys [entities] :or {entities as-is}}] + (into [(str "DELETE FROM " (table-str table entities) + (when where " WHERE ") where)] + params)) + +(defn insert [table & clauses] + (let [rows (take-while map? clauses) + n-rows (count rows) + cols-and-vals-etc (drop n-rows clauses) + cols-and-vals (take-while (comp not keyword?) cols-and-vals-etc) + n-cols-and-vals (count cols-and-vals) + no-cols-and-vals (zero? n-cols-and-vals) + options (drop (+ (count rows) (count cols-and-vals)) clauses) + {:keys [entities] :or {entities as-is}} (apply hash-map options)] + (if (zero? n-rows) + (if no-cols-and-vals + (throw (IllegalArgumentException. "insert called without data to insert")) + (if (< n-cols-and-vals 2) + (throw (IllegalArgumentException. "insert called with columns but no values")) + (insert-multi-row table (first cols-and-vals) (rest cols-and-vals) entities))) + (if no-cols-and-vals + (map (fn [row] (insert-single-row table row entities)) rows) + (throw (IllegalArgumentException. "insert may take records or columns and values, not both")))))) + +(defn join [table on-map & {:keys [entities] :or {entities as-is}}] + (str "JOIN " (table-str table entities) " ON " + (str/join + " AND " + (map (fn [[k v]] (str (as-identifier k entities) " = " (as-identifier v entities))) on-map)))) + +(defn order-by [cols & {:keys [entities] :or {entities as-is}}] + (str "ORDER BY " + (if (or (string? cols) (keyword? cols) (map? cols)) + (order-direction cols entities) + (str/join "," (map #(order-direction % entities) cols))))) + +(defn select [col-seq table & clauses] + (let [joins (take-while string? clauses) + where-etc (drop (count joins) clauses) + [where-clause & more] where-etc + [where & params] (when-not (keyword? where-clause) where-clause) + order-etc (if (keyword? where-clause) where-etc more) + [order-clause & more] order-etc + order-by (when (string? order-clause) order-clause) + options (if order-by more order-etc) + {:keys [entities] :or {entities as-is}} (apply hash-map options)] + (cons (str "SELECT " + (cond + (= * col-seq) "*" + (or (string? col-seq) + (keyword? col-seq) + (map? col-seq)) (col-str col-seq entities) + :else (str/join "," (map #(col-str % entities) col-seq))) + " FROM " (table-str table entities) + (when (seq joins) (str/join " " (cons "" joins))) + (when where " WHERE ") + where + (when order-by " ") + order-by) + params))) + +(defn update [table set-map & where-etc] + (let [[where-clause & options] (when-not (keyword? (first where-etc)) where-etc) + [where & params] where-clause + {:keys [entities] :or {entities as-is}} (if (keyword? (first where-etc)) where-etc options) + ks (keys set-map) + vs (vals set-map)] + (cons (str "UPDATE " (table-str table entities) + " SET " (str/join + "," + (map (fn [k v] + (str (as-identifier k entities) + " = " + (if (nil? v) "NULL" "?"))) + ks vs)) + (when where " WHERE ") + where) + (concat (remove nil? vs) params)))) + +(defn where [param-map & {:keys [entities] :or {entities as-is}}] + (let [ks (keys param-map) + vs (vals param-map)] + (cons (str/join + " AND " + (map (fn [k v] + (str (as-identifier k entities) + (if (nil? v) " IS NULL" " = ?"))) + ks vs)) + (remove nil? vs)))) diff --git a/src/test/clojure/clojure/java/test_sql.clj b/src/test/clojure/clojure/java/test_sql.clj new file mode 100644 index 00000000..a43a11a2 --- /dev/null +++ b/src/test/clojure/clojure/java/test_sql.clj @@ -0,0 +1,118 @@ +;; Copyright (c) Sean Corfield. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; test_sql.clj +;; +;; This namespace contains tests that exercise the optional DSL +;; portion of java.jdbc. +;; +;; seancorfield (gmail) +;; Constructured from tests for jsql DSL December 2012 + +(ns clojure.java.test-sql + (:use clojure.test + clojure.java.jdbc.sql)) + +(deftest select-dsl + (is (= ["SELECT * FROM table"] (select * :table))) + (is (= ["SELECT id FROM table"] (select :id :table))) + (is (= ["SELECT id,name FROM table"] (select [:id :name] :table))) + (is (= ["SELECT id AS foo,name FROM table"] (select [{:id :foo} :name] :table))) + (is (= ["SELECT t.id FROM table t"] (select :t.id {:table :t})))) + +(deftest quoting-fns + (is (= "`a`" ((quoted \`) "a"))) + (is (= "`A`" ((quoted \`) "A"))) + (is (= "a" (as-is "a"))) + (is (= "A" (as-is "A"))) + (is (= "a" (lower-case "a"))) + (is (= "a" (lower-case "A")))) + +(deftest select-entities + (is (= ["SELECT * FROM `table`"] (entities (quoted \`) (select * :table)))) + (is (= ["SELECT * FROM table"] (entities as-is (select * :table)))) + (is (= ["SELECT `t`.`id` FROM `table` `t`"] (entities (quoted \`) (select :t.id {:table :t}))))) + +(deftest join-dsl + (is (= "JOIN t ON a.id = t.id" (join :t {:a.id :t.id})))) + +(deftest select-join-dsl + (is (= ["SELECT * FROM a JOIN b ON a.id = b.id"] (select * :a (join :b {:a.id :b.id})))) + (is (= ["SELECT * FROM a JOIN b ON a.id = b.id JOIN c ON c.id = b.id"] + (select * :a (join :b {:a.id :b.id}) (join :c {:c.id :b.id}))))) + +(deftest where-dsl + (is (= ["id = ?" 42] (where {:id 42}))) + (is (= ["id IS NULL"] (where {:id nil})))) + +(deftest select-where-dsl + (is (= ["SELECT * FROM a WHERE c = ? AND b = ?" 3 2] + (select * :a (where {:b 2 :c 3})))) + (is (= ["SELECT * FROM a WHERE c IS NULL AND b = ?" 2] + (select * :a (where {:b 2 :c nil}))))) + +(deftest order-by-dsl + (is (= "ORDER BY a ASC" (order-by :a))) + (is (= "ORDER BY a ASC" (order-by [:a]))) + (is (= "ORDER BY a DESC" (order-by {:a :desc}))) + (is (= "ORDER BY a ASC,b ASC" (order-by [:a :b]))) + (is (= "ORDER BY a DESC,b ASC" (order-by [{:a :desc} :b]))) + (is (= "ORDER BY a DESC,b DESC" (order-by [{:a :desc} {:b :desc}]))) + (is (= "ORDER BY `a` ASC,`b` DESC" (entities (quoted \`) (order-by [{:a :asc} {:b :desc}])))) + (is (= "ORDER BY `a` ASC,`b` DESC" (order-by [{:a :asc} {:b :desc}] :entities (quoted \`))))) + +(deftest select-order-dsl + (is (= ["SELECT id FROM person ORDER BY name ASC"] (select :id :person (order-by :name)))) + (is (= ["SELECT a FROM b JOIN c ON b.id = c.id ORDER BY d ASC" + (select :a :b (join :c {:b.id :c.id}) (order-by :d))])) + (is (= ["SELECT a FROM b WHERE c = ? ORDER BY d ASC" 3] + (select :a :b (where {:c 3}) (order-by :d)))) + (is (= ["SELECT a FROM b JOIN c ON b.id = c.id WHERE d = ? ORDER BY e ASC" 4] + (select :a :b (join :c {:b.id :c.id}) (where {:d 4}) (order-by :e))))) + +(deftest select-join-alias-dsl + (is (= ["SELECT a.id,b.name FROM aa a JOIN bb b ON a.id = b.id WHERE b.test = ?" 42] + (select [:a.id :b.name] {:aa :a} + (join {:bb :b} {:a.id :b.id}) + (where {:b.test 42})))) + (is (= ["SELECT `a`.`id`,`b`.`name` FROM `aa` `a` JOIN `bb` `b` ON `a`.`id` = `b`.`id` WHERE `b`.`test` = ?" 42] + (entities (quoted \`) + (select [:a.id :b.name] {:aa :a} + (join {:bb :b} {:a.id :b.id}) + (where {:b.test 42})))))) + +(deftest update-dsl + (is (= ["UPDATE a SET b = ?" 2] (update :a {:b 2}))) + (is (= ["UPDATE a SET b = ? WHERE c = ?" 2 3] (update :a {:b 2} (where {:c 3})))) + (is (= ["UPDATE `a` SET `b` = ? WHERE `c` = ?" 2 3] + (entities (quoted \`) (update :a {:b 2} (where {:c 3})))))) + +(deftest delete-dsl + (is (= ["DELETE FROM a WHERE b = ?" 2] (delete :a (where {:b 2})))) + (is (= ["DELETE FROM a WHERE c IS NULL AND b = ?" 2] (delete :a (where {:b 2 :c nil})))) + (is (= ["DELETE FROM `a` WHERE `b` = ?" 2] + (entities (quoted \`) (delete :a (where {:b 2})))))) + +(deftest insert-dsl + (is (= ["INSERT INTO a ( b ) VALUES ( ? )" 2] (insert :a [:b] [2]))) + (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2]] (insert :a {:b 2}))) + (is (= ["INSERT INTO a ( b ) VALUES ( ? ), ( ? )" 2 3] (insert :a [:b] [2] [3]))) + (is (= ["INSERT INTO a ( b, c, d ) VALUES ( ?, ?, ? ), ( ?, ?, ? )" 2 3 4 3 4 5] + (insert :a [:b :c :d] [2 3 4] [3 4 5]))) + (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2] + ["INSERT INTO a ( b ) VALUES ( ? )" 3]] + (insert :a {:b 2} {:b 3}))) + (is (= ["INSERT INTO `a` ( `b` ) VALUES ( ? )" 2] + (entities (quoted \`) (insert :a [:b] [2]))))) + +(deftest bad-insert-args + (is (thrown? IllegalArgumentException (insert))) + (is (thrown? IllegalArgumentException (insert :a))) + (is (thrown? IllegalArgumentException (insert :a [:b]))) + (is (thrown? IllegalArgumentException (insert :a {:b 1} [:c] [2]))) + (is (thrown? IllegalArgumentException (insert :a [:b] [2 3])))) \ No newline at end of file From 59511108fc42a44024aac37ba7be4cb4ec05a25e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 24 Dec 2012 17:13:30 -0800 Subject: [PATCH 029/630] Make new private def's compatible with 1.2.x --- src/main/clojure/clojure/java/jdbc/sql.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 8312082c..e15e2317 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -75,13 +75,13 @@ and update! high-level operations within clojure.java.jdbc directly." } (str (as-identifier k entities) " " (as-identifier v entities))) (as-identifier table entities))) -(def ^:private entity-symbols +(def ^{:private true} entity-symbols #{"delete" "delete!" "insert" "insert!" "select" "join" "where" "order-by" "update" "update!"}) -(def ^:private identifier-symbols +(def ^{:private true} identifier-symbols #{"query"}) (defn- order-direction [col entities] From 1055c393365af761eded07fc2ef3870bf46cfc52 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 24 Dec 2012 17:18:20 -0800 Subject: [PATCH 030/630] Allow for different order traversal in maps for three tests. --- src/test/clojure/clojure/java/test_sql.clj | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/test/clojure/clojure/java/test_sql.clj b/src/test/clojure/clojure/java/test_sql.clj index a43a11a2..aa080ba9 100644 --- a/src/test/clojure/clojure/java/test_sql.clj +++ b/src/test/clojure/clojure/java/test_sql.clj @@ -51,9 +51,11 @@ (is (= ["id IS NULL"] (where {:id nil})))) (deftest select-where-dsl - (is (= ["SELECT * FROM a WHERE c = ? AND b = ?" 3 2] + (is (#{["SELECT * FROM a WHERE c = ? AND b = ?" 3 2] + ["SELECT * FROM a WHERE b = ? AND c = ?" 2 3]} (select * :a (where {:b 2 :c 3})))) - (is (= ["SELECT * FROM a WHERE c IS NULL AND b = ?" 2] + (is (#{["SELECT * FROM a WHERE c IS NULL AND b = ?" 2] + ["SELECT * FROM a WHERE b = ? AND c IS NULL" 2]} (select * :a (where {:b 2 :c nil}))))) (deftest order-by-dsl @@ -94,7 +96,9 @@ (deftest delete-dsl (is (= ["DELETE FROM a WHERE b = ?" 2] (delete :a (where {:b 2})))) - (is (= ["DELETE FROM a WHERE c IS NULL AND b = ?" 2] (delete :a (where {:b 2 :c nil})))) + (is (#{["DELETE FROM a WHERE c IS NULL AND b = ?" 2] + ["DELETE FROM a WHERE b = ? AND c IS NULL" 2]} + (delete :a (where {:b 2 :c nil})))) (is (= ["DELETE FROM `a` WHERE `b` = ?" 2] (entities (quoted \`) (delete :a (where {:b 2})))))) From 81180300c756f963635122905d5ba901790bd3db Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 25 Dec 2012 20:51:15 -0800 Subject: [PATCH 031/630] JDBC-20 Add in new API and tests - still need to rewrite old functions in terms of new ones. --- src/main/clojure/clojure/java/jdbc.clj | 202 +++++++++++++++++++- src/test/clojure/clojure/java/test_jdbc.clj | 141 +++++++++++++- 2 files changed, 341 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ea339979..50e5c33e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -42,7 +42,8 @@ generated keys are returned (as a map)." } [javax.naming InitialContext Name] [javax.sql DataSource]) (:refer-clojure :exclude [resultset-seq]) - (:require [clojure.string :as str])) + (:require [clojure.string :as str] + [clojure.java.jdbc.sql :as sql])) (def ^{:private true :dynamic true :doc "The default entity naming strategy is to do nothing."} @@ -722,3 +723,202 @@ generated keys are returned (as a map)." } index (get special-counts count count)))) (.getUpdateCounts exception)))) + +;; java.jdbc pieces rewritten to not use dynamic bindings + +(defn db-find-connection + "Returns the current database connection (or nil if there is none)" + ^java.sql.Connection [db] + (:connection db)) + +(defn db-connection + "Returns the current database connection (or throws if there is none)" + ^java.sql.Connection [db] + (or (db-find-connection db) + (throw (Exception. "no current database connection")))) + +(defn- db-rollback + "Accessor for the rollback flag on the current connection" + ([db] + (deref (:rollback db))) + ([db val] + (swap! (:rollback db) (fn [_] val)))) + +(defn- throw-non-rte + [^Throwable ex] + (cond (instance? java.sql.SQLException ex) (throw ex) + (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) + :else (throw ex))) + +(defn db-transaction* + "Evaluates func as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If rollback is set within scope of the outermost transaction, + the entire transaction will be rolled back rather than committed when + complete." + [db func] + (let [nested-db (update-in db [:level] inc)] + ;; This ugliness makes it easier to catch SQLException objects + ;; rather than something wrapped in a RuntimeException which + ;; can really obscure your code when working with JDBC from + ;; Clojure... :( + (if (= (:level nested-db) 1) + (let [^java.sql.Connection con (db-connection nested-db) + auto-commit (.getAutoCommit con)] + (io! + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-rollback nested-db) + (.rollback con) + (.commit con)) + result) + (catch Exception e + (.rollback con) + (throw-non-rte e)) + (finally + (db-rollback nested-db false) + (.setAutoCommit con auto-commit))))) + (try + (func nested-db) + (catch Exception e + (throw-non-rte e)))))) + +(defn db-do-prepared-return-keys + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. The param-group is a seq of values for all of + the parameters. + Return the generated keys for the (single) update/insert." + [db transaction? sql param-group] + (with-open [^PreparedStatement stmt (prepare-statement (db-connection db) sql :return-keys true)] + (set-parameters stmt param-group) + (letfn [(exec-and-return-keys [_] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (resultset-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] + (if transaction? + (db-transaction* db exec-and-return-keys) + (try + (exec-and-return-keys db) + (catch Exception e + (throw-non-rte e))))))) + +(defn db-do-prepared + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. Each param-group is a seq of values for all of + the parameters. + Return a seq of update counts (one count for each param-group)." + [db transaction? sql & param-groups] + (with-open [^PreparedStatement stmt (prepare-statement (db-connection db) sql)] + (if (empty? param-groups) + (if transaction? + (db-transaction* db (fn [_] (vector (.executeUpdate stmt)))) + (try + (vector (.executeUpdate stmt)) + (catch Exception e + (throw-non-rte e)))) + (do + (doseq [param-group param-groups] + (set-parameters stmt param-group) + (.addBatch stmt)) + (if transaction? + (db-transaction* db (fn [_] (execute-batch stmt))) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e)))))))) + +(defn db-with-query-results* + "Executes a query, then evaluates func passing in a seq of the results as + an argument. The first argument is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + [db sql-params func identifiers] + (when-not (vector? sql-params) + (let [^Class sql-params-class (class sql-params) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-params-class) + (pr-str sql-params))] + (throw (IllegalArgumentException. msg)))) + (let [special (first sql-params) + sql-is-first (string? special) + options-are-first (map? special) + sql (cond sql-is-first special + options-are-first (second sql-params)) + params (vec (cond sql-is-first (rest sql-params) + options-are-first (rest (rest sql-params)) + :else (rest sql-params))) + prepare-args (when (map? special) (flatten (seq special)))] + (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) + special + (apply prepare-statement (db-connection db) sql prepare-args))] + (set-parameters stmt params) + (with-open [rset (.executeQuery stmt)] + (func (resultset-seq rset :identifiers identifiers)))))) + +;; top-level API for actual SQL operations + +(defn query [db sql-params & {:keys [result-set-fn row-fn identifiers] + :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] + (with-open [^java.sql.Connection con (get-connection db)] + (db-with-query-results* + (assoc db :connection con :level 0 :rollback (atom false)) + (vec sql-params) + (fn [rs] + (result-set-fn (map row-fn rs))) + identifiers))) + +(defn execute! [db sql-params & {:keys [transaction?] + :or {transaction? true}}] + (with-open [^java.sql.Connection con (get-connection db)] + (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) + transaction? + (first sql-params) + (rest sql-params)))) + +(defn delete! [db table where-map & {:keys [entities transaction?] + :or {entities sql/as-is transaction? true}}] + (execute! db + (sql/delete table where-map :entities entities) + :transaction? transaction?)) + +(defn insert! [db table & maps-or-cols-and-values-etc] + (let [stmts (apply sql/insert table maps-or-cols-and-values-etc) + transaction? true] + (with-open [^java.sql.Connection con (get-connection db)] + (if (string? (first stmts)) + (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) + transaction? + (first stmts) + (rest stmts)) + (doall (map (fn [row] + (let [result (db-do-prepared-return-keys + (assoc db :connection con :level 0 :rollback (atom false)) + transaction? + (first row) + (rest row))] + (if (map? result) (first (vals result)) result))) + stmts)))))) + +(defn update! [db table set-map where-map & {:keys [entities transaction?] + :or {entities sql/as-is transaction? true}}] + (execute! db + (sql/update table set-map where-map :entities entities) + :transaction? transaction?)) \ No newline at end of file diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index bc6c6b0a..0f9aebbf 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -22,7 +22,8 @@ (ns clojure.java.test-jdbc (:use clojure.test) - (:require [clojure.java.jdbc :as sql])) + (:require [clojure.java.jdbc :as sql] + [clojure.java.jdbc.sql :as dsl])) ;; Set test-databases according to whether you have the local database available: ;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] @@ -355,3 +356,141 @@ (.getMetaData) (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] (is (= [] metadata)))))) + +(deftest empty-query + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (is (= [] (sql/query db (dsl/select * :fruit)))))) + +(deftest insert-one-row + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (is (= (condp = (:subprotocol db) + "derby" [nil] + "jtds:sqlserver" [nil] + "sqlserver" [nil] + [1]) (sql/insert! db :fruit {:name "Apple"}))))) + +(deftest insert-query + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (is (sql/insert! db :fruit {:name "Apple"})) + (is (= [{:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db (dsl/select * :fruit)))))) + +(deftest insert-two-by-map-and-query + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + (is (= (condp = (:subprotocol db) + "derby" [nil nil] + "hsqldb" [1 1] + "jtds:sqlserver" [nil nil] + "sqlserver" [nil nil] + [1 2]) new-keys)) + (is (= [{:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) + +(deftest insert-two-by-cols-and-query + (doseq [db (test-specs)] + ;; hsqldb, sqlite and sqlserver drivers do not support multi-row inserts in a single statement + (when (not (#{"hsqldb" "sqlite" "sqlserver" "jtds:sqlserver"} (:subprotocol db))) + (sql/with-connection db + (create-test-table :fruit db)) + (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) + rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + (is (= [2] update-counts)) + (is (= [{:id (condp = (:subprotocol db) + "derby" 0 + 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (condp = (:subprotocol db) + "derby" 0 + 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows)))))) + +(deftest insert-update-and-query + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (let [new-key (sql/insert! db :fruit {:name "Apple"}) + update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} + (dsl/where {:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 1)})) + rows (sql/query db (dsl/select * :fruit))] + (is (= (condp = (:subprotocol db) + "derby" [nil] + "jtds:sqlserver" [nil] + "sqlserver" [nil] + [1]) new-key)) + (is (= [1] update-result)) + (is (= [{:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 1) + :name "Apple" :appearance "Green" + :grade (condp = (:subprotocol db) + "derby" (Float. 1.2) + "jtds:sqlserver" (Float. 1.2) + "sqlserver" (Float. 1.2) + 1.2) + :cost 12}] rows))))) + +(deftest insert-delete-and-query + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (let [new-key (sql/insert! db :fruit {:name "Apple"}) + delete-result (sql/delete! db :fruit + (dsl/where {:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 1)})) + rows (sql/query db (dsl/select * :fruit))] + (is (= (condp = (:subprotocol db) + "derby" [nil] + "jtds:sqlserver" [nil] + "sqlserver" [nil] + [1]) new-key)) + (is (= [1] delete-result)) + (is (= [] rows))))) + +(deftest illegal-insert-arguments + (doseq [db (test-specs)] + (is (thrown? IllegalArgumentException (sql/insert! db))) + (is (thrown? IllegalArgumentException (sql/insert! db :entities dsl/as-is))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :entities dsl/as-is))) + (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) + (is (thrown? IllegalArgumentException (sql/insert! db [:name] :entities dsl/as-is))))) From 6c4570a8769abe20f6f307a425d06d15c4e9701b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Dec 2012 10:07:20 -0800 Subject: [PATCH 032/630] JDBC-20 Correct how multi-row insert is implemented so it is no longer MySQL-specific(!). --- src/main/clojure/clojure/java/jdbc.clj | 9 ++--- src/main/clojure/clojure/java/jdbc/sql.clj | 11 +++--- src/test/clojure/clojure/java/test_jdbc.clj | 38 +++++++++++++-------- src/test/clojure/clojure/java/test_sql.clj | 8 ++--- 4 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 50e5c33e..1cfcf556 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -904,10 +904,11 @@ generated keys are returned (as a map)." } transaction? true] (with-open [^java.sql.Connection con (get-connection db)] (if (string? (first stmts)) - (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) - transaction? - (first stmts) - (rest stmts)) + (apply db-do-prepared + (assoc db :connection con :level 0 :rollback (atom false)) + transaction? + (first stmts) + (rest stmts)) (doall (map (fn [row] (let [result (db-do-prepared-return-keys (assoc db :connection con :level 0 :rollback (atom false)) diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index e15e2317..87825774 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -99,13 +99,10 @@ and update! high-level operations within clojure.java.jdbc directly." } (throw (IllegalArgumentException. "insert called with inconsistent number of columns / values")) (into [(str "INSERT INTO " (table-str table entities) " ( " (str/join ", " (map (fn [col] (col-str col entities)) columns)) - " ) VALUES " - (str/join ", " - (repeat (count values) - (str "( " - (str/join ", " (repeat nc "?")) - " )"))))] - (apply concat values))))) + " ) VALUES ( " + (str/join ", " (repeat nc "?")) + " )")] + values)))) (defn- insert-single-row [table row entities] (let [ks (keys row)] diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 0f9aebbf..f63e28d2 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -377,7 +377,11 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (is (sql/insert! db :fruit {:name "Apple"})) + (is (= (condp = (:subprotocol db) + "derby" [nil] + "jtds:sqlserver" [nil] + "sqlserver" [nil] + [1]) (sql/insert! db :fruit {:name "Apple"}))) (is (= [{:id (condp = (:subprotocol db) "derby" 0 "hsqldb" 0 @@ -415,19 +419,25 @@ (deftest insert-two-by-cols-and-query (doseq [db (test-specs)] - ;; hsqldb, sqlite and sqlserver drivers do not support multi-row inserts in a single statement - (when (not (#{"hsqldb" "sqlite" "sqlserver" "jtds:sqlserver"} (:subprotocol db))) - (sql/with-connection db - (create-test-table :fruit db)) - (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) - rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] - (is (= [2] update-counts)) - (is (= [{:id (condp = (:subprotocol db) - "derby" 0 - 1) :name "Apple" :appearance nil :grade nil :cost nil} - {:id (condp = (:subprotocol db) - "derby" 0 - 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows)))))) + (sql/with-connection db + (create-test-table :fruit db)) + (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) + rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + (is (= [1 1] update-counts)) + (is (= [{:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) (deftest insert-update-and-query (doseq [db (test-specs)] diff --git a/src/test/clojure/clojure/java/test_sql.clj b/src/test/clojure/clojure/java/test_sql.clj index aa080ba9..6088fdd0 100644 --- a/src/test/clojure/clojure/java/test_sql.clj +++ b/src/test/clojure/clojure/java/test_sql.clj @@ -103,15 +103,15 @@ (entities (quoted \`) (delete :a (where {:b 2})))))) (deftest insert-dsl - (is (= ["INSERT INTO a ( b ) VALUES ( ? )" 2] (insert :a [:b] [2]))) + (is (= ["INSERT INTO a ( b ) VALUES ( ? )" [2]] (insert :a [:b] [2]))) (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2]] (insert :a {:b 2}))) - (is (= ["INSERT INTO a ( b ) VALUES ( ? ), ( ? )" 2 3] (insert :a [:b] [2] [3]))) - (is (= ["INSERT INTO a ( b, c, d ) VALUES ( ?, ?, ? ), ( ?, ?, ? )" 2 3 4 3 4 5] + (is (= ["INSERT INTO a ( b ) VALUES ( ? )" [2] [3]] (insert :a [:b] [2] [3]))) + (is (= ["INSERT INTO a ( b, c, d ) VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] (insert :a [:b :c :d] [2 3 4] [3 4 5]))) (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2] ["INSERT INTO a ( b ) VALUES ( ? )" 3]] (insert :a {:b 2} {:b 3}))) - (is (= ["INSERT INTO `a` ( `b` ) VALUES ( ? )" 2] + (is (= ["INSERT INTO `a` ( `b` ) VALUES ( ? )" [2]] (entities (quoted \`) (insert :a [:b] [2]))))) (deftest bad-insert-args From 6667c3ce9522e7d2301d58e62dd9ad1899ed6e9e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Dec 2012 10:18:58 -0800 Subject: [PATCH 033/630] Refactor tests to remove duplicate conditions --- src/test/clojure/clojure/java/test_jdbc.clj | 125 ++++++-------------- 1 file changed, 38 insertions(+), 87 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index f63e28d2..1c798414 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -357,6 +357,30 @@ (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] (is (= [] metadata)))))) +(defn- returned-key [db k] + (condp = (:subprotocol db) + "derby" nil + "hsqldb" 1 + "jtds:sqlserver" nil + "sqlserver" nil + k)) + +(defn- generated-key [db k] + (condp = (:subprotocol db) + "derby" 0 + "hsqldb" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + k)) + +(defn- float-or-double [db v] + (condp = (:subprotocol db) + "derby" (Float. v) + "jtds:sqlserver" (Float. v) + "sqlserver" (Float. v) + v)) + (deftest empty-query (doseq [db (test-specs)] (sql/with-connection db @@ -367,28 +391,14 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (is (= (condp = (:subprotocol db) - "derby" [nil] - "jtds:sqlserver" [nil] - "sqlserver" [nil] - [1]) (sql/insert! db :fruit {:name "Apple"}))))) + (is (= [(returned-key db 1)] (sql/insert! db :fruit {:name "Apple"}))))) (deftest insert-query (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (is (= (condp = (:subprotocol db) - "derby" [nil] - "jtds:sqlserver" [nil] - "sqlserver" [nil] - [1]) (sql/insert! db :fruit {:name "Apple"}))) - (is (= [{:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db (dsl/select * :fruit)))))) + (is (= [(returned-key db 1)] (sql/insert! db :fruit {:name "Apple"}))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db (dsl/select * :fruit)))))) (deftest insert-two-by-map-and-query (doseq [db (test-specs)] @@ -396,26 +406,9 @@ (create-test-table :fruit db)) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] - (is (= (condp = (:subprotocol db) - "derby" [nil nil] - "hsqldb" [1 1] - "jtds:sqlserver" [nil nil] - "sqlserver" [nil nil] - [1 2]) new-keys)) - (is (= [{:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 1) :name "Apple" :appearance nil :grade nil :cost nil} - {:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) + (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) (deftest insert-two-by-cols-and-query (doseq [db (test-specs)] @@ -424,20 +417,8 @@ (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] (is (= [1 1] update-counts)) - (is (= [{:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 1) :name "Apple" :appearance nil :grade nil :cost nil} - {:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) (deftest insert-update-and-query (doseq [db (test-specs)] @@ -445,33 +426,13 @@ (create-test-table :fruit db)) (let [new-key (sql/insert! db :fruit {:name "Apple"}) update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} - (dsl/where {:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 1)})) + (dsl/where {:id (generated-key db 1)})) rows (sql/query db (dsl/select * :fruit))] - (is (= (condp = (:subprotocol db) - "derby" [nil] - "jtds:sqlserver" [nil] - "sqlserver" [nil] - [1]) new-key)) + (is (= [(returned-key db 1)] new-key)) (is (= [1] update-result)) - (is (= [{:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 1) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance "Green" - :grade (condp = (:subprotocol db) - "derby" (Float. 1.2) - "jtds:sqlserver" (Float. 1.2) - "sqlserver" (Float. 1.2) - 1.2) + :grade (float-or-double db 1.2) :cost 12}] rows))))) (deftest insert-delete-and-query @@ -480,19 +441,9 @@ (create-test-table :fruit db)) (let [new-key (sql/insert! db :fruit {:name "Apple"}) delete-result (sql/delete! db :fruit - (dsl/where {:id (condp = (:subprotocol db) - "derby" 0 - "hsqldb" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - 1)})) + (dsl/where {:id (generated-key db 1)})) rows (sql/query db (dsl/select * :fruit))] - (is (= (condp = (:subprotocol db) - "derby" [nil] - "jtds:sqlserver" [nil] - "sqlserver" [nil] - [1]) new-key)) + (is (= [(returned-key db 1)] new-key)) (is (= [1] delete-result)) (is (= [] rows))))) From dbf27a1f648908a3165b6116acda9ebe2e4f7e7a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Dec 2012 11:31:43 -0800 Subject: [PATCH 034/630] Add more docstrings --- src/main/clojure/clojure/java/jdbc.clj | 51 +++++++++++++++++++++----- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1cfcf556..c1b30c79 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -875,8 +875,15 @@ generated keys are returned (as a map)." } ;; top-level API for actual SQL operations -(defn query [db sql-params & {:keys [result-set-fn row-fn identifiers] - :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] +(defn query + "Given a database connection and a vector containing SQL and optional parameters, + perform a simple database query. The optional keyword arguments specify how to + construct the result set: + :result-set-fn - applied to the entire result set, default doall + :row-fn - applied to each row as the result set is constructed, default identity + :identifiers - applied to each column name in the result set, default lower-case" + [db sql-params & {:keys [result-set-fn row-fn identifiers] + :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] (with-open [^java.sql.Connection con (get-connection db)] (db-with-query-results* (assoc db :connection con :level 0 :rollback (atom false)) @@ -885,21 +892,38 @@ generated keys are returned (as a map)." } (result-set-fn (map row-fn rs))) identifiers))) -(defn execute! [db sql-params & {:keys [transaction?] - :or {transaction? true}}] +(defn execute! + "Given a database connection and a vector containing SQL and optional parameters, + perform a general (non-select) SQL operation. The optional keyword argument specifies + whether to run the operation in a transaction or not (default true)." + [db sql-params & {:keys [transaction?] + :or {transaction? true}}] (with-open [^java.sql.Connection con (get-connection db)] (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) transaction? (first sql-params) (rest sql-params)))) -(defn delete! [db table where-map & {:keys [entities transaction?] - :or {entities sql/as-is transaction? true}}] +(defn delete! + "Given a database connection, a table name and a map of columns to match, + perform a delete. The optional keyword arguments specify how to transform + column names in the map (default 'as-is') and whether to run the delete in + a transaction (default true). + Example: + (delete! db :person {:zip 94546}) + is equivalent to: + (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" + [db table where-map & {:keys [entities transaction?] + :or {entities sql/as-is transaction? true}}] (execute! db (sql/delete table where-map :entities entities) :transaction? transaction?)) -(defn insert! [db table & maps-or-cols-and-values-etc] +(defn insert! + "Given a database connection, a table name and either maps representing rows or + a list of column names followed by lists of column values, perform an insert. + Currently the insert is always run in a transaction." + [db table & maps-or-cols-and-values-etc] (let [stmts (apply sql/insert table maps-or-cols-and-values-etc) transaction? true] (with-open [^java.sql.Connection con (get-connection db)] @@ -918,8 +942,17 @@ generated keys are returned (as a map)." } (if (map? result) (first (vals result)) result))) stmts)))))) -(defn update! [db table set-map where-map & {:keys [entities transaction?] - :or {entities sql/as-is transaction? true}}] +(defn update! + "Given a database connection, a table name, a map of column values to set and a + map of column values to match, perform an update. The optional keyword arguments + specify how column names (in the set / match maps) should be transformed (default + 'as-is') and whether to run the update in a transaction (default true). + Example: + (delete! db :person {:zip 94540} {:zip 94546}) + is equivalent to: + (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" + [db table set-map where-map & {:keys [entities transaction?] + :or {entities sql/as-is transaction? true}}] (execute! db (sql/update table set-map where-map :entities entities) :transaction? transaction?)) \ No newline at end of file From c4e154f45cb785d05c851ce9f757b84fe4c2cff2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Dec 2012 13:39:40 -0800 Subject: [PATCH 035/630] More docstring updates. --- src/main/clojure/clojure/java/jdbc.clj | 18 ++-- src/main/clojure/clojure/java/jdbc/sql.clj | 106 +++++++++++++++++---- 2 files changed, 98 insertions(+), 26 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c1b30c79..b0d71c36 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -905,7 +905,7 @@ generated keys are returned (as a map)." } (rest sql-params)))) (defn delete! - "Given a database connection, a table name and a map of columns to match, + "Given a database connection, a table name and a where clause of columns to match, perform a delete. The optional keyword arguments specify how to transform column names in the map (default 'as-is') and whether to run the delete in a transaction (default true). @@ -913,10 +913,10 @@ generated keys are returned (as a map)." } (delete! db :person {:zip 94546}) is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" - [db table where-map & {:keys [entities transaction?] - :or {entities sql/as-is transaction? true}}] + [db table where-clause & {:keys [entities transaction?] + :or {entities sql/as-is transaction? true}}] (execute! db - (sql/delete table where-map :entities entities) + (sql/delete table where-clause :entities entities) :transaction? transaction?)) (defn insert! @@ -944,15 +944,15 @@ generated keys are returned (as a map)." } (defn update! "Given a database connection, a table name, a map of column values to set and a - map of column values to match, perform an update. The optional keyword arguments + where clause of columns to match, perform an update. The optional keyword arguments specify how column names (in the set / match maps) should be transformed (default 'as-is') and whether to run the update in a transaction (default true). Example: - (delete! db :person {:zip 94540} {:zip 94546}) + (delete! db :person {:zip 94540} (where {:zip 94546})) is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" - [db table set-map where-map & {:keys [entities transaction?] - :or {entities sql/as-is transaction? true}}] + [db table set-map where-clause & {:keys [entities transaction?] + :or {entities sql/as-is transaction? true}}] (execute! db - (sql/update table set-map where-map :entities entities) + (sql/update table set-map where-clause :entities entities) :transaction? transaction?)) \ No newline at end of file diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 87825774..6a597a14 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -63,28 +63,42 @@ and update! high-level operations within clojure.java.jdbc directly." } (str (first q) x (last q)) (str q x q))) -(defn- col-str [col entities] +(defn- col-str + "Transform a column spec to an entity name for SQL. The column spec may be a + string, a keyword or a map with a single pair - column name and alias." + [col entities] (if (map? col) (let [[k v] (first col)] (str (as-identifier k entities) " AS " (as-identifier v entities))) (as-identifier col entities))) -(defn- table-str [table entities] +(defn- table-str + "Transform a table spec to an entity name for SQL. The table spec may be a + string, a keyword or a map with a single pair - table name and alias." + [table entities] (if (map? table) (let [[k v] (first table)] (str (as-identifier k entities) " " (as-identifier v entities))) (as-identifier table entities))) -(def ^{:private true} entity-symbols +(def ^{:private true + :doc "Symbols that need to be processed for entities within their forms."} + entity-symbols #{"delete" "delete!" "insert" "insert!" "select" "join" "where" "order-by" "update" "update!"}) -(def ^{:private true} identifier-symbols +(def ^{:private true + :doc "Symbols that need to be processed for identifiers within their forms."} + identifier-symbols #{"query"}) -(defn- order-direction [col entities] +(defn- order-direction + "Transform a column order spec to an order by entity for SQL. The order spec may be a + string, a keyword or a map with a single pair - column name and direction. If the order + spec is not a map, the default direction is ascending." + [col entities] (if (map? col) (str (as-identifier (first (keys col)) entities) " " @@ -92,7 +106,11 @@ and update! high-level operations within clojure.java.jdbc directly." } (get {:asc "ASC" :desc "DESC"} dir dir))) (str (as-identifier col entities) " ASC"))) -(defn- insert-multi-row [table columns values entities] +(defn- insert-multi-row + "Given a table and a list of columns, followed by a list of column value sequences, + return a vector of the SQL needed for the insert followed by the list of column + value sequences. The entities function specifies how column names are transformed." + [table columns values entities] (let [nc (count columns) vcs (map count values)] (if (not (apply = nc vcs)) @@ -104,7 +122,11 @@ and update! high-level operations within clojure.java.jdbc directly." } " )")] values)))) -(defn- insert-single-row [table row entities] +(defn- insert-single-row + "Given a table and a map representing a row, return a vector of the SQL needed for + the insert followed by the list of column values. The entities function specifies + how column names are transformed." + [table row entities] (let [ks (keys row)] (into [(str "INSERT INTO " (table-str table entities) " ( " (str/join ", " (map (fn [col] (col-str col entities)) ks)) @@ -115,7 +137,11 @@ and update! high-level operations within clojure.java.jdbc directly." } ;; quoting strategy helpers -(defmacro entities [entities sql] +(defmacro entities + "Given an entities function and a SQL-generating DSL form, transform the DSL form + to inject an :entities keyword argument with the function at the end of each appropriate + form." + [entities sql] (walk/postwalk (fn [form] (if (and (seq? form) (symbol? (first form)) @@ -123,7 +149,11 @@ and update! high-level operations within clojure.java.jdbc directly." } (concat form [:entities entities]) form)) sql)) -(defmacro identifiers [identifiers sql] +(defmacro identifiers + "Given an identifiers function and a SQL-generating DSL form, transform the DSL form + to inject an :identifiers keyword argument with the function at the end of each + appropriate form." + [identifiers sql] (walk/postwalk (fn [form] (if (and (seq? form) (symbol? (first form)) @@ -139,12 +169,20 @@ and update! high-level operations within clojure.java.jdbc directly." } ;; SQL generation functions -(defn delete [table [where & params] & {:keys [entities] :or {entities as-is}}] +(defn delete + "Given a table name, a where class and its parameters and an optional entities spec, + return a vector of the SQL for that delete operation followed by its parameters. The + entities spec (default 'as-is') specifies how to transform column names." + [table [where & params] & {:keys [entities] :or {entities as-is}}] (into [(str "DELETE FROM " (table-str table entities) (when where " WHERE ") where)] params)) -(defn insert [table & clauses] +(defn insert + "Given a table name and either column names and values or maps representing rows, retun + return a vector of the SQL for that insert operation followed by its parameters. An + optional entities spec (default 'as-is') specifies how to transform column names." + [table & clauses] (let [rows (take-while map? clauses) n-rows (count rows) cols-and-vals-etc (drop n-rows clauses) @@ -163,19 +201,40 @@ and update! high-level operations within clojure.java.jdbc directly." } (map (fn [row] (insert-single-row table row entities)) rows) (throw (IllegalArgumentException. "insert may take records or columns and values, not both")))))) -(defn join [table on-map & {:keys [entities] :or {entities as-is}}] +(defn join + "Given a table name and a map of how to join it (to the existing SQL fragment), + retun the SQL string for the JOIN clause. The optional entities spec (default 'as-is') + specifies how to transform column names." + [table on-map & {:keys [entities] :or {entities as-is}}] (str "JOIN " (table-str table entities) " ON " (str/join " AND " (map (fn [[k v]] (str (as-identifier k entities) " = " (as-identifier v entities))) on-map)))) -(defn order-by [cols & {:keys [entities] :or {entities as-is}}] +(defn order-by + "Given a sequence of column order specs, and an optional entities spec, return the + SQL string for the ORDER BY clause. A column order spec may be a column name or a + map of the column name to the desired order." + [cols & {:keys [entities] :or {entities as-is}}] (str "ORDER BY " (if (or (string? cols) (keyword? cols) (map? cols)) (order-direction cols entities) (str/join "," (map #(order-direction % entities) cols))))) -(defn select [col-seq table & clauses] +(defn select + "Given a sequence of column names (or *) and a table name, followed by optional SQL + clauses, return a vector for the SQL followed by its parameters. The general form is: + (select [columns] table joins [where params] order-by options) + where joins are optional strings, as is order-by, and the where clause is a vector + of a where SQL clause followed by its parameters. The options may may include an + entities spec to specify how column names should be transformed. + The intent is that the joins, where clause and order by clause are generated by + other parts of the DSL: + (select * {:person :p} + (join {:address :a} {:p.addressId :a.id}) + (where {:a.zip 94546}) + (order-by :p.name))" + [col-seq table & clauses] (let [joins (take-while string? clauses) where-etc (drop (count joins) clauses) [where-clause & more] where-etc @@ -184,7 +243,7 @@ and update! high-level operations within clojure.java.jdbc directly." } [order-clause & more] order-etc order-by (when (string? order-clause) order-clause) options (if order-by more order-etc) - {:keys [entities] :or {entities as-is}} (apply hash-map options)] + {:keys [entities] :or {entities as-is}} (apply hash-map options)] (cons (str "SELECT " (cond (= * col-seq) "*" @@ -200,7 +259,14 @@ and update! high-level operations within clojure.java.jdbc directly." } order-by) params))) -(defn update [table set-map & where-etc] +(defn update + "Given a table name and a map of columns to set, and optional map of columns to + match (and an optional entities spec), return a vector of the SQL for that update + followed by its parameters. Example: + (update :person {:zip 94540} (where {:zip 94546})) + returns: + [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" + [table set-map & where-etc] (let [[where-clause & options] (when-not (keyword? (first where-etc)) where-etc) [where & params] where-clause {:keys [entities] :or {entities as-is}} (if (keyword? (first where-etc)) where-etc options) @@ -218,7 +284,13 @@ and update! high-level operations within clojure.java.jdbc directly." } where) (concat (remove nil? vs) params)))) -(defn where [param-map & {:keys [entities] :or {entities as-is}}] +(defn where + "Given a map of columns and values, return a vector containing the where clause SQL + followed by its parameters. Example: + (where {:a 42 :b nil}) + returns: + [\"a = ? AND b IS NULL\" 42]" + [param-map & {:keys [entities] :or {entities as-is}}] (let [ks (keys param-map) vs (vals param-map)] (cons (str/join From b7693847c21ffbf864e216d84927d585f1038245 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Dec 2012 14:09:58 -0800 Subject: [PATCH 036/630] Fix JDBC-44 by adding db-do-commands. Also fixes JDBC-38. --- src/main/clojure/clojure/java/jdbc.clj | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b0d71c36..7b9aa9a9 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -786,6 +786,22 @@ generated keys are returned (as a map)." } (catch Exception e (throw-non-rte e)))))) +(defn db-do-commands + "Executes SQL commands on the specified database connection. Wraps the commands + in a transaction if transaction? is true." + [db transaction? & commands] + (with-open [^Statement stmt (let [^java.sql.Connection con (db-connection db)] (.createStatement con))] + (doseq [^String cmd commands] + (.addBatch stmt cmd)) + (letfn [(execute-batch* [_] + (execute-batch stmt))] + (if transaction? + (db-transaction* db execute-batch*) + (try + (execute-batch*) + (catch Exception e + (throw-non-rte e))))))) + (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the open database connection. The param-group is a seq of values for all of From b097aa1c25e257b1d96e9c41a81d87d86b72d3e2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Dec 2012 18:22:37 -0800 Subject: [PATCH 037/630] Initial code reorganization for JDBC-43 --- src/main/clojure/clojure/java/jdbc.clj | 705 +++++++++++++------------ 1 file changed, 354 insertions(+), 351 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7b9aa9a9..b90a9f0c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -118,17 +118,6 @@ generated keys are returned (as a map)." } (def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols {"postgres" "postgresql"}) -(defn find-connection - "Returns the current database connection (or nil if there is none)" - ^java.sql.Connection [] - (:connection *db*)) - -(defn connection - "Returns the current database connection (or throws if there is none)" - ^java.sql.Connection [] - (or (find-connection) - (throw (Exception. "no current database connection")))) - (defn- parse-properties-uri [^URI uri] (let [host (.getHost uri) port (if (pos? (.getPort uri)) (.getPort uri)) @@ -295,121 +284,6 @@ generated keys are returned (as a map)." } [q & body ] `(binding [*as-str* (partial as-quoted-str ~q)] ~@body)) -(defn with-connection* - "Evaluates func in the context of a new connection to a database then - closes the connection." - [db-spec func] - (with-open [^java.sql.Connection con (get-connection db-spec)] - (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] - (func)))) - -(defmacro with-connection - "Evaluates body in the context of a new connection to a database then - closes the connection. db-spec is a map containing values for one of the - following parameter sets: - - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DriverManager: - :subprotocol (required) a String, the jdbc subprotocol - :subname (required) a String, the jdbc subname - :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties. - - DataSource: - :datasource (required) a javax.sql.DataSource - :username (optional) a String - :password (optional) a String, required if :username is supplied - - JNDI: - :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map - - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - - URI: - Parsed JDBC connection string - see below - - String: - subprotocol://user:password@host:post/subname - An optional prefix of jdbc: is allowed." - [db-spec & body] - `(with-connection* ~db-spec (fn [] ~@body))) - -(defn- rollback - "Accessor for the rollback flag on the current connection" - ([] - (deref (:rollback *db*))) - ([val] - (swap! (:rollback *db*) (fn [_] val)))) - -(defn transaction* - "Evaluates func as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If rollback is set within scope of the outermost transaction, - the entire transaction will be rolled back rather than committed when - complete." - [func] - (binding [*db* (update-in *db* [:level] inc)] - ;; This ugliness makes it easier to catch SQLException objects - ;; rather than something wrapped in a RuntimeException which - ;; can really obscure your code when working with JDBC from - ;; Clojure... :( - (letfn [(throw-non-rte [^Throwable ex] - (cond (instance? java.sql.SQLException ex) (throw ex) - (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) - :else (throw ex)))] - (if (= (:level *db*) 1) - (let [^java.sql.Connection con (connection) - auto-commit (.getAutoCommit con)] - (io! - (.setAutoCommit con false) - (try - (let [result (func)] - (if (rollback) - (.rollback con) - (.commit con)) - result) - (catch Exception e - (.rollback con) - (throw-non-rte e)) - (finally - (rollback false) - (.setAutoCommit con auto-commit))))) - (try - (func) - (catch Exception e - (throw-non-rte e))))))) - -(defmacro transaction - "Evaluates body as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If set-rollback-only is called within scope of the outermost - transaction, the entire transaction will be rolled back rather than - committed when complete." - [& body] - `(transaction* (fn [] ~@body))) - -(defn set-rollback-only - "Marks the outermost transaction such that it will rollback rather than - commit when complete" - [] - (rollback true)) - -(defn is-rollback-only - "Returns true if the outermost transaction will rollback rather than - commit when complete" - [] - (rollback)) - (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. (-2) indicates a single operation operating on an unknown number of rows. @@ -422,15 +296,6 @@ generated keys are returned (as a map)." } (list (.getUpdateCount stmt)) (seq result)))) -(defn do-commands - "Executes SQL commands on the open database connection." - [& commands] - (with-open [^Statement stmt (let [^java.sql.Connection con (connection)] (.createStatement con))] - (doseq [^String cmd commands] - (.addBatch stmt cmd)) - (transaction - (execute-batch stmt)))) - (def ^{:private true :doc "Map friendly :concurrency values to ResultSet constants."} result-set-concurrency @@ -487,21 +352,6 @@ generated keys are returned (as a map)." } (.setObject stmt (inc ix) value)) params))) -(defn do-prepared - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. Each param-group is a seq of values for all of - the parameters. - Return a seq of update counts (one count for each param-group)." - [sql & param-groups] - (with-open [^PreparedStatement stmt (prepare-statement (connection) sql)] - (if (empty? param-groups) - (transaction* (fn [] (vector (.executeUpdate stmt)))) - (do - (doseq [param-group param-groups] - (set-parameters stmt param-group) - (.addBatch stmt)) - (transaction* (fn [] (execute-batch stmt))))))) - (defn create-table-ddl "Given a table name and column specs with an optional table-spec return the DDL string for creating a table based on that." @@ -521,210 +371,45 @@ generated keys are returned (as a map)." } (specs-to-string col-specs) table-spec-str))) -(defn create-table - "Creates a table on the open database connection given a table name and - specs. Each spec is either a column spec: a vector containing a column - name and optionally a type and other constraints, or a table-level - constraint: a vector containing words that express the constraint. An - optional suffix to the CREATE TABLE DDL describing table attributes may - by provided as :table-spec {table-attributes-string}. All words used to - describe the table may be supplied as strings or keywords." - [name & specs] - (do-commands (apply create-table-ddl name specs))) - -(defn drop-table - "Drops a table on the open database connection given its name, a string - or keyword" - [name] - (do-commands - (format "DROP TABLE %s" (as-identifier name)))) +(defn print-sql-exception + "Prints the contents of an SQLException to *out*" + [^SQLException exception] + (let [^Class exception-class (class exception)] + (println + (format (str "%s:" \newline + " Message: %s" \newline + " SQLState: %s" \newline + " Error Code: %d") + (.getSimpleName exception-class) + (.getMessage exception) + (.getSQLState exception) + (.getErrorCode exception))))) -(defn do-prepared-return-keys - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. The param-group is a seq of values for all of - the parameters. - Return the generated keys for the (single) update/insert." - [sql param-group] - (with-open [^PreparedStatement stmt (prepare-statement (connection) sql :return-keys true)] - (set-parameters stmt param-group) - (transaction* (fn [] (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (resultset-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))))) +(defn print-sql-exception-chain + "Prints a chain of SQLExceptions to *out*" + [^SQLException exception] + (loop [e exception] + (when e + (print-sql-exception e) + (recur (.getNextException e))))) -(defn insert-values - "Inserts rows into a table with values for specified columns only. - column-names is a vector of strings or keywords identifying columns. Each - value-group is a vector containing a values for each column in - order. When inserting complete rows (all columns), consider using - insert-rows instead. - If a single set of values is inserted, returns a map of the generated keys." - [table column-names & value-groups] - (let [column-strs (map as-identifier column-names) - n (count (first value-groups)) - return-keys (= 1 (count value-groups)) - prepared-statement (if return-keys do-prepared-return-keys do-prepared) - template (apply str (interpose "," (repeat n "?"))) - columns (if (seq column-names) - (format "(%s)" (apply str (interpose "," column-strs))) - "")] - (apply prepared-statement - (format "INSERT INTO %s %s VALUES (%s)" - (as-identifier table) columns template) - value-groups))) +(def ^{:private true} special-counts + {Statement/EXECUTE_FAILED "EXECUTE_FAILED" + Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) -(defn insert-rows - "Inserts complete rows into a table. Each row is a vector of values for - each of the table's columns in order. - If a single row is inserted, returns a map of the generated keys." - [table & rows] - (apply insert-values table nil rows)) +(defn print-update-counts + "Prints the update counts from a BatchUpdateException to *out*" + [^BatchUpdateException exception] + (println "Update counts:") + (dorun + (map-indexed + (fn [index count] + (println (format " Statement %d: %s" + index + (get special-counts count count)))) + (.getUpdateCounts exception)))) -(defn insert-records - "Inserts records into a table. records are maps from strings or keywords - (identifying columns) to values. Inserts the records one at a time. - Returns a sequence of maps containing the generated keys for each record." - [table & records] - (let [ins-v (fn [record] (insert-values table (keys record) (vals record)))] - (doall (map ins-v records)))) - -(defn insert-record - "Inserts a single record into a table. A record is a map from strings or - keywords (identifying columns) to values. - Returns a map of the generated keys." - [table record] - (let [keys (insert-records table record)] - (first keys))) - -(defn delete-rows - "Deletes rows from a table. where-params is a vector containing a string - providing the (optionally parameterized) selection criteria followed by - values for any parameters." - [table where-params] - (let [[where & params] where-params] - (do-prepared - (format "DELETE FROM %s WHERE %s" - (as-identifier table) where) - params))) - -(defn update-values - "Updates values on selected rows in a table. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." - [table where-params record] - (let [[where & params] where-params - column-strs (map as-identifier (keys record)) - columns (apply str (concat (interpose "=?, " column-strs) "=?"))] - (do-prepared - (format "UPDATE %s SET %s WHERE %s" - (as-identifier table) columns where) - (concat (vals record) params)))) - -(defn update-or-insert-values - "Updates values on selected rows in a table, or inserts a new row when no - existing row matches the selection criteria. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." - [table where-params record] - (transaction - (let [result (update-values table where-params record)] - (if (zero? (first result)) - (insert-values table (keys record) (vals record)) - result)))) - -(defn with-query-results* - "Executes a query, then evaluates func passing in a seq of the results as - an argument. The first argument is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs - See prepare-statement for supported options." - [sql-params func] - (when-not (vector? sql-params) - (let [^Class sql-params-class (class sql-params) - ^String msg (format "\"%s\" expected %s %s, found %s %s" - "sql-params" - "vector" - "[sql param*]" - (.getName sql-params-class) - (pr-str sql-params))] - (throw (IllegalArgumentException. msg)))) - (let [special (first sql-params) - sql-is-first (string? special) - options-are-first (map? special) - sql (cond sql-is-first special - options-are-first (second sql-params)) - params (vec (cond sql-is-first (rest sql-params) - options-are-first (rest (rest sql-params)) - :else (rest sql-params))) - prepare-args (when (map? special) (flatten (seq special)))] - (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (connection) sql prepare-args))] - (set-parameters stmt params) - (with-open [rset (.executeQuery stmt)] - (func (resultset-seq rset)))))) - -(defmacro with-query-results - "Executes a query, then evaluates body with results bound to a seq of the - results. sql-params is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs - See prepare-statement for supported options." - [results sql-params & body] - `(with-query-results* ~sql-params (fn [~results] ~@body))) - -(defn print-sql-exception - "Prints the contents of an SQLException to *out*" - [^SQLException exception] - (let [^Class exception-class (class exception)] - (println - (format (str "%s:" \newline - " Message: %s" \newline - " SQLState: %s" \newline - " Error Code: %d") - (.getSimpleName exception-class) - (.getMessage exception) - (.getSQLState exception) - (.getErrorCode exception))))) - -(defn print-sql-exception-chain - "Prints a chain of SQLExceptions to *out*" - [^SQLException exception] - (loop [e exception] - (when e - (print-sql-exception e) - (recur (.getNextException e))))) - -(def ^{:private true} special-counts - {Statement/EXECUTE_FAILED "EXECUTE_FAILED" - Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) - -(defn print-update-counts - "Prints the update counts from a BatchUpdateException to *out*" - [^BatchUpdateException exception] - (println "Update counts:") - (dorun - (map-indexed - (fn [index count] - (println (format " Statement %d: %s" - index - (get special-counts count count)))) - (.getUpdateCounts exception)))) - -;; java.jdbc pieces rewritten to not use dynamic bindings +;; java.jdbc pieces rewritten to not use dynamic bindings (defn db-find-connection "Returns the current database connection (or nil if there is none)" @@ -971,4 +656,322 @@ generated keys are returned (as a map)." } :or {entities sql/as-is transaction? true}}] (execute! db (sql/update table set-map where-clause :entities entities) - :transaction? transaction?)) \ No newline at end of file + :transaction? transaction?)) + +;; original API being relocated in preparation for rewriting it in +;; terms of new API primarily without dynamic binding + +(defn find-connection + "Returns the current database connection (or nil if there is none)" + ^java.sql.Connection [] + (:connection *db*)) + +(defn connection + "Returns the current database connection (or throws if there is none)" + ^java.sql.Connection [] + (or (find-connection) + (throw (Exception. "no current database connection")))) + +(defn with-connection* + "Evaluates func in the context of a new connection to a database then + closes the connection." + [db-spec func] + (with-open [^java.sql.Connection con (get-connection db-spec)] + (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] + (func)))) + +(defmacro with-connection + "Evaluates body in the context of a new connection to a database then + closes the connection. db-spec is a map containing values for one of the + following parameter sets: + + Factory: + :factory (required) a function of one argument, a map of params + (others) (optional) passed to the factory function in a map + + DriverManager: + :subprotocol (required) a String, the jdbc subprotocol + :subname (required) a String, the jdbc subname + :classname (optional) a String, the jdbc driver class name + (others) (optional) passed to the driver as properties. + + DataSource: + :datasource (required) a javax.sql.DataSource + :username (optional) a String + :password (optional) a String, required if :username is supplied + + JNDI: + :name (required) a String or javax.naming.Name + :environment (optional) a java.util.Map + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + + URI: + Parsed JDBC connection string - see below + + String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." + [db-spec & body] + `(with-connection* ~db-spec (fn [] ~@body))) + +(defn- rollback + "Accessor for the rollback flag on the current connection" + ([] + (deref (:rollback *db*))) + ([val] + (swap! (:rollback *db*) (fn [_] val)))) + +(defn transaction* + "Evaluates func as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If rollback is set within scope of the outermost transaction, + the entire transaction will be rolled back rather than committed when + complete." + [func] + (binding [*db* (update-in *db* [:level] inc)] + ;; This ugliness makes it easier to catch SQLException objects + ;; rather than something wrapped in a RuntimeException which + ;; can really obscure your code when working with JDBC from + ;; Clojure... :( + (letfn [(throw-non-rte [^Throwable ex] + (cond (instance? java.sql.SQLException ex) (throw ex) + (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) + :else (throw ex)))] + (if (= (:level *db*) 1) + (let [^java.sql.Connection con (connection) + auto-commit (.getAutoCommit con)] + (io! + (.setAutoCommit con false) + (try + (let [result (func)] + (if (rollback) + (.rollback con) + (.commit con)) + result) + (catch Exception e + (.rollback con) + (throw-non-rte e)) + (finally + (rollback false) + (.setAutoCommit con auto-commit))))) + (try + (func) + (catch Exception e + (throw-non-rte e))))))) + +(defmacro transaction + "Evaluates body as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If set-rollback-only is called within scope of the outermost + transaction, the entire transaction will be rolled back rather than + committed when complete." + [& body] + `(transaction* (fn [] ~@body))) + +(defn set-rollback-only + "Marks the outermost transaction such that it will rollback rather than + commit when complete" + [] + (rollback true)) + +(defn is-rollback-only + "Returns true if the outermost transaction will rollback rather than + commit when complete" + [] + (rollback)) + +(defn do-commands + "Executes SQL commands on the open database connection." + [& commands] + (with-open [^Statement stmt (let [^java.sql.Connection con (connection)] (.createStatement con))] + (doseq [^String cmd commands] + (.addBatch stmt cmd)) + (transaction + (execute-batch stmt)))) + +(defn do-prepared + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. Each param-group is a seq of values for all of + the parameters. + Return a seq of update counts (one count for each param-group)." + [sql & param-groups] + (with-open [^PreparedStatement stmt (prepare-statement (connection) sql)] + (if (empty? param-groups) + (transaction* (fn [] (vector (.executeUpdate stmt)))) + (do + (doseq [param-group param-groups] + (set-parameters stmt param-group) + (.addBatch stmt)) + (transaction* (fn [] (execute-batch stmt))))))) + +(defn create-table + "Creates a table on the open database connection given a table name and + specs. Each spec is either a column spec: a vector containing a column + name and optionally a type and other constraints, or a table-level + constraint: a vector containing words that express the constraint. An + optional suffix to the CREATE TABLE DDL describing table attributes may + by provided as :table-spec {table-attributes-string}. All words used to + describe the table may be supplied as strings or keywords." + [name & specs] + (do-commands (apply create-table-ddl name specs))) + +(defn drop-table + "Drops a table on the open database connection given its name, a string + or keyword" + [name] + (do-commands + (format "DROP TABLE %s" (as-identifier name)))) + +(defn do-prepared-return-keys + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. The param-group is a seq of values for all of + the parameters. + Return the generated keys for the (single) update/insert." + [sql param-group] + (with-open [^PreparedStatement stmt (prepare-statement (connection) sql :return-keys true)] + (set-parameters stmt param-group) + (transaction* (fn [] (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (resultset-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))))) + +(defn insert-values + "Inserts rows into a table with values for specified columns only. + column-names is a vector of strings or keywords identifying columns. Each + value-group is a vector containing a values for each column in + order. When inserting complete rows (all columns), consider using + insert-rows instead. + If a single set of values is inserted, returns a map of the generated keys." + [table column-names & value-groups] + (let [column-strs (map as-identifier column-names) + n (count (first value-groups)) + return-keys (= 1 (count value-groups)) + prepared-statement (if return-keys do-prepared-return-keys do-prepared) + template (apply str (interpose "," (repeat n "?"))) + columns (if (seq column-names) + (format "(%s)" (apply str (interpose "," column-strs))) + "")] + (apply prepared-statement + (format "INSERT INTO %s %s VALUES (%s)" + (as-identifier table) columns template) + value-groups))) + +(defn insert-rows + "Inserts complete rows into a table. Each row is a vector of values for + each of the table's columns in order. + If a single row is inserted, returns a map of the generated keys." + [table & rows] + (apply insert-values table nil rows)) + +(defn insert-records + "Inserts records into a table. records are maps from strings or keywords + (identifying columns) to values. Inserts the records one at a time. + Returns a sequence of maps containing the generated keys for each record." + [table & records] + (let [ins-v (fn [record] (insert-values table (keys record) (vals record)))] + (doall (map ins-v records)))) + +(defn insert-record + "Inserts a single record into a table. A record is a map from strings or + keywords (identifying columns) to values. + Returns a map of the generated keys." + [table record] + (let [keys (insert-records table record)] + (first keys))) + +(defn delete-rows + "Deletes rows from a table. where-params is a vector containing a string + providing the (optionally parameterized) selection criteria followed by + values for any parameters." + [table where-params] + (let [[where & params] where-params] + (do-prepared + (format "DELETE FROM %s WHERE %s" + (as-identifier table) where) + params))) + +(defn update-values + "Updates values on selected rows in a table. where-params is a vector + containing a string providing the (optionally parameterized) selection + criteria followed by values for any parameters. record is a map from + strings or keywords (identifying columns) to updated values." + [table where-params record] + (let [[where & params] where-params + column-strs (map as-identifier (keys record)) + columns (apply str (concat (interpose "=?, " column-strs) "=?"))] + (do-prepared + (format "UPDATE %s SET %s WHERE %s" + (as-identifier table) columns where) + (concat (vals record) params)))) + +(defn update-or-insert-values + "Updates values on selected rows in a table, or inserts a new row when no + existing row matches the selection criteria. where-params is a vector + containing a string providing the (optionally parameterized) selection + criteria followed by values for any parameters. record is a map from + strings or keywords (identifying columns) to updated values." + [table where-params record] + (transaction + (let [result (update-values table where-params record)] + (if (zero? (first result)) + (insert-values table (keys record) (vals record)) + result)))) + +(defn with-query-results* + "Executes a query, then evaluates func passing in a seq of the results as + an argument. The first argument is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + [sql-params func] + (when-not (vector? sql-params) + (let [^Class sql-params-class (class sql-params) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-params-class) + (pr-str sql-params))] + (throw (IllegalArgumentException. msg)))) + (let [special (first sql-params) + sql-is-first (string? special) + options-are-first (map? special) + sql (cond sql-is-first special + options-are-first (second sql-params)) + params (vec (cond sql-is-first (rest sql-params) + options-are-first (rest (rest sql-params)) + :else (rest sql-params))) + prepare-args (when (map? special) (flatten (seq special)))] + (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (connection) sql prepare-args))] + (set-parameters stmt params) + (with-open [rset (.executeQuery stmt)] + (func (resultset-seq rset)))))) + +(defmacro with-query-results + "Executes a query, then evaluates body with results bound to a seq of the + results. sql-params is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + [results sql-params & body] + `(with-query-results* ~sql-params (fn [~results] ~@body))) From ae74b23f7e8c40f32d089ebb91772156a38ade61 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 16:56:02 -0800 Subject: [PATCH 038/630] Document get-connection fully, make it public and clean it up JDBC-43 --- src/main/clojure/clojure/java/jdbc.clj | 113 +++++++++++++++++-------- 1 file changed, 76 insertions(+), 37 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b90a9f0c..5baf4a69 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -137,50 +137,89 @@ generated keys are returned (as a map)." } (.substring spec 5) spec)) -(defn- get-connection +(defn get-connection "Creates a connection to a database. db-spec is a map containing connection - parameters - see with-connection for full details." - [{:keys [factory + parameters. db-spec is a map containing values for one of the following + parameter sets: + + Existing Connection: + :connection (required) an existing open connection that can be used + but cannot be closed (only the parent connection can be closed) + + Factory: + :factory (required) a function of one argument, a map of params + (others) (optional) passed to the factory function in a map + + DriverManager: + :subprotocol (required) a String, the jdbc subprotocol + :subname (required) a String, the jdbc subname + :classname (optional) a String, the jdbc driver class name + (others) (optional) passed to the driver as properties. + + DataSource: + :datasource (required) a javax.sql.DataSource + :username (optional) a String + :password (optional) a String, required if :username is supplied + + JNDI: + :name (required) a String or javax.naming.Name + :environment (optional) a java.util.Map + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + + URI: + Parsed JDBC connection string - see below + + String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." + [{:keys [connection + factory connection-uri classname subprotocol subname datasource username password name environment] :as db-spec}] (cond - (instance? URI db-spec) - (get-connection (parse-properties-uri db-spec)) - - (string? db-spec) - (get-connection (URI. (strip-jdbc db-spec))) - - factory - (factory (dissoc db-spec :factory)) - - connection-uri - (DriverManager/getConnection connection-uri) - - (and subprotocol subname) - (let [url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname) - classname (or classname (classnames subprotocol))] - (clojure.lang.RT/loadClassForName classname) - (DriverManager/getConnection url (as-properties etc))) - - (and datasource username password) - (.getConnection ^DataSource datasource ^String username ^String password) - - datasource - (.getConnection ^DataSource datasource) - - name - (let [env (and environment (Hashtable. ^Map environment)) - context (InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (.getConnection datasource)) - - :else - (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] - (throw (IllegalArgumentException. msg))))) + connection + connection + + (instance? URI db-spec) + (get-connection (parse-properties-uri db-spec)) + + (string? db-spec) + (get-connection (URI. (strip-jdbc db-spec))) + + factory + (factory (dissoc db-spec :factory)) + + connection-uri + (DriverManager/getConnection connection-uri) + + (and subprotocol subname) + (let [url (format "jdbc:%s:%s" subprotocol subname) + etc (dissoc db-spec :classname :subprotocol :subname) + classname (or classname (classnames subprotocol))] + (clojure.lang.RT/loadClassForName classname) + (DriverManager/getConnection url (as-properties etc))) + + (and datasource username password) + (.getConnection ^DataSource datasource ^String username ^String password) + + datasource + (.getConnection ^DataSource datasource) + + name + (let [env (and environment (Hashtable. ^Map environment)) + context (InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (.getConnection datasource)) + + :else + (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] + (throw (IllegalArgumentException. msg))))) (defn- make-name-unique "Given a collection of column names and a new column name, From d5bdbca8a6ffd406d1b742a4921bf36aad7cbe21 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 16:57:38 -0800 Subject: [PATCH 039/630] Standardize on get-connection and fix a number of pass thru uses of the db-spec JDBC-43 --- src/main/clojure/clojure/java/jdbc.clj | 56 +++++++++++++++++--------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5baf4a69..b7245ed8 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -469,11 +469,27 @@ generated keys are returned (as a map)." } (swap! (:rollback db) (fn [_] val)))) (defn- throw-non-rte + "This ugliness makes it easier to catch SQLException objects + rather than something wrapped in a RuntimeException which + can really obscure your code when working with JDBC from + Clojure... :(" [^Throwable ex] (cond (instance? java.sql.SQLException ex) (throw ex) (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) :else (throw ex))) +(defn db-set-rollback-only + "Marks the outermost transaction such that it will rollback rather than + commit when complete" + [db] + (db-rollback db true)) + +(defn db-is-rollback-only + "Returns true if the outermost transaction will rollback rather than + commit when complete" + [db] + (db-rollback db)) + (defn db-transaction* "Evaluates func as a transaction on the open database connection. Any nested transactions are absorbed into the outermost transaction. By @@ -484,12 +500,9 @@ generated keys are returned (as a map)." } complete." [db func] (let [nested-db (update-in db [:level] inc)] - ;; This ugliness makes it easier to catch SQLException objects - ;; rather than something wrapped in a RuntimeException which - ;; can really obscure your code when working with JDBC from - ;; Clojure... :( (if (= (:level nested-db) 1) - (let [^java.sql.Connection con (db-connection nested-db) + (let [^java.sql.Connection con (get-connection nested-db) + nested-db (assoc nested-db :connection con) auto-commit (.getAutoCommit con)] (io! (.setAutoCommit con false) @@ -514,15 +527,15 @@ generated keys are returned (as a map)." } "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true." [db transaction? & commands] - (with-open [^Statement stmt (let [^java.sql.Connection con (db-connection db)] (.createStatement con))] + (with-open [^Statement stmt (let [^java.sql.Connection con (get-connection db)] (.createStatement con))] (doseq [^String cmd commands] (.addBatch stmt cmd)) (letfn [(execute-batch* [_] (execute-batch stmt))] (if transaction? - (db-transaction* db execute-batch*) + (db-transaction* (assoc db :connection (.getConnection stmt)) execute-batch*) (try - (execute-batch*) + (execute-batch* nil) (catch Exception e (throw-non-rte e))))))) @@ -532,7 +545,7 @@ generated keys are returned (as a map)." } the parameters. Return the generated keys for the (single) update/insert." [db transaction? sql param-group] - (with-open [^PreparedStatement stmt (prepare-statement (db-connection db) sql :return-keys true)] + (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql :return-keys true)] (set-parameters stmt param-group) (letfn [(exec-and-return-keys [_] (let [counts (.executeUpdate stmt)] @@ -547,9 +560,9 @@ generated keys are returned (as a map)." } ;; assume generated keys is unsupported and return counts instead: counts))))] (if transaction? - (db-transaction* db exec-and-return-keys) + (db-transaction* (assoc db :connection (.getConnection stmt)) exec-and-return-keys) (try - (exec-and-return-keys db) + (exec-and-return-keys nil) (catch Exception e (throw-non-rte e))))))) @@ -559,10 +572,10 @@ generated keys are returned (as a map)." } the parameters. Return a seq of update counts (one count for each param-group)." [db transaction? sql & param-groups] - (with-open [^PreparedStatement stmt (prepare-statement (db-connection db) sql)] + (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql)] (if (empty? param-groups) (if transaction? - (db-transaction* db (fn [_] (vector (.executeUpdate stmt)))) + (db-transaction* (assoc db :connection (.getConnection stmt)) (fn [_] (vector (.executeUpdate stmt)))) (try (vector (.executeUpdate stmt)) (catch Exception e @@ -572,7 +585,7 @@ generated keys are returned (as a map)." } (set-parameters stmt param-group) (.addBatch stmt)) (if transaction? - (db-transaction* db (fn [_] (execute-batch stmt))) + (db-transaction* (assoc db :connection (.getConnection stmt)) (fn [_] (execute-batch stmt))) (try (execute-batch stmt) (catch Exception e @@ -608,7 +621,7 @@ generated keys are returned (as a map)." } prepare-args (when (map? special) (flatten (seq special)))] (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special - (apply prepare-statement (db-connection db) sql prepare-args))] + (apply prepare-statement (get-connection db) sql prepare-args))] (set-parameters stmt params) (with-open [rset (.executeQuery stmt)] (func (resultset-seq rset :identifiers identifiers)))))) @@ -624,13 +637,20 @@ generated keys are returned (as a map)." } :identifiers - applied to each column name in the result set, default lower-case" [db sql-params & {:keys [result-set-fn row-fn identifiers] :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] - (with-open [^java.sql.Connection con (get-connection db)] + (if-let [con (:connection db)] (db-with-query-results* - (assoc db :connection con :level 0 :rollback (atom false)) + db (vec sql-params) (fn [rs] (result-set-fn (map row-fn rs))) - identifiers))) + identifiers) + (with-open [con (get-connection db)] + (db-with-query-results* + (assoc db :connection con :level 0 :rollback (atom false)) + (vec sql-params) + (fn [rs] + (result-set-fn (map row-fn rs))) + identifiers)))) (defn execute! "Given a database connection and a vector containing SQL and optional parameters, From 9bc821dd2fdc9639c4269650517b8ec98107ef14 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 16:58:34 -0800 Subject: [PATCH 040/630] Correct nested handling of db specs and already open connections JDBC-43 --- src/main/clojure/clojure/java/jdbc.clj | 56 ++++++++++++++++++-------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b7245ed8..a271e597 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -658,11 +658,16 @@ generated keys are returned (as a map)." } whether to run the operation in a transaction or not (default true)." [db sql-params & {:keys [transaction?] :or {transaction? true}}] - (with-open [^java.sql.Connection con (get-connection db)] - (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) + (if-let [con (:connection db)] + (db-do-prepared db transaction? (first sql-params) - (rest sql-params)))) + (rest sql-params)) + (with-open [con (get-connection db)] + (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) + transaction? + (first sql-params) + (rest sql-params))))) (defn delete! "Given a database connection, a table name and a where clause of columns to match, @@ -686,21 +691,38 @@ generated keys are returned (as a map)." } [db table & maps-or-cols-and-values-etc] (let [stmts (apply sql/insert table maps-or-cols-and-values-etc) transaction? true] - (with-open [^java.sql.Connection con (get-connection db)] + (if-let [con (:connection db)] (if (string? (first stmts)) - (apply db-do-prepared - (assoc db :connection con :level 0 :rollback (atom false)) - transaction? - (first stmts) - (rest stmts)) - (doall (map (fn [row] - (let [result (db-do-prepared-return-keys - (assoc db :connection con :level 0 :rollback (atom false)) - transaction? - (first row) - (rest row))] - (if (map? result) (first (vals result)) result))) - stmts)))))) + (apply db-do-prepared + db + transaction? + (first stmts) + (rest stmts)) + (doall (map (fn [row] + (let [result (db-do-prepared-return-keys + db + ;; bad idea - this is nested + transaction? + (first row) + (rest row))] + result)) + stmts))) + (with-open [con (get-connection db)] + (if (string? (first stmts)) + (apply db-do-prepared + (assoc db :connection con :level 0 :rollback (atom false)) + transaction? + (first stmts) + (rest stmts)) + (doall (map (fn [row] + (let [result (db-do-prepared-return-keys + (assoc db :connection con :level 0 :rollback (atom false)) + ;; bad idea - this is nested + transaction? + (first row) + (rest row))] + result)) + stmts))))))) (defn update! "Given a database connection, a table name, a map of column values to set and a From 59d2081988a197571782ee76011a940effbdb2a7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 16:58:45 -0800 Subject: [PATCH 041/630] Type in docstring JDBC-43 --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a271e597..c8746e70 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -730,7 +730,7 @@ generated keys are returned (as a map)." } specify how column names (in the set / match maps) should be transformed (default 'as-is') and whether to run the update in a transaction (default true). Example: - (delete! db :person {:zip 94540} (where {:zip 94546})) + (update! db :person {:zip 94540} (where {:zip 94546})) is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" [db table set-map where-clause & {:keys [entities transaction?] From 07437b9524d67d3a7efd8b1c2d1f7304af1f18a8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 16:59:21 -0800 Subject: [PATCH 042/630] Rewrite most of old API in terms of new API JDBC-43 --- src/main/clojure/clojure/java/jdbc.clj | 370 +++++++++++-------------- 1 file changed, 162 insertions(+), 208 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c8746e70..d403e22d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -739,158 +739,114 @@ generated keys are returned (as a map)." } (sql/update table set-map where-clause :entities entities) :transaction? transaction?)) -;; original API being relocated in preparation for rewriting it in -;; terms of new API primarily without dynamic binding +;; original API mostly rewritten in terms of new API primarily without dynamic binding -(defn find-connection - "Returns the current database connection (or nil if there is none)" +(defn ^{:doc "Returns the current database connection (or nil if there is none)" + :deprecated "0.3.0"} + find-connection ^java.sql.Connection [] - (:connection *db*)) + (db-find-connection *db*)) -(defn connection - "Returns the current database connection (or throws if there is none)" +(defn ^{:doc "Returns the current database connection (or throws if there is none)" + :deprecated "0.3.0"} + connection ^java.sql.Connection [] - (or (find-connection) - (throw (Exception. "no current database connection")))) + (db-connection *db*)) -(defn with-connection* - "Evaluates func in the context of a new connection to a database then - closes the connection." +(defn ^{:doc "Evaluates func in the context of a new connection to a database then + closes the connection." + :deprecated "0.3.0"} + with-connection* [db-spec func] (with-open [^java.sql.Connection con (get-connection db-spec)] (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] (func)))) -(defmacro with-connection - "Evaluates body in the context of a new connection to a database then - closes the connection. db-spec is a map containing values for one of the - following parameter sets: - - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DriverManager: - :subprotocol (required) a String, the jdbc subprotocol - :subname (required) a String, the jdbc subname - :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties. - - DataSource: - :datasource (required) a javax.sql.DataSource - :username (optional) a String - :password (optional) a String, required if :username is supplied - - JNDI: - :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map - - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - - URI: - Parsed JDBC connection string - see below - - String: - subprotocol://user:password@host:post/subname - An optional prefix of jdbc: is allowed." +(defmacro ^{:doc "Evaluates body in the context of a new connection to a database then + closes the connection." + :deprecated "0.3.0"} + with-connection [db-spec & body] `(with-connection* ~db-spec (fn [] ~@body))) -(defn- rollback - "Accessor for the rollback flag on the current connection" - ([] - (deref (:rollback *db*))) - ([val] - (swap! (:rollback *db*) (fn [_] val)))) - (defn transaction* - "Evaluates func as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If rollback is set within scope of the outermost transaction, - the entire transaction will be rolled back rather than committed when - complete." + ^{:doc "Evaluates func as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If rollback is set within scope of the outermost transaction, + the entire transaction will be rolled back rather than committed when + complete." + :deprecated "0.3.0"} [func] (binding [*db* (update-in *db* [:level] inc)] - ;; This ugliness makes it easier to catch SQLException objects - ;; rather than something wrapped in a RuntimeException which - ;; can really obscure your code when working with JDBC from - ;; Clojure... :( - (letfn [(throw-non-rte [^Throwable ex] - (cond (instance? java.sql.SQLException ex) (throw ex) - (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) - :else (throw ex)))] - (if (= (:level *db*) 1) - (let [^java.sql.Connection con (connection) - auto-commit (.getAutoCommit con)] - (io! - (.setAutoCommit con false) - (try - (let [result (func)] - (if (rollback) - (.rollback con) - (.commit con)) - result) - (catch Exception e + (if (= (:level *db*) 1) + (let [^java.sql.Connection con (get-connection *db*) + auto-commit (.getAutoCommit con)] + (io! + (.setAutoCommit con false) + (try + (let [result (func)] + (if (db-rollback *db*) (.rollback con) - (throw-non-rte e)) - (finally - (rollback false) - (.setAutoCommit con auto-commit))))) - (try - (func) - (catch Exception e - (throw-non-rte e))))))) + (.commit con)) + result) + (catch Exception e + (.rollback con) + (throw-non-rte e)) + (finally + (db-rollback *db* false) + (.setAutoCommit con auto-commit))))) + (try + (func) + (catch Exception e + (throw-non-rte e)))))) -(defmacro transaction - "Evaluates body as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If set-rollback-only is called within scope of the outermost - transaction, the entire transaction will be rolled back rather than - committed when complete." +(defmacro + ^{:doc "Evaluates body as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If set-rollback-only is called within scope of the outermost + transaction, the entire transaction will be rolled back rather than + committed when complete." + :deprecated "0.3.0"} + transaction [& body] `(transaction* (fn [] ~@body))) -(defn set-rollback-only - "Marks the outermost transaction such that it will rollback rather than - commit when complete" +(defn + ^{:doc "Marks the outermost transaction such that it will rollback rather than + commit when complete" + :deprecated "0.3.0"} + set-rollback-only [] - (rollback true)) + (db-set-rollback-only *db*)) -(defn is-rollback-only - "Returns true if the outermost transaction will rollback rather than - commit when complete" +(defn + ^{:doc "Returns true if the outermost transaction will rollback rather than + commit when complete" + :deprecated "0.3.0"} + is-rollback-only [] - (rollback)) + (db-is-rollback-only *db*)) -(defn do-commands - "Executes SQL commands on the open database connection." +(defn + ^{:doc "Executes SQL commands on the open database connection." + :deprecated "0.3.0"} + do-commands [& commands] - (with-open [^Statement stmt (let [^java.sql.Connection con (connection)] (.createStatement con))] - (doseq [^String cmd commands] - (.addBatch stmt cmd)) - (transaction - (execute-batch stmt)))) - -(defn do-prepared - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. Each param-group is a seq of values for all of - the parameters. - Return a seq of update counts (one count for each param-group)." + (apply db-do-commands *db* true commands)) + +(defn + ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. Each param-group is a seq of values for all of + the parameters. + Return a seq of update counts (one count for each param-group)." + :deprecated "0.3.0"} + do-prepared [sql & param-groups] - (with-open [^PreparedStatement stmt (prepare-statement (connection) sql)] - (if (empty? param-groups) - (transaction* (fn [] (vector (.executeUpdate stmt)))) - (do - (doseq [param-group param-groups] - (set-parameters stmt param-group) - (.addBatch stmt)) - (transaction* (fn [] (execute-batch stmt))))))) + (apply db-do-prepared *db* true sql param-groups)) (defn create-table "Creates a table on the open database connection given a table name and @@ -900,43 +856,39 @@ generated keys are returned (as a map)." } optional suffix to the CREATE TABLE DDL describing table attributes may by provided as :table-spec {table-attributes-string}. All words used to describe the table may be supplied as strings or keywords." + ;; technically deprecated but we don't yet have a replacement [name & specs] (do-commands (apply create-table-ddl name specs))) (defn drop-table "Drops a table on the open database connection given its name, a string or keyword" + ;; technically deprecated but we don't yet have a replacement [name] (do-commands (format "DROP TABLE %s" (as-identifier name)))) -(defn do-prepared-return-keys - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. The param-group is a seq of values for all of - the parameters. - Return the generated keys for the (single) update/insert." +(defn + ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. The param-group is a seq of values for all of + the parameters. + Return the generated keys for the (single) update/insert." + :deprecated "0.3.0"} + do-prepared-return-keys [sql param-group] - (with-open [^PreparedStatement stmt (prepare-statement (connection) sql :return-keys true)] - (set-parameters stmt param-group) - (transaction* (fn [] (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (resultset-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))))) - -(defn insert-values - "Inserts rows into a table with values for specified columns only. - column-names is a vector of strings or keywords identifying columns. Each - value-group is a vector containing a values for each column in - order. When inserting complete rows (all columns), consider using - insert-rows instead. - If a single set of values is inserted, returns a map of the generated keys." + (db-do-prepared-return-keys *db* true sql param-group)) + +(defn + ^{:doc "Inserts rows into a table with values for specified columns only. + column-names is a vector of strings or keywords identifying columns. Each + value-group is a vector containing a values for each column in + order. When inserting complete rows (all columns), consider using + insert-rows instead. + If a single set of values is inserted, returns a map of the generated keys." + :deprecated "0.3.0"} + ;; technically not fully deprecated since the nil column-names case + ;; is not (yet) supported in the new API... JDBC-45 + insert-values [table column-names & value-groups] (let [column-strs (map as-identifier column-names) n (count (first value-groups)) @@ -956,48 +908,45 @@ generated keys are returned (as a map)." } each of the table's columns in order. If a single row is inserted, returns a map of the generated keys." [table & rows] + ;; will be deprecated after JDBC-45 is implemented (apply insert-values table nil rows)) -(defn insert-records - "Inserts records into a table. records are maps from strings or keywords - (identifying columns) to values. Inserts the records one at a time. - Returns a sequence of maps containing the generated keys for each record." +(defn + ^{:doc "Inserts records into a table. records are maps from strings or keywords + (identifying columns) to values. Inserts the records one at a time. + Returns a sequence of maps containing the generated keys for each record." + :deprecated "0.3.0"} + insert-records [table & records] - (let [ins-v (fn [record] (insert-values table (keys record) (vals record)))] - (doall (map ins-v records)))) - -(defn insert-record - "Inserts a single record into a table. A record is a map from strings or - keywords (identifying columns) to values. - Returns a map of the generated keys." + (apply insert! *db* table records)) + +(defn + ^{:doc "Inserts a single record into a table. A record is a map from strings or + keywords (identifying columns) to values. + Returns a map of the generated keys." + :deprecated "0.3.0"} + insert-record [table record] - (let [keys (insert-records table record)] - (first keys))) - -(defn delete-rows - "Deletes rows from a table. where-params is a vector containing a string - providing the (optionally parameterized) selection criteria followed by - values for any parameters." + (first (insert! *db* table record))) + +(defn + ^{:doc "Deletes rows from a table. where-params is a vector containing a string + providing the (optionally parameterized) selection criteria followed by + values for any parameters." + :deprecated "0.3.0"} + delete-rows [table where-params] - (let [[where & params] where-params] - (do-prepared - (format "DELETE FROM %s WHERE %s" - (as-identifier table) where) - params))) - -(defn update-values - "Updates values on selected rows in a table. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." + (delete! *db* table where-params)) + +(defn + ^{:doc "Updates values on selected rows in a table. where-params is a vector + containing a string providing the (optionally parameterized) selection + criteria followed by values for any parameters. record is a map from + strings or keywords (identifying columns) to updated values." + :deprecated "0.3.0"} + update-values [table where-params record] - (let [[where & params] where-params - column-strs (map as-identifier (keys record)) - columns (apply str (concat (interpose "=?, " column-strs) "=?"))] - (do-prepared - (format "UPDATE %s SET %s WHERE %s" - (as-identifier table) columns where) - (concat (vals record) params)))) + (update! *db* table record where-params)) (defn update-or-insert-values "Updates values on selected rows in a table, or inserts a new row when no @@ -1012,15 +961,17 @@ generated keys are returned (as a map)." } (insert-values table (keys record) (vals record)) result)))) -(defn with-query-results* - "Executes a query, then evaluates func passing in a seq of the results as - an argument. The first argument is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs - See prepare-statement for supported options." +(defn + ^{:doc "Executes a query, then evaluates func passing in a seq of the results as + an argument. The first argument is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + :deprecated "0.3.0"} + with-query-results* [sql-params func] (when-not (vector? sql-params) (let [^Class sql-params-class (class sql-params) @@ -1040,19 +991,22 @@ generated keys are returned (as a map)." } options-are-first (rest (rest sql-params)) :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special)))] - (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (connection) sql prepare-args))] + (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (get-connection *db*) sql prepare-args))] (set-parameters stmt params) (with-open [rset (.executeQuery stmt)] - (func (resultset-seq rset)))))) - -(defmacro with-query-results - "Executes a query, then evaluates body with results bound to a seq of the - results. sql-params is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs - See prepare-statement for supported options." + (binding [*db* (assoc *db* :connection (.getConnection stmt))] + (func (resultset-seq rset))))))) + +(defmacro + ^{:doc "Executes a query, then evaluates body with results bound to a seq of the + results. sql-params is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + :deprecated "0.3.0"} + with-query-results [results sql-params & body] `(with-query-results* ~sql-params (fn [~results] ~@body))) From 2c38fb53196c85973ec4397399264bfcbde4983a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 17:00:00 -0800 Subject: [PATCH 043/630] Restore full form of generated keys for compatibility with old API JDBC-43 --- src/test/clojure/clojure/java/test_jdbc.clj | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 1c798414..c4fc6d68 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -359,10 +359,12 @@ (defn- returned-key [db k] (condp = (:subprotocol db) - "derby" nil + "derby" {:1 nil} "hsqldb" 1 - "jtds:sqlserver" nil - "sqlserver" nil + "mysql" {:generated_key k} + "jtds:sqlserver" {:id nil} + "sqlserver" {:generated_keys nil} + "sqlite" {(keyword "last_insert_rowid()") k} k)) (defn- generated-key [db k] From a84e36369b272cea353444a5d0a9bac840ab47a5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 30 Dec 2012 17:41:40 -0800 Subject: [PATCH 044/630] Add initial cut of convenience macro for new db-transaction* function JDBC-20 Leftover piece missing from JDBC-20 - need to add more tests for this too. --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d403e22d..5f4b1ecf 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -523,6 +523,14 @@ generated keys are returned (as a map)." } (catch Exception e (throw-non-rte e)))))) +(defmacro db-transaction + "Evaluates body in the context of a transaction on the specified database connection. + The binding provides the dataabase connection for the transaction and the name to which + that is bound for evaluation of the body. + See db-transaction* for more details." + [binding & body] + `(db-transaction* ~(second binding) (fn [~(first binding)] ~@body))) + (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true." From 9b813a76fbe28370a26b828ac99bf55de015c179 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 6 Jan 2013 17:01:01 -0800 Subject: [PATCH 045/630] Added tests for new db-transaction etc and found and fixed bug in db-transaction regarding rollback. JDBC-42 --- src/main/clojure/clojure/java/jdbc.clj | 2 +- src/test/clojure/clojure/java/test_jdbc.clj | 69 +++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5f4b1ecf..c4802acf 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -529,7 +529,7 @@ generated keys are returned (as a map)." } that is bound for evaluation of the body. See db-transaction* for more details." [binding & body] - `(db-transaction* ~(second binding) (fn [~(first binding)] ~@body))) + `(db-transaction* (assoc ~(second binding) :level 0 :rollback (atom false)) (fn [~(first binding)] ~@body))) (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index c4fc6d68..062444c4 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -457,3 +457,72 @@ (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :entities dsl/as-is))) (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) (is (thrown? IllegalArgumentException (sql/insert! db [:name] :entities dsl/as-is))))) + +(deftest test-partial-exception-with-db + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (try + (sql/db-transaction [db db] + (sql/insert! db + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (throw (Exception. "deliberate exception"))) + (catch Exception _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) + +(deftest test-sql-exception-with-db + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (try + (sql/db-transaction [db db] + (sql/insert! db + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + ;; sqlite does not throw exception for too many items + (throw (java.sql.SQLException.))) + (catch Exception _ ;; insert! throws the exception, not JDBC + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-rollback-with-db + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (try + (sql/db-transaction [db db] + (is (not (sql/db-is-rollback-only db))) + (sql/db-set-rollback-only db) + (is (sql/db-is-rollback-only db)) + (sql/insert! db + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + (is (= 3 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))) + (catch Exception _ ;; insert! throws the exception, not JDBC + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-transactions-with-possible-generated-keys-result-set-with-db + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (try + (sql/db-transaction [db db] + (sql/db-set-rollback-only db) + (sql/insert! db + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + From d168464a9abaed4d8e9f79183a7dc4f235d3eb83 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 6 Jan 2013 17:15:11 -0800 Subject: [PATCH 046/630] Substantial clean up of transaction handling to make it easier to work with nested transactions JDBC-42 --- src/main/clojure/clojure/java/jdbc.clj | 37 +++++++++++++------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c4802acf..24a3156f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -529,7 +529,10 @@ generated keys are returned (as a map)." } that is bound for evaluation of the body. See db-transaction* for more details." [binding & body] - `(db-transaction* (assoc ~(second binding) :level 0 :rollback (atom false)) (fn [~(first binding)] ~@body))) + `(db-transaction* (let [db# ~(second binding)] + (assoc db# :level (or (:level db#) 0) :rollback (or (:rollback db#) (atom false)))) + (fn [~(first binding)] + ~@body))) (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands @@ -538,14 +541,12 @@ generated keys are returned (as a map)." } (with-open [^Statement stmt (let [^java.sql.Connection con (get-connection db)] (.createStatement con))] (doseq [^String cmd commands] (.addBatch stmt cmd)) - (letfn [(execute-batch* [_] - (execute-batch stmt))] - (if transaction? - (db-transaction* (assoc db :connection (.getConnection stmt)) execute-batch*) - (try - (execute-batch* nil) - (catch Exception e - (throw-non-rte e))))))) + (if transaction? + (db-transaction [db (assoc db :connection (.getConnection stmt))] (execute-batch stmt)) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e)))))) (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the @@ -555,7 +556,7 @@ generated keys are returned (as a map)." } [db transaction? sql param-group] (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql :return-keys true)] (set-parameters stmt param-group) - (letfn [(exec-and-return-keys [_] + (letfn [(exec-and-return-keys [] (let [counts (.executeUpdate stmt)] (try (let [rs (.getGeneratedKeys stmt) @@ -568,9 +569,9 @@ generated keys are returned (as a map)." } ;; assume generated keys is unsupported and return counts instead: counts))))] (if transaction? - (db-transaction* (assoc db :connection (.getConnection stmt)) exec-and-return-keys) + (db-transaction [db (assoc db :connection (.getConnection stmt))] (exec-and-return-keys)) (try - (exec-and-return-keys nil) + (exec-and-return-keys) (catch Exception e (throw-non-rte e))))))) @@ -583,7 +584,7 @@ generated keys are returned (as a map)." } (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql)] (if (empty? param-groups) (if transaction? - (db-transaction* (assoc db :connection (.getConnection stmt)) (fn [_] (vector (.executeUpdate stmt)))) + (db-transaction [db (assoc db :connection (.getConnection stmt))] (vector (.executeUpdate stmt))) (try (vector (.executeUpdate stmt)) (catch Exception e @@ -593,7 +594,7 @@ generated keys are returned (as a map)." } (set-parameters stmt param-group) (.addBatch stmt)) (if transaction? - (db-transaction* (assoc db :connection (.getConnection stmt)) (fn [_] (execute-batch stmt))) + (db-transaction [db (assoc db :connection (.getConnection stmt))] (execute-batch stmt)) (try (execute-batch stmt) (catch Exception e @@ -654,7 +655,7 @@ generated keys are returned (as a map)." } identifiers) (with-open [con (get-connection db)] (db-with-query-results* - (assoc db :connection con :level 0 :rollback (atom false)) + (assoc db :connection con) (vec sql-params) (fn [rs] (result-set-fn (map row-fn rs))) @@ -672,7 +673,7 @@ generated keys are returned (as a map)." } (first sql-params) (rest sql-params)) (with-open [con (get-connection db)] - (db-do-prepared (assoc db :connection con :level 0 :rollback (atom false)) + (db-do-prepared (assoc db :connection con) transaction? (first sql-params) (rest sql-params))))) @@ -718,13 +719,13 @@ generated keys are returned (as a map)." } (with-open [con (get-connection db)] (if (string? (first stmts)) (apply db-do-prepared - (assoc db :connection con :level 0 :rollback (atom false)) + (assoc db :connection con) transaction? (first stmts) (rest stmts)) (doall (map (fn [row] (let [result (db-do-prepared-return-keys - (assoc db :connection con :level 0 :rollback (atom false)) + (assoc db :connection con) ;; bad idea - this is nested transaction? (first row) From c897fb31f40d96da443bda5a6ef23164c1a09ce6 Mon Sep 17 00:00:00 2001 From: Gary Fredericks Date: Tue, 26 Feb 2013 16:43:30 -0600 Subject: [PATCH 047/630] Catch Throwable inside transaction instead of Exception This ensures that transactions roll back whether an Exception or an Error is thrown. Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 24a3156f..faefba91 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -512,9 +512,9 @@ generated keys are returned (as a map)." } (.rollback con) (.commit con)) result) - (catch Exception e + (catch Throwable t (.rollback con) - (throw-non-rte e)) + (throw-non-rte t)) (finally (db-rollback nested-db false) (.setAutoCommit con auto-commit))))) @@ -800,9 +800,9 @@ generated keys are returned (as a map)." } (.rollback con) (.commit con)) result) - (catch Exception e + (catch Throwable t (.rollback con) - (throw-non-rte e)) + (throw-non-rte t)) (finally (db-rollback *db* false) (.setAutoCommit con auto-commit))))) From d8a77c03ca353421df957874bbbef64b03661ad1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 29 Mar 2013 18:05:55 -0700 Subject: [PATCH 048/630] Correct typos. --- src/main/clojure/clojure/java/jdbc.clj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index faefba91..cabc4a8d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -302,7 +302,7 @@ generated keys are returned (as a map)." } "Given a quote pattern - either a single character or a pair of characters in a vector - and a keyword, return the keyword as a string using a simple quoting naming strategy. - Given a qote pattern and a string, return the string as-is. + Given a quote pattern and a string, return the string as-is. (as-quoted-identifier X :name) will return XnameX as a string. (as-quoted-identifier [A B] :name) will return AnameB as a string." [q x] @@ -525,7 +525,7 @@ generated keys are returned (as a map)." } (defmacro db-transaction "Evaluates body in the context of a transaction on the specified database connection. - The binding provides the dataabase connection for the transaction and the name to which + The binding provides the database connection for the transaction and the name to which that is bound for evaluation of the body. See db-transaction* for more details." [binding & body] @@ -607,7 +607,7 @@ generated keys are returned (as a map)." } [stmt & params] - a PreparedStatement, followed by any parameters it needs (the PreparedStatement already contains the SQL query) [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs + PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." [db sql-params func identifiers] (when-not (vector? sql-params) @@ -977,7 +977,7 @@ generated keys are returned (as a map)." } [stmt & params] - a PreparedStatement, followed by any parameters it needs (the PreparedStatement already contains the SQL query) [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs + PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." :deprecated "0.3.0"} with-query-results* @@ -1013,7 +1013,7 @@ generated keys are returned (as a map)." } [stmt & params] - a PreparedStatement, followed by any parameters it needs (the PreparedStatement already contains the SQL query) [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs + PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." :deprecated "0.3.0"} with-query-results From b3b0483597cd738d2bdbb72b2df0f1ad4d956517 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 13:26:50 -0700 Subject: [PATCH 049/630] Fix JDBC-50 by checkout value-groups have consistent lengths --- src/main/clojure/clojure/java/jdbc.clj | 11 +++++++---- src/test/clojure/clojure/java/test_jdbc.clj | 22 ++++++++++++++++++--- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index cabc4a8d..6fa4dff1 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -901,16 +901,19 @@ generated keys are returned (as a map)." } [table column-names & value-groups] (let [column-strs (map as-identifier column-names) n (count (first value-groups)) + ns (map count value-groups) return-keys (= 1 (count value-groups)) prepared-statement (if return-keys do-prepared-return-keys do-prepared) template (apply str (interpose "," (repeat n "?"))) columns (if (seq column-names) (format "(%s)" (apply str (interpose "," column-strs))) "")] - (apply prepared-statement - (format "INSERT INTO %s %s VALUES (%s)" - (as-identifier table) columns template) - value-groups))) + (if (apply = ns) + (apply prepared-statement + (format "INSERT INTO %s %s VALUES (%s)" + (as-identifier table) columns template) + value-groups) + (throw (IllegalArgumentException. "insert-values called with inconsistent number of columns / values"))))) (defn insert-rows "Inserts complete rows into a table. Each row is a vector of values for diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 062444c4..80a72492 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -302,8 +302,6 @@ (sql/insert-values :fruit [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] ["Apple" "strange" "whoops"]) ;; sqlite does not throw exception for too many items (throw (java.sql.SQLException.))) @@ -311,6 +309,24 @@ (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) +(deftest test-insert-values-exception + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (try + (sql/transaction + (sql/insert-values + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + ;; insert-values should complain about the mismatch + (is nil "insert-values did not throw an exception!")) + (catch IllegalArgumentException _ + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (deftest test-rollback (doseq [db (test-specs)] (sql/with-connection db @@ -325,7 +341,7 @@ [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) + ["Apple" "strange"]) (is (= 3 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))) (catch java.sql.SQLException _ (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) From c8224199109ca7e3a964489e9cf672a98215484a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 13:27:04 -0700 Subject: [PATCH 050/630] Bump version to more accurate 0.3.0-SNAPSHOT --- CHANGES.txt | 2 +- pom.xml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 4d5d541f..12ae18e5 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,4 @@ -Changes in 0.2.4-SNAPSHOT +Changes in 0.3.0-SNAPSHOT * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy diff --git a/pom.xml b/pom.xml index be67d150..4611bb2d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.2.4-SNAPSHOT + 0.3.0-SNAPSHOT ${project.artifactId} @@ -62,13 +62,13 @@ test - + From 63aeed67b3eba76a7d0a98c82ff2a99bb69c2f1c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 14:14:04 -0700 Subject: [PATCH 051/630] Update compatibility layer to explicitly use :entities based on dynamic *as-str* variable to fix JDBC-49 --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6fa4dff1..e164bb07 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -930,7 +930,7 @@ generated keys are returned (as a map)." } :deprecated "0.3.0"} insert-records [table & records] - (apply insert! *db* table records)) + (apply insert! *db* table (concat records [:entities *as-str*]))) (defn ^{:doc "Inserts a single record into a table. A record is a map from strings or @@ -939,7 +939,7 @@ generated keys are returned (as a map)." } :deprecated "0.3.0"} insert-record [table record] - (first (insert! *db* table record))) + (first (insert-records table record))) (defn ^{:doc "Deletes rows from a table. where-params is a vector containing a string @@ -948,7 +948,7 @@ generated keys are returned (as a map)." } :deprecated "0.3.0"} delete-rows [table where-params] - (delete! *db* table where-params)) + (apply delete! *db* table where-params [:entities *as-str*])) (defn ^{:doc "Updates values on selected rows in a table. where-params is a vector @@ -958,7 +958,7 @@ generated keys are returned (as a map)." } :deprecated "0.3.0"} update-values [table where-params record] - (update! *db* table record where-params)) + (apply update! *db* table record where-params [:entities *as-str*])) (defn update-or-insert-values "Updates values on selected rows in a table, or inserts a new row when no From 5389202342617c435e59fc84096a358aca187882 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 14:30:10 -0700 Subject: [PATCH 052/630] Address JDBC-45 by supporting nil / empty column list in sql/insert --- src/main/clojure/clojure/java/jdbc/sql.clj | 13 ++++++++----- src/test/clojure/clojure/java/test_sql.clj | 14 +++++++++++++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 6a597a14..0e09b1fe 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -113,12 +113,15 @@ and update! high-level operations within clojure.java.jdbc directly." } [table columns values entities] (let [nc (count columns) vcs (map count values)] - (if (not (apply = nc vcs)) + (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) (throw (IllegalArgumentException. "insert called with inconsistent number of columns / values")) - (into [(str "INSERT INTO " (table-str table entities) " ( " - (str/join ", " (map (fn [col] (col-str col entities)) columns)) - " ) VALUES ( " - (str/join ", " (repeat nc "?")) + (into [(str "INSERT INTO " (table-str table entities) + (when (seq columns) + (str " ( " + (str/join ", " (map (fn [col] (col-str col entities)) columns)) + " )")) + " VALUES ( " + (str/join ", " (repeat (first vcs) "?")) " )")] values)))) diff --git a/src/test/clojure/clojure/java/test_sql.clj b/src/test/clojure/clojure/java/test_sql.clj index 6088fdd0..89d76fbf 100644 --- a/src/test/clojure/clojure/java/test_sql.clj +++ b/src/test/clojure/clojure/java/test_sql.clj @@ -104,15 +104,27 @@ (deftest insert-dsl (is (= ["INSERT INTO a ( b ) VALUES ( ? )" [2]] (insert :a [:b] [2]))) + (is (= ["INSERT INTO a VALUES ( ? )" [2]] (insert :a nil [2]))) + (is (= ["INSERT INTO a VALUES ( ? )" [2]] (insert :a [] [2]))) (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2]] (insert :a {:b 2}))) (is (= ["INSERT INTO a ( b ) VALUES ( ? )" [2] [3]] (insert :a [:b] [2] [3]))) + (is (= ["INSERT INTO a VALUES ( ? )" [2] [3]] (insert :a nil [2] [3]))) + (is (= ["INSERT INTO a VALUES ( ? )" [2] [3]] (insert :a [] [2] [3]))) (is (= ["INSERT INTO a ( b, c, d ) VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] (insert :a [:b :c :d] [2 3 4] [3 4 5]))) + (is (= ["INSERT INTO a VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] + (insert :a nil [2 3 4] [3 4 5]))) + (is (= ["INSERT INTO a VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] + (insert :a [] [2 3 4] [3 4 5]))) (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2] ["INSERT INTO a ( b ) VALUES ( ? )" 3]] (insert :a {:b 2} {:b 3}))) (is (= ["INSERT INTO `a` ( `b` ) VALUES ( ? )" [2]] - (entities (quoted \`) (insert :a [:b] [2]))))) + (entities (quoted \`) (insert :a [:b] [2])))) + (is (= ["INSERT INTO `a` VALUES ( ? )" [2]] + (entities (quoted \`) (insert :a nil [2])))) + (is (= ["INSERT INTO `a` VALUES ( ? )" [2]] + (entities (quoted \`) (insert :a [] [2]))))) (deftest bad-insert-args (is (thrown? IllegalArgumentException (insert))) From 4e15891d53ce5021184207a1357dd71c672172d6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 14:37:34 -0700 Subject: [PATCH 053/630] Rewrite insert-values and insert-rows in terms of insert! so insert-rows can be deprecated in 0.3.0 - fixes JDBC-45 --- src/main/clojure/clojure/java/jdbc.clj | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e164bb07..2f7e59a7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -899,29 +899,15 @@ generated keys are returned (as a map)." } ;; is not (yet) supported in the new API... JDBC-45 insert-values [table column-names & value-groups] - (let [column-strs (map as-identifier column-names) - n (count (first value-groups)) - ns (map count value-groups) - return-keys (= 1 (count value-groups)) - prepared-statement (if return-keys do-prepared-return-keys do-prepared) - template (apply str (interpose "," (repeat n "?"))) - columns (if (seq column-names) - (format "(%s)" (apply str (interpose "," column-strs))) - "")] - (if (apply = ns) - (apply prepared-statement - (format "INSERT INTO %s %s VALUES (%s)" - (as-identifier table) columns template) - value-groups) - (throw (IllegalArgumentException. "insert-values called with inconsistent number of columns / values"))))) + (apply insert! *db* table column-names (concat value-groups [:entities *as-str*]))) (defn insert-rows - "Inserts complete rows into a table. Each row is a vector of values for - each of the table's columns in order. - If a single row is inserted, returns a map of the generated keys." + ^{:doc "Inserts complete rows into a table. Each row is a vector of values for + each of the table's columns in order. + If a single row is inserted, returns a map of the generated keys." + :deprecated "0.3.0"} [table & rows] - ;; will be deprecated after JDBC-45 is implemented - (apply insert-values table nil rows)) + (apply insert! *db* table nil (concat rows [:entities *as-str*]))) (defn ^{:doc "Inserts records into a table. records are maps from strings or keywords From 00cec02b37aa475a47e588ee1706fd4e72b223a8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 14:38:07 -0700 Subject: [PATCH 054/630] insert-values / insert-rows now throw IllegalArgumentException after JDBC-45 --- src/test/clojure/clojure/java/test_jdbc.clj | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 80a72492..9c6f2397 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -302,10 +302,8 @@ (sql/insert-values :fruit [:name :appearance] - ["Apple" "strange" "whoops"]) - ;; sqlite does not throw exception for too many items - (throw (java.sql.SQLException.))) - (catch java.sql.SQLException _ + ["Apple" "strange" "whoops"])) + (catch IllegalArgumentException _ (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) From 5e5fd1e9e5e6ae12657e17227011631e4eb21200 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 15:19:30 -0700 Subject: [PATCH 055/630] Clean up test to use thrown? macro. --- src/test/clojure/clojure/java/test_jdbc.clj | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9c6f2397..9afdd7b1 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -311,18 +311,14 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db) - (try - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - ;; insert-values should complain about the mismatch - (is nil "insert-values did not throw an exception!")) - (catch IllegalArgumentException _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) + (is (thrown? IllegalArgumentException + (sql/transaction + (sql/insert-values + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"])))) (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) (deftest test-rollback From 685ccdd745620882420bad9c190eb7a465996e90 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 16:49:33 -0700 Subject: [PATCH 056/630] Clean up copyright / license notice --- src/main/clojure/clojure/java/jdbc.clj | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 2f7e59a7..ee6e6fa6 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,10 +1,11 @@ -;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. +;; Copyright (c) Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; The use and distribution terms for this software are covered by +;; the Eclipse Public License 1.0 +;; (http://opensource.org/licenses/eclipse-1.0.php) which can be +;; found in the file epl-v10.html at the root of this distribution. +;; By using this software in any fashion, you are agreeing to be +;; bound by the terms of this license. You must not remove this +;; notice, or any other, from this software. ;; ;; jdbc.clj ;; From c9e8de51afddb4c34fec3834ffcd526ef76f9ced Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 16:50:03 -0700 Subject: [PATCH 057/630] Minor code cleanup --- src/main/clojure/clojure/java/jdbc.clj | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ee6e6fa6..bc2fa67d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -531,9 +531,10 @@ generated keys are returned (as a map)." } See db-transaction* for more details." [binding & body] `(db-transaction* (let [db# ~(second binding)] - (assoc db# :level (or (:level db#) 0) :rollback (or (:rollback db#) (atom false)))) - (fn [~(first binding)] - ~@body))) + (assoc db# + :level (or (:level db#) 0) + :rollback (or (:rollback db#) (atom false)))) + (fn [~(first binding)] ~@body))) (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands From 00296e7acdea5c7c37ff710315f4b9cae05f0706 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 16:50:46 -0700 Subject: [PATCH 058/630] Code cleanup (rename db-transaction bound argument so it is clearer) --- src/main/clojure/clojure/java/jdbc.clj | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index bc2fa67d..16038321 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -544,7 +544,8 @@ generated keys are returned (as a map)." } (doseq [^String cmd commands] (.addBatch stmt cmd)) (if transaction? - (db-transaction [db (assoc db :connection (.getConnection stmt))] (execute-batch stmt)) + (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (execute-batch stmt)) (try (execute-batch stmt) (catch Exception e @@ -571,7 +572,8 @@ generated keys are returned (as a map)." } ;; assume generated keys is unsupported and return counts instead: counts))))] (if transaction? - (db-transaction [db (assoc db :connection (.getConnection stmt))] (exec-and-return-keys)) + (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (exec-and-return-keys)) (try (exec-and-return-keys) (catch Exception e @@ -586,7 +588,8 @@ generated keys are returned (as a map)." } (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql)] (if (empty? param-groups) (if transaction? - (db-transaction [db (assoc db :connection (.getConnection stmt))] (vector (.executeUpdate stmt))) + (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (vector (.executeUpdate stmt))) (try (vector (.executeUpdate stmt)) (catch Exception e @@ -596,7 +599,8 @@ generated keys are returned (as a map)." } (set-parameters stmt param-group) (.addBatch stmt)) (if transaction? - (db-transaction [db (assoc db :connection (.getConnection stmt))] (execute-batch stmt)) + (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (execute-batch stmt)) (try (execute-batch stmt) (catch Exception e From 0673d9fc657233040934b8917d6b2363cf1f6c5b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 16:51:26 -0700 Subject: [PATCH 059/630] Use local helper for query and execute! to reduce duplication and clean up the code --- src/main/clojure/clojure/java/jdbc.clj | 44 ++++++++++++-------------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 16038321..e1b9bbb5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -652,20 +652,17 @@ generated keys are returned (as a map)." } :identifiers - applied to each column name in the result set, default lower-case" [db sql-params & {:keys [result-set-fn row-fn identifiers] :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] - (if-let [con (:connection db)] - (db-with-query-results* - db - (vec sql-params) - (fn [rs] - (result-set-fn (map row-fn rs))) - identifiers) - (with-open [con (get-connection db)] - (db-with-query-results* - (assoc db :connection con) - (vec sql-params) - (fn [rs] - (result-set-fn (map row-fn rs))) - identifiers)))) + (let [query-helper (fn [db] + (db-with-query-results* db + (vec sql-params) + (fn [rs] + (result-set-fn (map row-fn rs))) + identifiers))] + (if-let [con (:connection db)] + (query-helper db) + (with-open [con (get-connection db)] + (query-helper + (assoc db :connection con)))))) (defn execute! "Given a database connection and a vector containing SQL and optional parameters, @@ -673,16 +670,15 @@ generated keys are returned (as a map)." } whether to run the operation in a transaction or not (default true)." [db sql-params & {:keys [transaction?] :or {transaction? true}}] - (if-let [con (:connection db)] - (db-do-prepared db - transaction? - (first sql-params) - (rest sql-params)) - (with-open [con (get-connection db)] - (db-do-prepared (assoc db :connection con) - transaction? - (first sql-params) - (rest sql-params))))) + (let [execute-helper (fn [db] + (db-do-prepared db + transaction? + (first sql-params) + (rest sql-params)))] + (if-let [con (:connection db)] + (execute-helper db) + (with-open [con (get-connection db)] + (execute-helper (assoc db :connection con)))))) (defn delete! "Given a database connection, a table name and a where clause of columns to match, From 985d672f0e563935625e3a96159466b7ba63721e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 16:52:22 -0700 Subject: [PATCH 060/630] Cleanup insert! using helper functions, add proper transaction support to fix JDBC-42 --- src/main/clojure/clojure/java/jdbc.clj | 72 +++++++++++++------------- 1 file changed, 37 insertions(+), 35 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e1b9bbb5..8a04464b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -695,45 +695,47 @@ generated keys are returned (as a map)." } (sql/delete table where-clause :entities entities) :transaction? transaction?)) +(defn- multi-insert-helper + "Given a (connected) database connection and some SQL statements (for multiple + inserts), run a prepared statement on each and return any generated keys. + Note: we are eager so an unrealized lazy-seq cannot escape from the connection." + [db stmts] + (doall (map (fn [row] + (db-do-prepared-return-keys db false (first row) (rest row))) + stmts))) + +(defn- insert-helper + "Given a (connected) database connection, a transaction flag and some SQL statements + (for one or more inserts), run a prepared statement or a sequence of them." + [db transaction? stmts] + (if (string? (first stmts)) + (apply db-do-prepared db transaction? (first stmts) (rest stmts)) + (if transaction? + (db-transaction [t-db db] (multi-insert-helper t-db stmts)) + (multi-insert-helper db stmts)))) + +(defn- extract-transaction? + "Given a sequence of data, look for :transaction? arg in it and return a pair of + the transaction? value (defaulting to true) and the data without the option." + [data] + (let [before (take-while (partial not= :transaction?) data) + after (drop-while (partial not= :transaction?) data)] + (if (seq after) + [(second after) (concat before (nnext after))] + [true data]))) + (defn insert! "Given a database connection, a table name and either maps representing rows or - a list of column names followed by lists of column values, perform an insert. - Currently the insert is always run in a transaction." - [db table & maps-or-cols-and-values-etc] - (let [stmts (apply sql/insert table maps-or-cols-and-values-etc) - transaction? true] + a list of column names followed by lists of column values, perform an insert. + Use :transaction? argument to specify whether to run in a transaction or not. + The default is true (use a transaction)." + [db table & options] + (let [[transaction? maps-or-cols-and-values-etc] (extract-transaction? options) + stmts (apply sql/insert table maps-or-cols-and-values-etc)] (if-let [con (:connection db)] - (if (string? (first stmts)) - (apply db-do-prepared - db - transaction? - (first stmts) - (rest stmts)) - (doall (map (fn [row] - (let [result (db-do-prepared-return-keys - db - ;; bad idea - this is nested - transaction? - (first row) - (rest row))] - result)) - stmts))) + (insert-helper db transaction? stmts) (with-open [con (get-connection db)] - (if (string? (first stmts)) - (apply db-do-prepared - (assoc db :connection con) - transaction? - (first stmts) - (rest stmts)) - (doall (map (fn [row] - (let [result (db-do-prepared-return-keys - (assoc db :connection con) - ;; bad idea - this is nested - transaction? - (first row) - (rest row))] - result)) - stmts))))))) + (insert-helper (assoc db :connection con) transaction? stmts))))) (defn update! "Given a database connection, a table name, a map of column values to set and a From c366c7f376657d005d633239f9f42697901a3364 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 19:07:47 -0700 Subject: [PATCH 061/630] Add ! db-set-rollback-only and rename some db-transaction bindings for clarity --- src/test/clojure/clojure/java/test_jdbc.clj | 37 ++++++++++----------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9afdd7b1..b8480585 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -473,13 +473,13 @@ (sql/with-connection db (create-test-table :fruit db)) (try - (sql/db-transaction [db db] - (sql/insert! db + (sql/db-transaction [t-db db] + (sql/insert! t-db :fruit [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"]) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 2 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count))) (throw (Exception. "deliberate exception"))) (catch Exception _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) @@ -489,8 +489,8 @@ (sql/with-connection db (create-test-table :fruit db)) (try - (sql/db-transaction [db db] - (sql/insert! db + (sql/db-transaction [t-db db] + (sql/insert! t-db :fruit [:name :appearance] ["Grape" "yummy"] @@ -507,17 +507,17 @@ (sql/with-connection db (create-test-table :fruit db)) (try - (sql/db-transaction [db db] - (is (not (sql/db-is-rollback-only db))) - (sql/db-set-rollback-only db) - (is (sql/db-is-rollback-only db)) - (sql/insert! db + (sql/db-transaction [t-db db] + (is (not (sql/db-is-rollback-only t-db))) + (sql/db-set-rollback-only! t-db) + (is (sql/db-is-rollback-only t-db)) + (sql/insert! t-db :fruit [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"] ["Apple" "strange" "whoops"]) - (is (= 3 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 3 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) (catch Exception _ ;; insert! throws the exception, not JDBC (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) @@ -526,13 +526,12 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (try - (sql/db-transaction [db db] - (sql/db-set-rollback-only db) - (sql/insert! db - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (sql/db-transaction [t-db db] + (sql/db-set-rollback-only! t-db) + (sql/insert! t-db + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) From a2daa8b0512b354d7177c47b622b179efab44f39 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 19:10:02 -0700 Subject: [PATCH 062/630] Cleanup a lot of the transaction / rollback logic --- src/main/clojure/clojure/java/jdbc.clj | 132 +++++++++++++++---------- 1 file changed, 80 insertions(+), 52 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8a04464b..773ebe8b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -105,7 +105,33 @@ generated keys are returned (as a map)." } (.setProperty p (as-str identity k) (as-str identity v))) p)) -(def ^{:private true :dynamic true} *db* {:connection nil :level 0}) +(defprotocol Connectable + (add-connection [db connection]) + (get-level [db])) + +(defn- inc-level + "Increment the nesting level for a transacted database connection. + If we are at the top level, also add in a rollback state." + [db] + (let [nested-db (update-in db [:level] (fnil inc 0))] + (if (= 1 (:level nested-db)) + (assoc nested-db :rollback (atom false)) + nested-db))) + +(extend-protocol Connectable + String + (add-connection [_ connection] {:connection connection :level 0}) + (get-level [_] 0) + + clojure.lang.Associative + (add-connection [m connection] (assoc m :connection connection)) + (get-level [m] (or (:level m) 0)) + + nil + (add-connection [_ connection] {:connection connection :level 0}) + (get-level [_] 0)) + +(def ^{:private true :dynamic true} *db* (add-connection nil nil)) (def ^{:private true :doc "Map of classnames to subprotocols"} classnames {"postgresql" "org.postgresql.Driver" @@ -454,7 +480,8 @@ generated keys are returned (as a map)." } (defn db-find-connection "Returns the current database connection (or nil if there is none)" ^java.sql.Connection [db] - (:connection db)) + (and (map? db) + (:connection db))) (defn db-connection "Returns the current database connection (or throws if there is none)" @@ -462,13 +489,6 @@ generated keys are returned (as a map)." } (or (db-find-connection db) (throw (Exception. "no current database connection")))) -(defn- db-rollback - "Accessor for the rollback flag on the current connection" - ([db] - (deref (:rollback db))) - ([db val] - (swap! (:rollback db) (fn [_] val)))) - (defn- throw-non-rte "This ugliness makes it easier to catch SQLException objects rather than something wrapped in a RuntimeException which @@ -479,17 +499,22 @@ generated keys are returned (as a map)." } (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) :else (throw ex))) -(defn db-set-rollback-only +(defn db-set-rollback-only! "Marks the outermost transaction such that it will rollback rather than commit when complete" [db] - (db-rollback db true)) + (reset! (:rollback db) true)) + +(defn db-unset-rollback-only! + "Marks the outermost transaction such that it will not rollback when complete" + [db] + (reset! (:rollback db) false)) (defn db-is-rollback-only "Returns true if the outermost transaction will rollback rather than commit when complete" [db] - (db-rollback db)) + (deref (:rollback db))) (defn db-transaction* "Evaluates func as a transaction on the open database connection. Any @@ -500,29 +525,35 @@ generated keys are returned (as a map)." } the entire transaction will be rolled back rather than committed when complete." [db func] - (let [nested-db (update-in db [:level] inc)] - (if (= (:level nested-db) 1) - (let [^java.sql.Connection con (get-connection nested-db) - nested-db (assoc nested-db :connection con) - auto-commit (.getAutoCommit con)] - (io! - (.setAutoCommit con false) - (try - (let [result (func nested-db)] - (if (db-rollback nested-db) - (.rollback con) - (.commit con)) - result) - (catch Throwable t - (.rollback con) - (throw-non-rte t)) - (finally - (db-rollback nested-db false) - (.setAutoCommit con auto-commit))))) - (try - (func nested-db) - (catch Exception e - (throw-non-rte e)))))) + (if (zero? (get-level db)) + (let [^java.sql.Connection con (get-connection db) + nested-db (inc-level (add-connection db con)) + auto-commit (.getAutoCommit con)] + #_(println "db-transaction* top-level: " nested-db) + (io! + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-is-rollback-only nested-db) + (do + #_(println "-- rolling back") + (.rollback con)) + (do + #_(println "-- committing") + (.commit con))) + result) + (catch Throwable t + #_(println "-- exception: rolling back" (.getMessage t)) + (.rollback con) + (throw-non-rte t)) + (finally + (db-unset-rollback-only! nested-db) + (.setAutoCommit con auto-commit))))) + (try + #_(println "db-transaction* nested:" (inc-level db)) + (func (inc-level db)) + (catch Exception e + (throw-non-rte e))))) (defmacro db-transaction "Evaluates body in the context of a transaction on the specified database connection. @@ -530,10 +561,7 @@ generated keys are returned (as a map)." } that is bound for evaluation of the body. See db-transaction* for more details." [binding & body] - `(db-transaction* (let [db# ~(second binding)] - (assoc db# - :level (or (:level db#) 0) - :rollback (or (:rollback db#) (atom false)))) + `(db-transaction* ~(second binding) (fn [~(first binding)] ~@body))) (defn db-do-commands @@ -544,7 +572,7 @@ generated keys are returned (as a map)." } (doseq [^String cmd commands] (.addBatch stmt cmd)) (if transaction? - (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (db-transaction [t-db (add-connection db (.getConnection stmt))] (execute-batch stmt)) (try (execute-batch stmt) @@ -572,7 +600,7 @@ generated keys are returned (as a map)." } ;; assume generated keys is unsupported and return counts instead: counts))))] (if transaction? - (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (db-transaction [t-db (add-connection db (.getConnection stmt))] (exec-and-return-keys)) (try (exec-and-return-keys) @@ -588,7 +616,7 @@ generated keys are returned (as a map)." } (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql)] (if (empty? param-groups) (if transaction? - (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (db-transaction [t-db (add-connection db (.getConnection stmt))] (vector (.executeUpdate stmt))) (try (vector (.executeUpdate stmt)) @@ -599,7 +627,7 @@ generated keys are returned (as a map)." } (set-parameters stmt param-group) (.addBatch stmt)) (if transaction? - (db-transaction [t-db (assoc db :connection (.getConnection stmt))] + (db-transaction [t-db (add-connection db (.getConnection stmt))] (execute-batch stmt)) (try (execute-batch stmt) @@ -658,11 +686,11 @@ generated keys are returned (as a map)." } (fn [rs] (result-set-fn (map row-fn rs))) identifiers))] - (if-let [con (:connection db)] + (if-let [con (and (map? db) (:connection db))] (query-helper db) (with-open [con (get-connection db)] (query-helper - (assoc db :connection con)))))) + (add-connection db con)))))) (defn execute! "Given a database connection and a vector containing SQL and optional parameters, @@ -675,10 +703,10 @@ generated keys are returned (as a map)." } transaction? (first sql-params) (rest sql-params)))] - (if-let [con (:connection db)] + (if-let [con (and (map? db) (:connection db))] (execute-helper db) (with-open [con (get-connection db)] - (execute-helper (assoc db :connection con)))))) + (execute-helper (add-connection db con)))))) (defn delete! "Given a database connection, a table name and a where clause of columns to match, @@ -732,10 +760,10 @@ generated keys are returned (as a map)." } [db table & options] (let [[transaction? maps-or-cols-and-values-etc] (extract-transaction? options) stmts (apply sql/insert table maps-or-cols-and-values-etc)] - (if-let [con (:connection db)] + (if-let [con (and (map? db) (:connection db))] (insert-helper db transaction? stmts) (with-open [con (get-connection db)] - (insert-helper (assoc db :connection con) transaction? stmts))))) + (insert-helper (add-connection db con) transaction? stmts))))) (defn update! "Given a database connection, a table name, a map of column values to set and a @@ -800,7 +828,7 @@ generated keys are returned (as a map)." } (.setAutoCommit con false) (try (let [result (func)] - (if (db-rollback *db*) + (if (db-is-rollback-only *db*) (.rollback con) (.commit con)) result) @@ -808,7 +836,7 @@ generated keys are returned (as a map)." } (.rollback con) (throw-non-rte t)) (finally - (db-rollback *db* false) + (db-unset-rollback-only! *db*) (.setAutoCommit con auto-commit))))) (try (func) @@ -834,7 +862,7 @@ generated keys are returned (as a map)." } :deprecated "0.3.0"} set-rollback-only [] - (db-set-rollback-only *db*)) + (db-set-rollback-only! *db*)) (defn ^{:doc "Returns true if the outermost transaction will rollback rather than From 32e548dd204c073f912987dd4653823a7140d068 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 21:18:39 -0700 Subject: [PATCH 063/630] Remove debug and clean up --- src/main/clojure/clojure/java/jdbc.clj | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 773ebe8b..72f94cb6 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -529,28 +529,21 @@ generated keys are returned (as a map)." } (let [^java.sql.Connection con (get-connection db) nested-db (inc-level (add-connection db con)) auto-commit (.getAutoCommit con)] - #_(println "db-transaction* top-level: " nested-db) (io! (.setAutoCommit con false) (try (let [result (func nested-db)] (if (db-is-rollback-only nested-db) - (do - #_(println "-- rolling back") - (.rollback con)) - (do - #_(println "-- committing") - (.commit con))) + (.rollback con) + (.commit con)) result) (catch Throwable t - #_(println "-- exception: rolling back" (.getMessage t)) (.rollback con) (throw-non-rte t)) (finally (db-unset-rollback-only! nested-db) (.setAutoCommit con auto-commit))))) (try - #_(println "db-transaction* nested:" (inc-level db)) (func (inc-level db)) (catch Exception e (throw-non-rte e))))) From a94a42f07b701694f6953bd59893b63d8de61a10 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 21:20:54 -0700 Subject: [PATCH 064/630] Clean up how tests handle string-based MySQL connection tests --- src/test/clojure/clojure/java/test_jdbc.clj | 33 +++++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index b8480585..04573865 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -123,20 +123,23 @@ ;; We start with all tables dropped and each test has to create the tables ;; necessary for it to do its job, and populate it as needed... +(defn- mysql? [db] + (if (string? db) + (re-find #"mysql:" db) + (= "mysql" (:subprotocol db)))) + (defn- create-test-table "Create a standard test table. Must be inside with-connection. For MySQL, ensure table uses an engine that supports transactions!" [table db] - (let [p (:subprotocol db)] - (sql/create-table - table - [:id :int (if (= "mysql" p) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] - [:name "VARCHAR(32)" (if (= "mysql" p) "" "PRIMARY KEY")] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))) - "ENGINE=InnoDB" "")))) + (sql/create-table + table + [:id :int (if (mysql? db) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] + [:name "VARCHAR(32)" (if (mysql? db) "" "PRIMARY KEY")] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec (if (mysql? db) "ENGINE=InnoDB" ""))) (deftest test-create-table (doseq [db (test-specs)] @@ -223,7 +226,8 @@ {:name "Pomegranate" :appearance "fresh" :cost 585} {:name "Kiwifruit" :grade 93})] (condp = (:subprotocol db) - nil nil ; for the string connection args + nil (when (mysql? db) + (is (= '({:generated_key 1} {:generated_key 2}) r))) "postgresql" (is (= 2 (count r))) "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) @@ -369,9 +373,12 @@ (defn- returned-key [db k] (condp = (:subprotocol db) - "derby" {:1 nil} + "derby" {:1 nil} "hsqldb" 1 - "mysql" {:generated_key k} + "mysql" {:generated_key k} + nil (if (mysql? db) ; string-based tests + {:generated_key k} + k) "jtds:sqlserver" {:id nil} "sqlserver" {:generated_keys nil} "sqlite" {(keyword "last_insert_rowid()") k} From 2eb182fc577dbacb30bbac0d52b9422d0f7e887c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 22:55:39 -0700 Subject: [PATCH 065/630] Comment out local MS SQL Server driver dependency --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 4611bb2d..1e97083d 100644 --- a/pom.xml +++ b/pom.xml @@ -62,13 +62,13 @@ test - + From 47b17e4b5f3f985e77ac19d02de1b9c573652c66 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 22:56:17 -0700 Subject: [PATCH 066/630] Update ns docstring to indicate massive API overhaul --- src/main/clojure/clojure/java/jdbc.clj | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 72f94cb6..68a270e7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -35,10 +35,17 @@ parameters can be represented as simple vectors where the first element is the SQL string, with ? for each parameter, and the remaining elements are the parameter values to be substituted. In general, operations return the number of rows affected, except for a single record insert where any -generated keys are returned (as a map)." } +generated keys are returned (as a map). + +As of release 0.3.0, the API has undergone a major overhaul and most of the +original API has been deprecated in favor of a more idiomatic API, and a +minimal DSL for generating SQL has been added as an option. The original +API is still supported but will be deprecated before a 1.0.0 release is +made at some future date." } clojure.java.jdbc (:import [java.net URI] - [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement] + [java.sql BatchUpdateException DriverManager ParameterMetaData + PreparedStatement ResultSet SQLException Statement Types] [java.util Hashtable Map Properties] [javax.naming InitialContext Name] [javax.sql DataSource]) From 36aa936bec7926c767a30da7579046edb9ed5c0b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 22:56:46 -0700 Subject: [PATCH 067/630] Add note about yet-to-be-deprecated naming strategy stuff --- src/main/clojure/clojure/java/jdbc.clj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 68a270e7..60032868 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -53,6 +53,8 @@ made at some future date." } (:require [clojure.string :as str] [clojure.java.jdbc.sql :as sql])) +;; this whole section needs to be deprecated too as part of 0.3.0 + (def ^{:private true :dynamic true :doc "The default entity naming strategy is to do nothing."} *as-str* @@ -103,6 +105,8 @@ made at some future date." } ([x] (as-keyword x *as-key*)) ([x f-keyword] (as-key f-keyword x))) +;; end of to-be-deprecated section + (defn- ^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. Uses as-str to convert both keys and values into strings." From bf853d9a8e4ce90211951204f948070b1adec7ef Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 22:57:16 -0700 Subject: [PATCH 068/630] Enhance add-connection to retain more information about how connections were added --- src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 60032868..4596c97a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -131,7 +131,7 @@ made at some future date." } (extend-protocol Connectable String - (add-connection [_ connection] {:connection connection :level 0}) + (add-connection [s connection] {:connection connection :level 0 :connection-string s}) (get-level [_] 0) clojure.lang.Associative @@ -139,7 +139,7 @@ made at some future date." } (get-level [m] (or (:level m) 0)) nil - (add-connection [_ connection] {:connection connection :level 0}) + (add-connection [_ connection] {:connection connection :level 0 :legacy true}) (get-level [_] 0)) (def ^{:private true :dynamic true} *db* (add-connection nil nil)) From 1815e7ea3846fbd9aae8b5be9896922832657454 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 22:59:43 -0700 Subject: [PATCH 069/630] Enhance set-parameters to use metadata and types - fixes JDBC-40 Tidy up prepare-statement so it doesn't wrap so much. Add unfortunate test for MySQL so we can avoid unnecessary metadata calls in the updated set-parameters. --- src/main/clojure/clojure/java/jdbc.clj | 83 +++++++++++++++++--------- 1 file changed, 56 insertions(+), 27 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 4596c97a..ff928d2a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -156,6 +156,18 @@ made at some future date." } (def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols {"postgres" "postgresql"}) +(defn- mysql? + "Given a db spec, return true if it represents MySQL. This is used for set-parameters." + [db] + (cond (string? db) + (re-find #"mysql:" db) + + (:subprotocol db) + (= "mysql" (:subprotocol db)) + + (:connection db) + (.startsWith (.getName (type (:connection db))) "com.mysql."))) + (defn- parse-properties-uri [^URI uri] (let [host (.getHost uri) port (if (pos? (.getPort uri)) (.getPort uri)) @@ -398,36 +410,53 @@ made at some future date." } :return-keys true | false - default false :result-type :forward-only | :scroll-insensitive | :scroll-sensitive :concurrency :read-only | :updatable + :cursors :fetch-size n :max-rows n" - [^java.sql.Connection con ^String sql & {:keys [return-keys result-type concurrency cursors fetch-size max-rows]}] - (let [^PreparedStatement stmt (cond - return-keys (try - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS) - (catch Exception _ - ;; assume it is unsupported and try basic PreparedStatement: - (.prepareStatement con sql))) - (and result-type concurrency) (if cursors - (.prepareStatement con sql - (result-type result-set-type) - (concurrency result-set-concurrency) - (cursors result-set-holdability)) - (.prepareStatement con sql - (result-type result-set-type) - (concurrency result-set-concurrency))) - :else (.prepareStatement con sql))] + [^java.sql.Connection con ^String sql & + {:keys [return-keys result-type concurrency cursors fetch-size max-rows]}] + (let [^PreparedStatement + stmt (cond return-keys + (try + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS) + (catch Exception _ + ;; assume it is unsupported and try basic PreparedStatement: + (.prepareStatement con sql))) + + (and result-type concurrency) + (if cursors + (.prepareStatement con sql + (result-type result-set-type) + (concurrency result-set-concurrency) + (cursors result-set-holdability)) + (.prepareStatement con sql + (result-type result-set-type) + (concurrency result-set-concurrency))) + + :else + (.prepareStatement con sql))] (when fetch-size (.setFetchSize stmt fetch-size)) (when max-rows (.setMaxRows stmt max-rows)) stmt)) (defn- set-parameters - "Add the parameters to the given statement." - [^PreparedStatement stmt params] - (dorun - (map-indexed - (fn [ix value] - (.setObject stmt (inc ix) value)) - params))) + "Add the parameters to the given statement. Use parameter metadata if it is + available, which allows us to specify the SQL type and support NULL better." + [^PreparedStatement stmt params db] + (let [^ParameterMetaData metadata (when-not (mysql? db) + (try (.getParameterMetaData stmt) + (catch SQLException _)))] + (dorun (map-indexed (fn [ix value] + (let [ix* (inc ix) + sql-type (when metadata + (try (.getParameterType metadata ix*) + (catch SQLException _)))] + (if sql-type + (if (nil? value) + (.setNull stmt ix* sql-type) + (.setObject stmt ix* value)) + (.setObject stmt ix* value)))) + params)))) (defn create-table-ddl "Given a table name and column specs with an optional table-spec @@ -590,7 +619,7 @@ made at some future date." } Return the generated keys for the (single) update/insert." [db transaction? sql param-group] (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql :return-keys true)] - (set-parameters stmt param-group) + (set-parameters stmt param-group db) (letfn [(exec-and-return-keys [] (let [counts (.executeUpdate stmt)] (try @@ -628,7 +657,7 @@ made at some future date." } (throw-non-rte e)))) (do (doseq [param-group param-groups] - (set-parameters stmt param-group) + (set-parameters stmt param-group db) (.addBatch stmt)) (if transaction? (db-transaction [t-db (add-connection db (.getConnection stmt))] @@ -669,7 +698,7 @@ made at some future date." } (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (get-connection db) sql prepare-args))] - (set-parameters stmt params) + (set-parameters stmt params db) (with-open [rset (.executeQuery stmt)] (func (resultset-seq rset :identifiers identifiers)))))) @@ -1026,7 +1055,7 @@ made at some future date." } :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special)))] (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (get-connection *db*) sql prepare-args))] - (set-parameters stmt params) + (set-parameters stmt params *db*) (with-open [rset (.executeQuery stmt)] (binding [*db* (assoc *db* :connection (.getConnection stmt))] (func (resultset-seq rset))))))) From c6c7f11e4607019460d67eb2cefa22071ad7e3a8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 6 Apr 2013 23:34:11 -0700 Subject: [PATCH 070/630] Reorder some fns that will be deprecated, add alternate spelling for resultset-seq --- src/main/clojure/clojure/java/jdbc.clj | 120 +++++++++++++------------ 1 file changed, 64 insertions(+), 56 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ff928d2a..e3639f58 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -105,6 +105,63 @@ made at some future date." } ([x] (as-keyword x *as-key*)) ([x f-keyword] (as-key f-keyword x))) +(defn as-quoted-str + "Given a quoting pattern - either a single character or a vector pair of + characters - and a string, return the quoted string: + (as-quoted-str X foo) will return XfooX + (as-quoted-str [A B] foo) will return AfooB" + [q x] + (if (vector? q) + (str (first q) x (last q)) + (str q x q))) + +(defn as-named-identifier + "Given a naming strategy and a keyword, return the keyword as a string using the + entity naming strategy. + Given a naming strategy and a string, return the string as-is. + The naming strategy should either be a function (the entity naming strategy) or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or keyword naming strategy respectively." + [naming-strategy x] + (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) + +(defn as-named-keyword + "Given a naming strategy and a string, return the string as a keyword using the + keyword naming strategy. + Given a naming strategy and a keyword, return the keyword as-is. + The naming strategy should either be a function (the entity naming strategy) or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or keyword naming strategy respectively. + Note that providing a single function will cause the default keyword naming + strategy to be used!" + [naming-strategy x] + (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) + +(defn as-quoted-identifier + "Given a quote pattern - either a single character or a pair of characters in + a vector - and a keyword, return the keyword as a string using a simple + quoting naming strategy. + Given a quote pattern and a string, return the string as-is. + (as-quoted-identifier X :name) will return XnameX as a string. + (as-quoted-identifier [A B] :name) will return AnameB as a string." + [q x] + (as-identifier x (partial as-quoted-str q))) + +(defmacro with-naming-strategy + "Evaluates body in the context of a naming strategy. + The naming strategy is either a function - the entity naming strategy - or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or the keyword naming strategy respectively. The default entity + naming strategy is identity; the default keyword naming strategy is lower-case." + [naming-strategy & body ] + `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) + *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) + +(defmacro with-quoted-identifiers + "Evaluates body in the context of a simple quoting naming strategy." + [q & body ] + `(binding [*as-str* (partial as-quoted-str ~q)] ~@body)) + ;; end of to-be-deprecated section (defn- ^Properties as-properties @@ -316,62 +373,13 @@ made at some future date." } (cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))] (rows))) -(defn as-quoted-str - "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (as-quoted-str X foo) will return XfooX - (as-quoted-str [A B] foo) will return AfooB" - [q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q))) - -(defn as-named-identifier - "Given a naming strategy and a keyword, return the keyword as a string using the - entity naming strategy. - Given a naming strategy and a string, return the string as-is. - The naming strategy should either be a function (the entity naming strategy) or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or keyword naming strategy respectively." - [naming-strategy x] - (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) - -(defn as-named-keyword - "Given a naming strategy and a string, return the string as a keyword using the - keyword naming strategy. - Given a naming strategy and a keyword, return the keyword as-is. - The naming strategy should either be a function (the entity naming strategy) or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or keyword naming strategy respectively. - Note that providing a single function will cause the default keyword naming - strategy to be used!" - [naming-strategy x] - (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) - -(defn as-quoted-identifier - "Given a quote pattern - either a single character or a pair of characters in - a vector - and a keyword, return the keyword as a string using a simple - quoting naming strategy. - Given a quote pattern and a string, return the string as-is. - (as-quoted-identifier X :name) will return XnameX as a string. - (as-quoted-identifier [A B] :name) will return AnameB as a string." - [q x] - (as-identifier x (partial as-quoted-str q))) - -(defmacro with-naming-strategy - "Evaluates body in the context of a naming strategy. - The naming strategy is either a function - the entity naming strategy - or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or the keyword naming strategy respectively. The default entity - naming strategy is identity; the default keyword naming strategy is lower-case." - [naming-strategy & body ] - `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) - *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) - -(defmacro with-quoted-identifiers - "Evaluates body in the context of a simple quoting naming strategy." - [q & body ] - `(binding [*as-str* (partial as-quoted-str ~q)] ~@body)) +(defn result-set-seq + "An alternative name for resultset-seq since result-set-seq is more consistent with + the rest of java.jdbc (and resultset-seq is already a clojure.core function, albeit + with different functionality)." + [rs & {:keys [identifiers] + :or {identifiers *as-key*}}] + (resultset-seq rs :identifiers identifiers)) (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. From 78e0234632d4faf5ced33434944b638bf0b143a6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 00:40:57 -0700 Subject: [PATCH 071/630] Expose a few functions from sql/ namespace to help clean up the deprecated stuff in the top-level namespace --- src/main/clojure/clojure/java/jdbc.clj | 219 +++++++++++---------- src/main/clojure/clojure/java/jdbc/sql.clj | 48 +++-- 2 files changed, 133 insertions(+), 134 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e3639f58..571a6fff 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -53,7 +53,8 @@ made at some future date." } (:require [clojure.string :as str] [clojure.java.jdbc.sql :as sql])) -;; this whole section needs to be deprecated too as part of 0.3.0 +;; technically deprecated but still used as defaults in a couple of +;; places for backward compatibility... (def ^{:private true :dynamic true :doc "The default entity naming strategy is to do nothing."} @@ -65,112 +66,15 @@ made at some future date." } *as-key* str/lower-case) -(defn as-str - "Given a naming strategy and a keyword, return the keyword as a - string per that naming strategy. Given (a naming strategy and) - a string, return it as-is. - A keyword of the form :x.y is treated as keywords :x and :y, - both are turned into strings via the naming strategy and then - joined back together so :x.y might become `x`.`y` if the naming - strategy quotes identifiers with `." - [f x] - (if (instance? clojure.lang.Named x) - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))) - (str x))) - -(defn as-key - "Given a naming strategy and a string, return the string as a - keyword per that naming strategy. Given (a naming strategy and) - a keyword, return it as-is." - [f x] - (if (instance? clojure.lang.Named x) - x - (keyword (f (str x))))) - -(defn as-identifier - "Given a keyword, convert it to a string using the current naming - strategy. - Given a string, return it as-is." - ([x] (as-identifier x *as-str*)) - ([x f-entity] (as-str f-entity x))) - -(defn as-keyword - "Given an entity name (string), convert it to a keyword using the - current naming strategy. - Given a keyword, return it as-is." - ([x] (as-keyword x *as-key*)) - ([x f-keyword] (as-key f-keyword x))) - -(defn as-quoted-str - "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (as-quoted-str X foo) will return XfooX - (as-quoted-str [A B] foo) will return AfooB" - [q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q))) - -(defn as-named-identifier - "Given a naming strategy and a keyword, return the keyword as a string using the - entity naming strategy. - Given a naming strategy and a string, return the string as-is. - The naming strategy should either be a function (the entity naming strategy) or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or keyword naming strategy respectively." - [naming-strategy x] - (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) - -(defn as-named-keyword - "Given a naming strategy and a string, return the string as a keyword using the - keyword naming strategy. - Given a naming strategy and a keyword, return the keyword as-is. - The naming strategy should either be a function (the entity naming strategy) or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or keyword naming strategy respectively. - Note that providing a single function will cause the default keyword naming - strategy to be used!" - [naming-strategy x] - (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) - -(defn as-quoted-identifier - "Given a quote pattern - either a single character or a pair of characters in - a vector - and a keyword, return the keyword as a string using a simple - quoting naming strategy. - Given a quote pattern and a string, return the string as-is. - (as-quoted-identifier X :name) will return XnameX as a string. - (as-quoted-identifier [A B] :name) will return AnameB as a string." - [q x] - (as-identifier x (partial as-quoted-str q))) - -(defmacro with-naming-strategy - "Evaluates body in the context of a naming strategy. - The naming strategy is either a function - the entity naming strategy - or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or the keyword naming strategy respectively. The default entity - naming strategy is identity; the default keyword naming strategy is lower-case." - [naming-strategy & body ] - `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) - *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) - -(defmacro with-quoted-identifiers - "Evaluates body in the context of a simple quoting naming strategy." - [q & body ] - `(binding [*as-str* (partial as-quoted-str ~q)] ~@body)) - -;; end of to-be-deprecated section +;; end of deprecated API artifacts... (defn- ^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. - Uses as-str to convert both keys and values into strings." + Uses sql/as-str to convert both keys and values into strings." [m] (let [p (Properties.)] (doseq [[k v] m] - (.setProperty p (as-str identity k) (as-str identity v))) + (.setProperty p (sql/as-str identity k) (sql/as-str identity v))) p)) (defprotocol Connectable @@ -376,9 +280,10 @@ made at some future date." } (defn result-set-seq "An alternative name for resultset-seq since result-set-seq is more consistent with the rest of java.jdbc (and resultset-seq is already a clojure.core function, albeit - with different functionality)." + with different functionality). + Note: this does not respect the dynamic *as-key* variable." [rs & {:keys [identifiers] - :or {identifiers *as-key*}}] + :or {identifiers str/lower-case}}] (resultset-seq rs :identifiers identifiers)) (defn- execute-batch @@ -476,12 +381,12 @@ made at some future date." } table-spec-str (or (and table-spec (str " " table-spec)) "") specs-to-string (fn [specs] (apply str - (map as-identifier + (map (sql/as-str identity) (apply concat (interpose [", "] (map (partial interpose " ") specs))))))] (format "CREATE TABLE %s (%s)%s" - (as-identifier name) + (sql/as-str identity name) (specs-to-string col-specs) table-spec-str))) @@ -948,7 +853,7 @@ made at some future date." } ;; technically deprecated but we don't yet have a replacement [name] (do-commands - (format "DROP TABLE %s" (as-identifier name)))) + (format "DROP TABLE %s" (sql/as-str identity name)))) (defn ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the @@ -968,8 +873,6 @@ made at some future date." } insert-rows instead. If a single set of values is inserted, returns a map of the generated keys." :deprecated "0.3.0"} - ;; technically not fully deprecated since the nil column-names case - ;; is not (yet) supported in the new API... JDBC-45 insert-values [table column-names & value-groups] (apply insert! *db* table column-names (concat value-groups [:entities *as-str*]))) @@ -1081,3 +984,103 @@ made at some future date." } with-query-results [results sql-params & body] `(with-query-results* ~sql-params (fn [~results] ~@body))) + +(defn as-key + ^{:doc "Given a naming strategy and a string, return the string as a + keyword per that naming strategy. Given (a naming strategy and) + a keyword, return it as-is." + :deprecated "0.3.0"} + [f x] + (if (instance? clojure.lang.Named x) + x + (keyword (f (str x))))) + +(defn as-keyword + ^{:doc "Given an entity name (string), convert it to a keyword using the + current naming strategy. + Given a keyword, return it as-is." + :deprecated "0.3.0"} + ([x] (as-keyword x *as-key*)) + ([x f-keyword] (as-key f-keyword x))) + +(defn as-named-keyword + ^{:doc "Given a naming strategy and a string, return the string as a keyword using + the keyword naming strategy. + Given a naming strategy and a keyword, return the keyword as-is. + The naming strategy should either be a function (the entity naming strategy) + or a map containing :entity and/or :keyword keys which provide the entity + naming strategy and/or keyword naming strategy respectively. + Note that providing a single function will cause the default keyword naming + strategy to be used!" + :deprecated "0.3.0"} + [naming-strategy x] + (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) + +(defn as-str + ^{:doc "Given a naming strategy and a keyword, return the keyword as a + string per that naming strategy. Given (a naming strategy and) + a string, return it as-is. + A keyword of the form :x.y is treated as keywords :x and :y, + both are turned into strings via the naming strategy and then + joined back together so :x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." + :deprecated "0.3.0"} + [f x] + (sql/as-str f x)) + +(defn as-identifier + ^{:doc "Given a keyword, convert it to a string using the current naming + strategy. + Given a string, return it as-is." + :deprecated "0.3.0"} + ([x] (as-identifier x *as-str*)) + ([x f-entity] (as-str f-entity x))) + +(defn as-quoted-str + ^{:doc "Given a quoting pattern - either a single character or a vector pair of + characters - and a string, return the quoted string: + (as-quoted-str X foo) will return XfooX + (as-quoted-str [A B] foo) will return AfooB" + :deprecated "0.3.0"} + [q x] + (sql/as-quoted-str q x)) + +(defn as-named-identifier + ^{:doc "Given a naming strategy and a keyword, return the keyword as a string using + the entity naming strategy. + Given a naming strategy and a string, return the string as-is. + The naming strategy should either be a function (the entity naming strategy) + or a map containing :entity and/or :keyword keys which provide the entity + naming strategy and/or keyword naming strategy respectively." + :deprecated "0.3.0"} + [naming-strategy x] + (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) + +(defn as-quoted-identifier + ^{:doc "Given a quote pattern - either a single character or a pair of characters in + a vector - and a keyword, return the keyword as a string using a simple + quoting naming strategy. + Given a quote pattern and a string, return the string as-is. + (as-quoted-identifier X :name) will return XnameX as a string. + (as-quoted-identifier [A B] :name) will return AnameB as a string." + :deprecated "0.3.0"} + [q x] + (as-identifier x (partial sql/as-quoted-str q))) + +(defmacro with-quoted-identifiers + ^{:doc "Evaluates body in the context of a simple quoting naming strategy." + :deprecated "0.3.0"} + [q & body ] + `(binding [*as-str* (partial sql/as-quoted-str ~q)] ~@body)) + +(defmacro with-naming-strategy + ^{:doc "Evaluates body in the context of a naming strategy. + The naming strategy is either a function - the entity naming strategy - or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or the keyword naming strategy respectively. The default entity + naming strategy is identity; the default keyword naming strategy is + lower-case." + :deprecated "0.3.0"} + [naming-strategy & body ] + `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) + *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) \ No newline at end of file diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 0e09b1fe..98296b45 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -29,7 +29,7 @@ and update! high-level operations within clojure.java.jdbc directly." } ;; implementation utilities -(defn- as-str +(defn as-str "Given a naming strategy and a keyword, return the keyword as a string per that naming strategy. Given (a naming strategy and) a string, return it as-is. @@ -37,23 +37,19 @@ and update! high-level operations within clojure.java.jdbc directly." } both are turned into strings via the naming strategy and then joined back together so :x.y might become `x`.`y` if the naming strategy quotes identifiers with `." - [f x] - (if (instance? clojure.lang.Named x) - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))) - (str x))) + ([f] + (fn [x] + (as-str f x))) + ([f x] + (if (instance? clojure.lang.Named x) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))) + (str x)))) -(defn- as-identifier - "Given a keyword, convert it to a string using the current naming - strategy. - Given a string, return it as-is." - [x f-entity] - (as-str f-entity x)) - -(defn- as-quoted-str +(defn as-quoted-str "Given a quoting pattern - either a single character or a vector pair of characters - and a string, return the quoted string: (as-quoted-str X foo) will return XfooX @@ -69,8 +65,8 @@ and update! high-level operations within clojure.java.jdbc directly." } [col entities] (if (map? col) (let [[k v] (first col)] - (str (as-identifier k entities) " AS " (as-identifier v entities))) - (as-identifier col entities))) + (str (as-str entities k) " AS " (as-str entities v))) + (as-str entities col))) (defn- table-str "Transform a table spec to an entity name for SQL. The table spec may be a @@ -78,8 +74,8 @@ and update! high-level operations within clojure.java.jdbc directly." } [table entities] (if (map? table) (let [[k v] (first table)] - (str (as-identifier k entities) " " (as-identifier v entities))) - (as-identifier table entities))) + (str (as-str entities k) " " (as-str entities v))) + (as-str entities table))) (def ^{:private true :doc "Symbols that need to be processed for entities within their forms."} @@ -100,11 +96,11 @@ and update! high-level operations within clojure.java.jdbc directly." } spec is not a map, the default direction is ascending." [col entities] (if (map? col) - (str (as-identifier (first (keys col)) entities) + (str (as-str entities (first (keys col))) " " (let [dir (first (vals col))] (get {:asc "ASC" :desc "DESC"} dir dir))) - (str (as-identifier col entities) " ASC"))) + (str (as-str entities col) " ASC"))) (defn- insert-multi-row "Given a table and a list of columns, followed by a list of column value sequences, @@ -212,7 +208,7 @@ and update! high-level operations within clojure.java.jdbc directly." } (str "JOIN " (table-str table entities) " ON " (str/join " AND " - (map (fn [[k v]] (str (as-identifier k entities) " = " (as-identifier v entities))) on-map)))) + (map (fn [[k v]] (str (as-str entities k) " = " (as-str entities v))) on-map)))) (defn order-by "Given a sequence of column order specs, and an optional entities spec, return the @@ -279,7 +275,7 @@ and update! high-level operations within clojure.java.jdbc directly." } " SET " (str/join "," (map (fn [k v] - (str (as-identifier k entities) + (str (as-str entities k) " = " (if (nil? v) "NULL" "?"))) ks vs)) @@ -299,7 +295,7 @@ and update! high-level operations within clojure.java.jdbc directly." } (cons (str/join " AND " (map (fn [k v] - (str (as-identifier k entities) + (str (as-str entities k) (if (nil? v) " IS NULL" " = ?"))) ks vs)) (remove nil? vs)))) From b8d54e6089808aff9b99b4b55596a21cc5f1b795 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 00:41:56 -0700 Subject: [PATCH 072/630] Remove some comments that are no longer applicable --- src/main/clojure/clojure/java/jdbc.clj | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 571a6fff..915e4dd2 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -843,14 +843,12 @@ made at some future date." } optional suffix to the CREATE TABLE DDL describing table attributes may by provided as :table-spec {table-attributes-string}. All words used to describe the table may be supplied as strings or keywords." - ;; technically deprecated but we don't yet have a replacement [name & specs] (do-commands (apply create-table-ddl name specs))) (defn drop-table "Drops a table on the open database connection given its name, a string or keyword" - ;; technically deprecated but we don't yet have a replacement [name] (do-commands (format "DROP TABLE %s" (sql/as-str identity name)))) From d14e2bff19010719b69668e631d1e773bba29e98 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 01:01:14 -0700 Subject: [PATCH 073/630] Cleanup resultset-seq / result-set-seq in preparation for extending the latter --- src/main/clojure/clojure/java/jdbc.clj | 8 +++++--- src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 915e4dd2..79209b8b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -537,7 +537,7 @@ made at some future date." } (let [counts (.executeUpdate stmt)] (try (let [rs (.getGeneratedKeys stmt) - result (first (resultset-seq rs))] + result (first (result-set-seq rs))] ;; sqlite (and maybe others?) requires ;; record set to be closed (.close rs) @@ -613,7 +613,7 @@ made at some future date." } (apply prepare-statement (get-connection db) sql prepare-args))] (set-parameters stmt params db) (with-open [rset (.executeQuery stmt)] - (func (resultset-seq rset :identifiers identifiers)))))) + (func (result-set-seq rset :identifiers identifiers)))))) ;; top-level API for actual SQL operations @@ -625,7 +625,9 @@ made at some future date." } :row-fn - applied to each row as the result set is constructed, default identity :identifiers - applied to each column name in the result set, default lower-case" [db sql-params & {:keys [result-set-fn row-fn identifiers] - :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] + :or {result-set-fn doall + row-fn identity + identifiers sql/lower-case}}] (let [query-helper (fn [db] (db-with-query-results* db (vec sql-params) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 04573865..a6d55415 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -365,7 +365,7 @@ (let [metadata (sql/with-connection db (into [] - (sql/resultset-seq + (sql/result-set-seq (-> (sql/connection) (.getMetaData) (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] From 5f02f0a750ca18a5cbe2de0516623a2a7f8b3765 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 01:06:27 -0700 Subject: [PATCH 074/630] Swap resultset-seq / result-set-seq in terms of definitive / deprecated --- src/main/clojure/clojure/java/jdbc.clj | 55 ++++++++++++-------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 79209b8b..f81d1d76 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -250,41 +250,38 @@ made at some future date." } cols (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) -(defn resultset-seq +(defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to - the rows in the java.sql.ResultSet rs. Based on clojure.core/resultset-seq - but it respects the current naming strategy. Duplicate column names are + the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq + but it respects the specified naming strategy. Duplicate column names are made unique by appending _N before applying the naming strategy (where N is a unique integer)." [^ResultSet rs & {:keys [identifiers] - :or {identifiers *as-key*}}] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (->> idxs - (map (fn [^Integer i] (.getColumnLabel rsmeta i))) - make-cols-unique + :or {identifiers str/lower-case}}] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (->> idxs + (map (fn [^Integer i] (.getColumnLabel rsmeta i))) + make-cols-unique (map (comp keyword identifiers))) - row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) - ;; This used to use create-struct (on keys) and then struct to populate each row. - ;; That had the side effect of preserving the order of columns in each row. As - ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't - ;; want to switch to records so we're using regular maps instead. We no longer - ;; guarantee column order in rows but using into {} should preserve order for up - ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying - ;; on the order-preserving behavior of structmaps, we can reconsider... - rows (fn thisfn [] - (when (.next rs) - (cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))] - (rows))) + row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) + ;; This used to use create-struct (on keys) and then struct to populate each row. + ;; That had the side effect of preserving the order of columns in each row. As + ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't + ;; want to switch to records so we're using regular maps instead. We no longer + ;; guarantee column order in rows but using into {} should preserve order for up + ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying + ;; on the order-preserving behavior of structmaps, we can reconsider... + rows (fn thisfn [] + (when (.next rs) + (cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))] + (rows))) -(defn result-set-seq - "An alternative name for resultset-seq since result-set-seq is more consistent with - the rest of java.jdbc (and resultset-seq is already a clojure.core function, albeit - with different functionality). - Note: this does not respect the dynamic *as-key* variable." - [rs & {:keys [identifiers] - :or {identifiers str/lower-case}}] - (resultset-seq rs :identifiers identifiers)) +(defn resultset-seq + "A deprecated version of result-set-seq that uses the dynamic *as-key* variable." + [^ResultSet rs & {:keys [identifiers] + :or {identifiers *as-key*}}] + (result-set-seq rs :identifiers identifiers)) (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. From 15e3c62af3fbaa2c1df1fbbd162497be71380e1c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 01:08:04 -0700 Subject: [PATCH 075/630] Clean up docstring --- src/main/clojure/clojure/java/jdbc.clj | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f81d1d76..a4135ab0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -251,11 +251,10 @@ made at some future date." } (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) (defn result-set-seq - "Creates and returns a lazy sequence of maps corresponding to - the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq - but it respects the specified naming strategy. Duplicate column names are - made unique by appending _N before applying the naming strategy (where - N is a unique integer)." + "Creates and returns a lazy sequence of maps corresponding to the rows in the + java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it + respects the specified naming strategy. Duplicate column names are made unique + by appending _N before applying the naming strategy (where N is a unique integer)." [^ResultSet rs & {:keys [identifiers] :or {identifiers str/lower-case}}] (let [rsmeta (.getMetaData rs) From 2b8185f5c6ab54e14a99010f9c8199c66cb7e7d3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 01:35:42 -0700 Subject: [PATCH 076/630] Fix JDBC-41 by adding :as-arrays option to query and result-set-seq --- src/main/clojure/clojure/java/jdbc.clj | 30 ++++++++++++++------- src/test/clojure/clojure/java/test_jdbc.clj | 12 +++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a4135ab0..1d17cc87 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -254,8 +254,8 @@ made at some future date." } "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it respects the specified naming strategy. Duplicate column names are made unique - by appending _N before applying the naming strategy (where N is a unique integer)." - [^ResultSet rs & {:keys [identifiers] + by appending _N before applying the naming strategy (where N is a unique integer)." + [^ResultSet rs & {:keys [identifiers as-arrays] :or {identifiers str/lower-case}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) @@ -271,10 +271,15 @@ made at some future date." } ;; guarantee column order in rows but using into {} should preserve order for up ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying ;; on the order-preserving behavior of structmaps, we can reconsider... + records (fn thisfn [] + (when (.next rs) + (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) rows (fn thisfn [] (when (.next rs) - (cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))] - (rows))) + (cons (vec (row-values)) (lazy-seq (thisfn)))))] + (if as-arrays + (cons (vec keys) (rows)) + (records)))) (defn resultset-seq "A deprecated version of result-set-seq that uses the dynamic *as-key* variable." @@ -585,7 +590,7 @@ made at some future date." } [options sql & params] - options and a SQL query for creating a PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." - [db sql-params func identifiers] + [db sql-params func identifiers as-arrays] (when-not (vector? sql-params) (let [^Class sql-params-class (class sql-params) ^String msg (format "\"%s\" expected %s %s, found %s %s" @@ -609,7 +614,7 @@ made at some future date." } (apply prepare-statement (get-connection db) sql prepare-args))] (set-parameters stmt params db) (with-open [rset (.executeQuery stmt)] - (func (result-set-seq rset :identifiers identifiers)))))) + (func (result-set-seq rset :identifiers identifiers :as-arrays as-arrays)))))) ;; top-level API for actual SQL operations @@ -619,8 +624,9 @@ made at some future date." } construct the result set: :result-set-fn - applied to the entire result set, default doall :row-fn - applied to each row as the result set is constructed, default identity - :identifiers - applied to each column name in the result set, default lower-case" - [db sql-params & {:keys [result-set-fn row-fn identifiers] + :identifiers - applied to each column name in the result set, default lower-case + :as-arrays - return the results as a set of arrays, default false." + [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays] :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] @@ -628,8 +634,12 @@ made at some future date." } (db-with-query-results* db (vec sql-params) (fn [rs] - (result-set-fn (map row-fn rs))) - identifiers))] + (result-set-fn (if as-arrays + (cons (first rs) + (vec (map row-fn (rest rs)))) + (map row-fn rs)))) + identifiers + as-arrays))] (if-let [con (and (map? db) (:connection db))] (query-helper db) (with-open [con (get-connection db)] diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index a6d55415..e8669ac8 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -429,6 +429,18 @@ (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) +(deftest insert-two-by-map-and-query-as-arrays + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)) + :as-arrays true)] + (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) + (is (= [[:id :name :appearance :cost :grade] + [(generated-key db 1) "Apple" nil nil nil] + [(generated-key db 2) "Pear" nil nil nil]] rows))))) + (deftest insert-two-by-cols-and-query (doseq [db (test-specs)] (sql/with-connection db From d55eacb186433e24dd6592ef36e6b7e2d197d8d1 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 7 Apr 2013 13:32:08 -0500 Subject: [PATCH 077/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-alpha1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1e97083d..fb9d1621 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-alpha1 ${project.artifactId} From 68933318c4bd248cc77b9b1422805326d1682450 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 7 Apr 2013 13:32:08 -0500 Subject: [PATCH 078/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index fb9d1621..1e97083d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-alpha1 + 0.3.0-SNAPSHOT ${project.artifactId} From 6c0ba62ef0c4cc10d0a43437f387c5483398b7c6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 15:01:28 -0700 Subject: [PATCH 079/630] Added CHANGES as markdown --- CHANGES.md | 140 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 CHANGES.md diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 00000000..a12cb78e --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,140 @@ +Changes coming in 0.3.0-alpha2 + +* Rename :as-arrays to :as-arrays? since it is boolean +* Officially deprecate resultset-seq + +Changes in 0.3.0-alpha1 + +Major overhaul of the API and deprecation of most of the old API! + +* Add insert!, query, update!, delete! and execute! high-level API + [JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20) +* Add optional SQL-generating DSL in clojure.java.jdbc.sql +* Add db- prefixed versions of low-level API +* Add db-transaction macro: +``` + (db-transaction [t-con db-spec] + (query t-con (select * :user (where {:id 42})))) +``` +* Add result-set-seq as replacement for resultset-seq (which will be deprecated) +* Transaction now correctly rollback on non-Exception Throwables + [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) +* Rewrite old API functions in terms of new API, and deprecate old API + [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) +* Add :as-arrays to query / result-set-seq + [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) +* Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) + and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) +* db-do-command allows you to execute SQL without a transaction wrapping it + [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) +* Remove reflection warning from execute-batch +* Add notes to README about 3rd party database driver dependencies +* Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy + +Changes in 0.2.3: + +* as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] +* Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) + +Changes in 0.2.2: + +* Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) +* Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) +* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) + +Changes in 0.2.1: + +* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29) +* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30) + +Changes in 0.2.0: + +* Merge internal namespace into main jdbc namespace and update symbol visibility / naming. + +Changes in 0.1.4: + +* Unwrap RTE for nested transaction exception (we already unwrapped top-level transaction RTEs). +* Remove reflection warning unwrapping RunTimeException (Alan Malloy) + +Changes in 0.1.3: + +* Fix JDBC-26 (fully) by adding transaction/generated keys support for SQLite3 (based on patch from Nelson Morris) + +Changes in 0.1.2: + +* Fix JDBC-23 by handling prepared statement params correctly (Ghadi Shayban) +* Fix JDBC-26 by adding support for SQLite3 (based on patch from Nelson Morris) +* Fix JDBC-27 by replacing replicate with repeat (Jonas Enlund) +* Ensure MS SQL Server passes tests with both Microsoft and jTDS drivers +* Build server now tests derby, hsqldb and sqlite by default +* Update README per Stuart Sierra's outline for contrib projects + +Changes in 0.1.1: + +* Fix JDBC-21 by adding support for db-spec as URI (Phil Hagelberg). +* Fix JDBC-22 by deducing driver class name from subprotocol (Phil Hagelberg). +* Add Postgres dependency so tests can be automcated (Phil Hagelberg). +* Add ability to specify test databases via TEST_DBS environment variable (Phil Hagelberg). + +Changes in 0.1.0: + +* Fix JDBC-15 by removing dependence on deprecated structmap. + +Changes in 0.0.7: + +* Fix JDBC-9 by renaming duplicate columns instead of throwing an exception. + - thanx to Peter Siewert! +* Fix JDBC-16 by ensuring do-prepared works with no param-groups provided. +* Fix JDBC-17 by adding type hints to remove more reflection warnings. + - thanx to Stuart Sierra! +Documentation: +* Address JDBC-4 by documenting how to do connection pooling. + +Changes in 0.0.6: + +* Move former tests to test-utilities namespace - these do not touch a database +* Convert old "test" examples into real tests against real databases + - tested locally against MySQL, Apache Derby, HSQLDB + - build system should run against Apache Derby, HSQLSB + - will add additional databases later +* Fix JDBC-12 by removing batch when doing a single update +* Remove wrapping of exceptions in transactions to make it easier to work with SQLExceptions + +Changes in 0.0.5: + +* Add prepare-statement function to ease creation of PreparedStatement with common options: + - see docstring for details +* with-query-results now allows the SQL/params vector to be: + - a PreparedStatement object, followed by any parameters the SQL needs + - a SQL query string, followed by any parameters it needs + - options (for prepareStatement), a SQL query string, followed by any parameters it needs +* Add support for databases that cannot return generated keys (e.g., HSQLDB) + - insert operations silently return the insert counts instead of generated keys + - it is the user's responsibility to handle this if you're using such a database! + +Changes in 0.0.4: + +* Fix JDBC-2 by allowing :table-spec {string} at the end of create-table arguments: + (sql/create-table :foo [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM") +* Fix JDBC-8 by removing all reflection warnings +* Fix JDBC-11 by no longer committing the transaction when an Error occurs +* Clean up as-... functions to reduce use of (binding) +* Refactor do-prepared*, separating out return keys logic and parameter setting logic + - in preparation for exposing more hooks in PreparedStatement creation / manipulation + +Changes in 0.0.3: + +* Fix JDBC-10 by using .executeUpdate when generating keys (MS SQL Server, PostgreSQL compatibility issue) + +Changes in 0.0.2: + +* Fix JDBC-7 Clojure 1.2 compatibility (thanx to Aaron Bedra!) + +Changes in 0.0.1 (compared to clojure.contrib.sql): + +* Exposed print-... functions for exception printing; no longer writes exceptions to *out* +* Add clojure.java.jdbc/resultset-seq (to replace clojure.core/resultset-seq which should be deprecated) +* Add support for naming and quoting strategies - see http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/NameMapping.html + - The formatting is a bit borked, Tom F knows about this and is working on an enhancement to auto-doc to improve it +* Add ability to return generated keys from single insert operations, add insert-record function +* Clojure 1.3 compatibility From c03f25572e689d49d2111ed313b98c7bfe1cf027 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 15:06:57 -0700 Subject: [PATCH 080/630] Remove text version of CHANGES --- CHANGES.md | 4 +- CHANGES.txt | 109 ---------------------------------------------------- 2 files changed, 3 insertions(+), 110 deletions(-) delete mode 100644 CHANGES.txt diff --git a/CHANGES.md b/CHANGES.md index a12cb78e..ead2f2ac 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -9,13 +9,15 @@ Major overhaul of the API and deprecation of most of the old API! * Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20) -* Add optional SQL-generating DSL in clojure.java.jdbc.sql +* Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20) * Add db- prefixed versions of low-level API * Add db-transaction macro: + ``` (db-transaction [t-con db-spec] (query t-con (select * :user (where {:id 42})))) ``` + * Add result-set-seq as replacement for resultset-seq (which will be deprecated) * Transaction now correctly rollback on non-Exception Throwables [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) diff --git a/CHANGES.txt b/CHANGES.txt deleted file mode 100644 index 12ae18e5..00000000 --- a/CHANGES.txt +++ /dev/null @@ -1,109 +0,0 @@ -Changes in 0.3.0-SNAPSHOT -* Remove reflection warning from execute-batch -* Add notes to README about 3rd party database driver dependencies -* Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy - -Changes in 0.2.3: -* as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] -* Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) - -Changes in 0.2.2: -* Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) -* Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) -* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) - -Changes in 0.2.1: -* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29) -* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30) - -Changes in 0.2.0: - -* Merge internal namespace into main jdbc namespace and update symbol visibility / naming. - -Changes in 0.1.4: - -* Unwrap RTE for nested transaction exception (we already unwrapped top-level transaction RTEs). -* Remove reflection warning unwrapping RunTimeException (Alan Malloy) - -Changes in 0.1.3: - -* Fix JDBC-26 (fully) by adding transaction/generated keys support for SQLite3 (based on patch from Nelson Morris) - -Changes in 0.1.2: - -* Fix JDBC-23 by handling prepared statement params correctly (Ghadi Shayban) -* Fix JDBC-26 by adding support for SQLite3 (based on patch from Nelson Morris) -* Fix JDBC-27 by replacing replicate with repeat (Jonas Enlund) -* Ensure MS SQL Server passes tests with both Microsoft and jTDS drivers -* Build server now tests derby, hsqldb and sqlite by default -* Update README per Stuart Sierra's outline for contrib projects - -Changes in 0.1.1: - -* Fix JDBC-21 by adding support for db-spec as URI (Phil Hagelberg). -* Fix JDBC-22 by deducing driver class name from subprotocol (Phil Hagelberg). -* Add Postgres dependency so tests can be automcated (Phil Hagelberg). -* Add ability to specify test databases via TEST_DBS environment variable (Phil Hagelberg). - -Changes in 0.1.0: - -* Fix JDBC-15 by removing dependence on deprecated structmap. - -Changes in 0.0.7: - -* Fix JDBC-9 by renaming duplicate columns instead of throwing an exception. - - thanx to Peter Siewert! -* Fix JDBC-16 by ensuring do-prepared works with no param-groups provided. -* Fix JDBC-17 by adding type hints to remove more reflection warnings. - - thanx to Stuart Sierra! -Documentation: -* Address JDBC-4 by documenting how to do connection pooling. - -Changes in 0.0.6: - -* Move former tests to test-utilities namespace - these do not touch a database -* Convert old "test" examples into real tests against real databases - - tested locally against MySQL, Apache Derby, HSQLDB - - build system should run against Apache Derby, HSQLSB - - will add additional databases later -* Fix JDBC-12 by removing batch when doing a single update -* Remove wrapping of exceptions in transactions to make it easier to work with SQLExceptions - -Changes in 0.0.5: - -* Add prepare-statement function to ease creation of PreparedStatement with common options: - - see docstring for details -* with-query-results now allows the SQL/params vector to be: - - a PreparedStatement object, followed by any parameters the SQL needs - - a SQL query string, followed by any parameters it needs - - options (for prepareStatement), a SQL query string, followed by any parameters it needs -* Add support for databases that cannot return generated keys (e.g., HSQLDB) - - insert operations silently return the insert counts instead of generated keys - - it is the user's responsibility to handle this if you're using such a database! - -Changes in 0.0.4: - -* Fix JDBC-2 by allowing :table-spec {string} at the end of create-table arguments: - (sql/create-table :foo [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM") -* Fix JDBC-8 by removing all reflection warnings -* Fix JDBC-11 by no longer committing the transaction when an Error occurs -* Clean up as-... functions to reduce use of (binding) -* Refactor do-prepared*, separating out return keys logic and parameter setting logic - - in preparation for exposing more hooks in PreparedStatement creation / manipulation - -Changes in 0.0.3: - -* Fix JDBC-10 by using .executeUpdate when generating keys (MS SQL Server, PostgreSQL compatibility issue) - -Changes in 0.0.2: - -* Fix JDBC-7 Clojure 1.2 compatibility (thanx to Aaron Bedra!) - -Changes in 0.0.1 (compared to clojure.contrib.sql): - -* Exposed print-... functions for exception printing; no longer writes exceptions to *out* -* Add clojure.java.jdbc/resultset-seq (to replace clojure.core/resultset-seq which should be deprecated) -* Add support for naming and quoting strategies - see http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/NameMapping.html - - The formatting is a bit borked, Tom F knows about this and is working on an enhancement to auto-doc to improve it -* Add ability to return generated keys from single insert operations, add insert-record function -* Clojure 1.3 compatibility From 83fdbc8140b6e56bbf7842a3ef459c43dd614b76 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 17:32:50 -0700 Subject: [PATCH 081/630] Rename as-arrays to as-arrays? since it is boolean. Add curried as-quoted-str and simplify code that depends on it. --- src/main/clojure/clojure/java/jdbc.clj | 26 ++++++++++++---------- src/main/clojure/clojure/java/jdbc/sql.clj | 15 ++++++++----- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1d17cc87..97bf7398 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -255,7 +255,7 @@ made at some future date." } java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it respects the specified naming strategy. Duplicate column names are made unique by appending _N before applying the naming strategy (where N is a unique integer)." - [^ResultSet rs & {:keys [identifiers as-arrays] + [^ResultSet rs & {:keys [identifiers as-arrays?] :or {identifiers str/lower-case}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) @@ -277,12 +277,14 @@ made at some future date." } rows (fn thisfn [] (when (.next rs) (cons (vec (row-values)) (lazy-seq (thisfn)))))] - (if as-arrays + (if as-arrays? (cons (vec keys) (rows)) (records)))) (defn resultset-seq - "A deprecated version of result-set-seq that uses the dynamic *as-key* variable." + ^{doc: "A deprecated version of result-set-seq that uses the + dynamic *as-key* variable." + :deprecated "0.3.0"} [^ResultSet rs & {:keys [identifiers] :or {identifiers *as-key*}}] (result-set-seq rs :identifiers identifiers)) @@ -590,7 +592,7 @@ made at some future date." } [options sql & params] - options and a SQL query for creating a PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." - [db sql-params func identifiers as-arrays] + [db sql-params func identifiers as-arrays?] (when-not (vector? sql-params) (let [^Class sql-params-class (class sql-params) ^String msg (format "\"%s\" expected %s %s, found %s %s" @@ -614,7 +616,7 @@ made at some future date." } (apply prepare-statement (get-connection db) sql prepare-args))] (set-parameters stmt params db) (with-open [rset (.executeQuery stmt)] - (func (result-set-seq rset :identifiers identifiers :as-arrays as-arrays)))))) + (func (result-set-seq rset :identifiers identifiers :as-arrays? as-arrays?)))))) ;; top-level API for actual SQL operations @@ -625,8 +627,8 @@ made at some future date." } :result-set-fn - applied to the entire result set, default doall :row-fn - applied to each row as the result set is constructed, default identity :identifiers - applied to each column name in the result set, default lower-case - :as-arrays - return the results as a set of arrays, default false." - [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays] + :as-arrays? - return the results as a set of arrays, default false." + [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] @@ -634,12 +636,12 @@ made at some future date." } (db-with-query-results* db (vec sql-params) (fn [rs] - (result-set-fn (if as-arrays + (result-set-fn (if as-arrays? (cons (first rs) (vec (map row-fn (rest rs)))) (map row-fn rs)))) identifiers - as-arrays))] + as-arrays?))] (if-let [con (and (map? db) (:connection db))] (query-helper db) (with-open [con (get-connection db)] @@ -668,7 +670,7 @@ made at some future date." } column names in the map (default 'as-is') and whether to run the delete in a transaction (default true). Example: - (delete! db :person {:zip 94546}) + (delete! db :person (where {:zip 94546})) is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" [db table where-clause & {:keys [entities transaction?] @@ -1071,13 +1073,13 @@ made at some future date." } (as-quoted-identifier [A B] :name) will return AnameB as a string." :deprecated "0.3.0"} [q x] - (as-identifier x (partial sql/as-quoted-str q))) + (as-identifier x (sql/as-quoted-str q))) (defmacro with-quoted-identifiers ^{:doc "Evaluates body in the context of a simple quoting naming strategy." :deprecated "0.3.0"} [q & body ] - `(binding [*as-str* (partial sql/as-quoted-str ~q)] ~@body)) + `(binding [*as-str* (sql/as-quoted-str ~q)] ~@body)) (defmacro with-naming-strategy ^{:doc "Evaluates body in the context of a naming strategy. diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 98296b45..34d95d1b 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -54,10 +54,13 @@ and update! high-level operations within clojure.java.jdbc directly." } characters - and a string, return the quoted string: (as-quoted-str X foo) will return XfooX (as-quoted-str [A B] foo) will return AfooB" - [q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q))) + ([q] + (fn [x] + (as-quoted-str q x))) + ([q x] + (if (vector? q) + (str (first q) x (last q)) + (str q x q)))) (defn- col-str "Transform a column spec to an entity name for SQL. The column spec may be a @@ -160,11 +163,11 @@ and update! high-level operations within clojure.java.jdbc directly." } (concat form [:identifiers identifiers]) form)) sql)) -;; some common quoting strategies +;; some common entity/identifier strategies (def as-is identity) (def lower-case str/lower-case) -(defn quoted [q] (partial as-quoted-str q)) +(defn quoted [q] (as-quoted-str q)) ;; SQL generation functions From f966a84ec05fa729012b74526c0891fc12b8748d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 17:33:23 -0700 Subject: [PATCH 082/630] Update README to 0.3.0-alpha1 and update all docs to show new API instead of old API --- README.md | 44 ++++-- doc/clojure/java/jdbc/NameMapping.md | 53 +++---- doc/clojure/java/jdbc/UsingDDL.md | 11 +- doc/clojure/java/jdbc/UsingSQL.md | 203 +++++++++++++-------------- 4 files changed, 158 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index 3cf29f88..9270e1d7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Formerly known as clojure.contrib.sql. Releases and Dependency Information ======================================== -Latest stable release: 0.2.3 +Latest stable release: 0.3.0-alpha1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -16,14 +16,14 @@ Latest stable release: 0.2.3 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.2.3"] +[org.clojure/java.jdbc "0.3.0-alpha1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.2.3 + 0.3.0-alpha1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -52,22 +52,23 @@ has to be downloaded manually and placed in a Maven repository accessible to you Example Usage ======================================== ```clojure -(require '[clojure.java.jdbc :as sql]) +(require '[clojure.java.jdbc :as j] + '[clojure.java.jdbc.sql :as s]) (def mysql-db {:subprotocol "mysql" :subname "//127.0.0.1:3306/clojure_test" :user "clojure_test" :password "clojure_test"}) -(sql/with-connection mysql-db - (sql/insert-records :fruit - {:name "Apple" :appearance "rosy" :cost 24} - {:name "Orange" :appearance "round" :cost 49})) +(j/insert! mysql-db :fruit + {:name "Apple" :appearance "rosy" :cost 24} + {:name "Orange" :appearance "round" :cost 49}) +;; ({:generated_key 1} {:generated_key 2}) -(sql/with-connection mysql-db - (sql/with-query-results rows - ["SELECT * FROM fruit WHERE appearance = ?" "rosy"] - (:cost (first rows)))) +(j/query mysql-db + (s/select * :fruit (s/where {:appearance "rosy"})) + :row-fn :cost) +;; (24) ``` For more detail see the [generated documentation on github](http://clojure.github.com/java.jdbc/). @@ -103,6 +104,23 @@ Developer Information Change Log ==================== +* Release 0.3.0-alpha1 on 2013-04-07 + * MAJOR API OVERHAUL! + * Most of the old 0.2.x API has been deprecated and a new, more idiomatic API introduced, along with a minimal DSL to generate basic SQL + * Specifics: + * Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20) + * Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20) + * Add db- prefixed versions of low-level API + * Add db-transaction macro + * Add result-set-seq as replacement for resultset-seq (which will be deprecated) + * Transaction now correctly rollback on non-Exception Throwables [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) + * Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) + * Add :as-arrays to query / result-set-seq [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) + * Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) + * db-do-command allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) + * Remove reflection warning from execute-batch + * Add notes to README about 3rd party database driver dependencies + * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy * Release 0.2.3 on 2012-06-18 * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] * Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) @@ -166,7 +184,7 @@ Change Log Copyright and License ======================================== -Copyright (c) Stephen Gilardi, Sean Corfield, 2011-2012. All rights reserved. The use and +Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2013. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. diff --git a/doc/clojure/java/jdbc/NameMapping.md b/doc/clojure/java/jdbc/NameMapping.md index 21eefa61..35499780 100644 --- a/doc/clojure/java/jdbc/NameMapping.md +++ b/doc/clojure/java/jdbc/NameMapping.md @@ -1,36 +1,39 @@ # Mapping Keywords to/from Entity Names Entity names in SQL may be specified as strings or as keywords. It's convenient to represent records as Clojure maps with keywords for the keys but this means that a mapping is required when moving from Clojure to SQL and back again. Historically, clojure.contrib.sql simply called (name) on keywords passed in and used clojure.core/resultset-seq to convert Java ResultSet objects back to Clojure maps, which had the side-effect of lowercasing all entity names as they became keywords. Whilst that is still the default behavior of clojure.java.jdbc, it is now possible to override this behavior in a couple of ways. -## Quoted Identifiers -The first problem that the old approach exposed was when table names or column names were the same as a SQL keyword. Databases provide a way to quote identifier names so that entity names do not get treated as SQL keywords (often referred to as 'stropping'). Unfortunately, the way quoting works tends to be vendor-specific so that Microsoft SQL Server accepts \[name\] and "name" whilst MySQL traditionally uses \`name\` (although recent versions also accept "name"). In order to support multiple approaches to quoted, clojure.java.jdbc now has a function *as-quoted-identifier* and a macro *with-quoted-identifiers* to allow you to specify how quoting should be handled. +## Quoted Entities +The first problem that the old approach exposed was when table names or column names were the same as a SQL keyword. Databases provide a way to quote identifier names so that entity names do not get treated as SQL keywords (often referred to as 'stropping'). Unfortunately, the way quoting works tends to be vendor-specific so that Microsoft SQL Server accepts \[name\] and "name" whilst MySQL traditionally uses \`name\` (although recent versions also accept "name"). In order to support multiple approaches to quoting, clojure.java.jdbc supports the concept of identifier functions and entity functions. The former are used to convert entity names in result sets into Clojure identifiers. The latter are used to convert Clojure identifiers (table names, keys in maps) into SQL entity names. + +The function clojure.java.jdbc.sql/quoted can be used to create an entity function. It takes a quote spec and returns a function that will quote its argument appropriately. Other entity functions are clojure.java.jdbc.sql/as-is which leaves names untouched (and is the default) and clojure.java.jdbc.sql/lower-case which lowercases name (and is the default identifier function for result-set-seq. A quote spec is either a single character or a pair of characters in a vector. For the former, the entity name is wrapped in a pair of that character. For the latter, the entity name is wrapped in the specified pair: - (as-quoted-identifier \` :name) ;; produces "`name`" - (as-quoted-identifier [[ ]] :name) ;; produces "[name]" + ((s/quoted \`) "name") ;; produces "`name`" + ((s/quoted [\[ \]]) "name") ;; produces "[name]" + +Code can either be passed an entity function or be wrapped in the *entities* macro to influence how keywords are mapped to entity names: -Any code can be wrapped in the *with-quoted-identifiers* macro to influence how keywords are mapped to entity names: + (j/insert! mysql-db :fruit + {:name "Pear" :appearance "green" :cost 99} + :entities (s/quoted \`)) + + (s/entities (s/quoted \`) + (j/insert! mysql-db :fruit + {:name "Pear" :appearance "green" :cost 99})) - (sql/with-quoted-identifiers \` - (sql/insert-record - :fruit - { :name "Pear" :appearance "green" :cost 99})) ;; INSERT INTO `fruit` ( `name`, `appearance`, `cost` ) ;; VALUES ( 'Pear', 'green', 99 ) Note that if a string is used for an entity name, rather than a keyword, it is passed through unchanged, on the assumption that if you're explicitly passing strings, you want to control exactly what goes into the SQL. -## Naming Strategies -The second problem with the old approach was that in returned results, all entity names were mapped to lowercase so any case sensitivity in the original entity names was lost. In addition to the option to determine a quoting strategy, clojure.java.jdbc now has functions *as-named-identifier*, *as-named-keyword* and a macro *with-naming-strategy* to allow you to specify how entity name / keyword mapping should be performed in both directions. - -A naming strategy may be a single function or a map containing the keys `:entity` and/or `:keyword`, whose values are functions. If a single function `f` is provided, it is treated as `{ :entity f }`, i.e., an entity naming strategy. The `:entity` mapping is used on keywords that need to be converted to entity names. The `:keyword` mapping is used on entity names that need to be converted to keywords. - - (as-named-identifier clojure.string/upper-case :name) ;; produces "NAME" - (def quote-dash - { :entity (partial as-quoted-str \`) :keyword #(.replace % "_" "-") }) - (as-named-identifier quote-dash :name) ;; produces "`name`" - (as-named-keyword quote-dash "item_id") ;; produces :item-id - -The default naming strategy is `{ :entity identity :keyword clojure.string/lower-case }`. clojure.java.jdbc provides its own version of *resultset-seq* that respects the current naming strategy (for entity names mapped to keywords). You cannot specify a naming strategy that produces strings instead of keywords (but you could use a keyword naming strategy of *identity* to preserve case and spelling). -## Convenience Functions -In addition to *as-quoted-identifier*, *as-named-identifier* and *as-named-keyword* described above, clojure.java.jdbc exposes *as-identifier* which maps strings/keywords to entity names under the current naming strategy and *as-keyword* which maps strings/keywords to keywords under the current naming strategy. - -The core of the quoting strategy is also exposed as *as-quoted-str* (shown in the `quote-dash` example above). \ No newline at end of file +## Entity to Identifier +The second problem with the old approach was that in returned results, all entity names were mapped to lowercase so any case sensitivity in the original entity names was lost. In addition to the option to determine a quoting strategy, clojure.java.jdbc support identifier functions for *query* and *result-set-seq*. + + (j/query mysql-db + (s/select * :fruit) + :identifiers clojure.string/upper-case) + + (s/identifiers clojure.string/upper-case + (j/query mysql-db + (s/select * :fruit))) + + ;; ({:GRADE nil, :COST 24, :APPEARANCE "rosy", :NAME "Apple", :ID 1} + ;; ...) diff --git a/doc/clojure/java/jdbc/UsingDDL.md b/doc/clojure/java/jdbc/UsingDDL.md index e7589a1c..03a236d3 100644 --- a/doc/clojure/java/jdbc/UsingDDL.md +++ b/doc/clojure/java/jdbc/UsingDDL.md @@ -28,10 +28,9 @@ To retrieve the metadata for a table, you can operate on the connection itself. (defn db-get-tables "Demonstrate getting table info" - [] - (sql/with-connection db - (into [] - (sql/resultset-seq - (-> (sql/connection) + [db] + (into [] + (j/result-set-seq + (-> (j/get-connection db) (.getMetaData) - (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))) + (.getTables nil nil nil (into-array ["TABLE" "VIEW"])))))) diff --git a/doc/clojure/java/jdbc/UsingSQL.md b/doc/clojure/java/jdbc/UsingSQL.md index 3a7d593d..5b9ddbc8 100644 --- a/doc/clojure/java/jdbc/UsingSQL.md +++ b/doc/clojure/java/jdbc/UsingSQL.md @@ -2,47 +2,49 @@ Here are some examples of using clojure.java.jdbc to manipulate data with SQL. These examples assume a simple table called fruit (see [Manipulating Tables with DDL](https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/UsingDDL.md)). ## Inserting multiple rows -If you want to insert complete rows, you can use *insert-rows* and provide the values as a simple vector for each row. Every column's value must be present in the same order the columns are declared in the table. This performs a single insert statement. If you attempt to insert a single row, a map of the generated keys will be returned. +If you want to insert complete rows, you can use *insert!* and provide the values as a simple vector for each row. Every column's value must be present in the same order the columns are declared in the table. This performs a series of insert statement. If you attempt to insert a single row, a map of the generated keys will be returned. (defn insert-rows-fruit "Insert complete rows" - [] - (sql/insert-rows + [db] + (j/insert! db :fruit - ["Apple" "red" 59 87] - ["Banana" "yellow" 29 92.2] - ["Peach" "fuzzy" 139 90.0] - ["Orange" "juicy" 89 88.6])) + nil ; column names not supplied + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])) + ;; (1 1 1 1) - row counts modified ## Inserting partial rows -If you want to insert rows but only specify some columns' values, you can use *insert-values* and provide the names of the columns following by vectors containing values for those columns. This performs a single insert statement. If you attempt to insert a single row, a map of the generated keys will be returned. +If you want to insert rows but only specify some columns' values, you can use *insert!* and provide the names of the columns following by vectors containing values for those columns. This performs a single insert statement. If you attempt to insert a single row, a map of the generated keys will be returned. (defn insert-values-fruit "Insert rows with values for only specific columns" - [] - (sql/insert-values + [db] + (j/insert! db :fruit [:name :cost] ["Mango" 722] ["Feijoa" 441])) ## Inserting a record -If you want to insert a single record, you can use *insert-record* and specify the columns and their values as a map. This performs a single insert statement. A map of the generated keys will be returned. +If you want to insert a single record, you can use *insert!* and specify the columns and their values as a map. This performs a single insert statement. A map of the generated keys will be returned. (defn insert-record-fruit "Insert a single record, map from keys specifying columsn to values" - [] - (sql/insert-record + [db] + (j/insert! db :fruit {:name "Pear" :appearance "green" :cost 99})) ## Inserting multiple records -If you want to insert multiple records, you can use *insert-records* and specify each record as a map of columns and their values. This performs a separate insert statement for each record. The generated keys are returned in a sequence of maps. +If you want to insert multiple records, you can use *insert!* and specify each record as a map of columns and their values. This performs a separate insert statement for each record. The generated keys are returned in a sequence of maps. (defn insert-records-fruit "Insert records, maps from keys specifying columns to values" - [] - (sql/insert-records + [db] + (j/insert! db :fruit {:name "Pomegranate" :appearance "fresh" :cost 585} {:name "Kiwifruit" :grade 93})) @@ -52,143 +54,126 @@ You can write multiple operations in a transaction to ensure they are either all (defn db-write "Write initial values to the database as a transaction" - [] - (sql/with-connection db - (sql/transaction - (drop-fruit) - (create-fruit) - (insert-rows-fruit) - (insert-values-fruit) - (insert-records-fruit))) - nil) + [db] + (j/db-transaction [t-con db] + (insert-rows-fruit t-con) + (insert-values-fruit t-con) + (insert-records-fruit t-con))) + +The *db-transaction* macro creates a transaction-aware connection from the database specification and that should be used in the body of the transaction code. ## Reading and processing rows -To execute code against each row in a result set, use *with-query-results* with SQL. +To execute code against each row in a result set, use *query* with SQL. (defn db-read "Read the entire fruit table" - [] - (sql/with-connection db - (sql/with-query-results res - ["SELECT * FROM fruit"] - (doseq [rec res] - (println rec))))) + [db] + (j/query db + ["SELECT * FROM fruit"] + :row-fn println)) (defn db-read-all "Return all the rows of the fruit table as a vector" - [] - (sql/with-connection db - (sql/with-query-results res - ["SELECT * FROM fruit"] - (into [] res)))) + [db] + (j/query db + ["SELECT * FROM fruit"] + :as-arrays? true)) + + ;; ([:id :name :appearance :cost :grade] + ;; [1 "Apple" "red" 59 87.0] + ;; [2 "Banana" "yellow" 29 92.2] + ;; ...) (defn db-grade-range "Print rows describing fruit that are within a grade range" - [min max] - (sql/with-connection db - (sql/with-query-results res - [(str "SELECT name, cost, grade " - "FROM fruit " - "WHERE grade >= ? AND grade <= ?") - min max] - (doseq [rec res] - (println rec))))) + [db min max] + (j/query db + [(str "SELECT name, cost, grade " + "FROM fruit " + "WHERE grade >= ? AND grade <= ?") + min max] + :row-fn println)) (defn db-grade-a "Print rows describing all grade a fruit (grade between 90 and 100)" - [] - (db-grade-range 90 100)) + [db] + (db-grade-range db 90 100)) ## Updating values across a table -To update column values based on a SQL predicate, use *update-values* with a SQL where clause and a map of columns to new values. The result is a sequence of update counts, indicating the number of records affected by each update (in this case, a single update and therefore a single count in the sequence). +To update column values based on a SQL predicate, use *update!* with a SQL where clause and a map of columns to new values. The result is a sequence of update counts, indicating the number of records affected by each update (in this case, a single update and therefore a single count in the sequence). (defn db-update-appearance-cost "Update the appearance and cost of the named fruit" - [name appearance cost] - (sql/update-values + [db name appearance cost] + (j/update! mysql-db :fruit - ["name=?" name] - {:appearance appearance :cost cost})) + {:appearance appearance :cost cost} + ["name=?" name])) (defn db-update "Update two fruits as a transaction" - [] - (sql/with-connection db - (sql/transaction - (db-update-appearance-cost "Banana" "bruised" 14) - (db-update-appearance-cost "Feijoa" "green" 400))) - nil) + [db] + (j/db-transaction [t-con db] + (db-update-appearance-cost t-con "Banana" "bruised" 14) + (db-update-appearance-cost t-con "Feijoa" "green" 400))) ## Updating values or Inserting records conditionally -If you want to update existing records that match a SQL predicate or insert a new record if no existing records match, use *update-or-insert-values* with a SQL where clause and a map of columns to values. This calls *update-values* first and if no rows were updated, this calls *insert-values*. The result is either the sequence of update counts from the update or the sequence of generated key maps from the insert. +If you want to update existing records that match a SQL predicate or insert a new record if no existing records match, you can use a transaction wrapped around an *update!* and a conditional *insert!*. +use *update-or-insert-values* with a SQL where clause and a map of columns to values. This calls *update-values* first and if no rows were updated, this calls *insert-values*. The result is either the sequence of update counts from the update or the sequence of generated key maps from the insert. (defn db-update-or-insert "Updates or inserts a fruit" - [record] - (sql/with-connection db - (sql/update-or-insert-values - :fruit - ["name=?" (:name record)] - record))) + [db record where-clause] + (j/db-transaction [t-con db] + (let [result (j/update! t-con :fruit record where-clause)] + (if (zero? (first result)) + (j/insert! t-con :fruit record) + result)))) + + (db-update-or-insert mysql-db + {:name "Cactus" :appearance "Spiky" :cost 2000} + ["name = ?" "Cactus"]) + ;; inserts Cactus + (db-update-or-insert mysql-db + {:name "Cactus" :appearance "Spiky" :cost 2500} + ["name = ?" "Cactus"]) + ;; updates the Cactus we just inserted ## Exception Handling and Transaction Rollback Transactions are rolled back if an exception is thrown, as shown in these examples. (defn db-exception "Demonstrate rolling back a partially completed transaction on exception" - [] - (sql/with-connection db - (sql/transaction - (sql/insert-values + [db] + (j/db-transaction [t-con db] + (j/insert! t-con :fruit [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"]) - ;; at this point the insert-values call is complete, but the transaction - ;; is not. the exception will cause it to roll back leaving the database - ;; untouched. - (throw (Exception. "sql/test exception"))))) - - (defn db-sql-exception - "Demonstrate an sql exception" - [] - (sql/with-connection db - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"])))) - - (defn db-batchupdate-exception - "Demonstrate a batch update exception" - [] - (sql/with-connection db - (sql/transaction - (sql/do-commands - "DROP TABLE fruit" - "DROP TABLE fruit")))) - + ;; at this point the insert-values call is complete, but the transaction + ;; is not. the exception will cause it to roll back leaving the database + ;; untouched. + (throw (Exception. "sql/test exception"))))) + +Transactions can also be set explicitly to rollback instead of commit: + (defn db-rollback "Demonstrate a rollback-only trasaction" - [] - (sql/with-connection db - (sql/transaction - (prn "is-rollback-only" (sql/is-rollback-only)) - (sql/set-rollback-only) - (sql/insert-values + [db] + (j/db-transaction [t-con db] + (prn "is-rollback-only" (j/db-is-rollback-only t-con)) + (j/db-set-rollback-only! t-con) + (j/insert! t-con :fruit [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"]) - (prn "is-rollback-only" (sql/is-rollback-only)) - (sql/with-query-results res + (prn "is-rollback-only" (j/db-is-rollback-only t-con)) + (j/query t-con ["SELECT * FROM fruit"] - (doseq [rec res] - (println rec)))) + :row-fn println)) (prn) - (sql/with-query-results res + (j/query db ["SELECT * FROM fruit"] - (doseq [rec res] - (println rec))))) + :row-fn println)) From dc4be40faa3ce9349b8fa4fb849ed14f6ec30c7d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 7 Apr 2013 17:35:46 -0700 Subject: [PATCH 083/630] Updated CHANGES with as-quoted-str (coming in alpha2) --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index ead2f2ac..bebbb0d1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.0-alpha2 * Rename :as-arrays to :as-arrays? since it is boolean +* Add curried version of clojure.java.jdbc.sql/as-quoted-str * Officially deprecate resultset-seq Changes in 0.3.0-alpha1 From b0c6bda7fb107c15050d15a15af96a242878d5b5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 8 Apr 2013 09:03:32 -0700 Subject: [PATCH 084/630] Fix typo in docstring metadata --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 97bf7398..ab73402e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -282,7 +282,7 @@ made at some future date." } (records)))) (defn resultset-seq - ^{doc: "A deprecated version of result-set-seq that uses the + ^{:doc "A deprecated version of result-set-seq that uses the dynamic *as-key* variable." :deprecated "0.3.0"} [^ResultSet rs & {:keys [identifiers] From eb66bff79ef224b8854a986e51bdb38bc7f7ada6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 17 Apr 2013 17:59:01 -0700 Subject: [PATCH 085/630] Revert JDBC-40 so MySQL is no longer a special case and PostgreSQL should no longer be broken (for MONEY type) --- src/main/clojure/clojure/java/jdbc.clj | 29 +++----------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ab73402e..bb1bad60 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -117,18 +117,6 @@ made at some future date." } (def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols {"postgres" "postgresql"}) -(defn- mysql? - "Given a db spec, return true if it represents MySQL. This is used for set-parameters." - [db] - (cond (string? db) - (re-find #"mysql:" db) - - (:subprotocol db) - (= "mysql" (:subprotocol db)) - - (:connection db) - (.startsWith (.getName (type (:connection db))) "com.mysql."))) - (defn- parse-properties-uri [^URI uri] (let [host (.getHost uri) port (if (pos? (.getPort uri)) (.getPort uri)) @@ -359,20 +347,9 @@ made at some future date." } "Add the parameters to the given statement. Use parameter metadata if it is available, which allows us to specify the SQL type and support NULL better." [^PreparedStatement stmt params db] - (let [^ParameterMetaData metadata (when-not (mysql? db) - (try (.getParameterMetaData stmt) - (catch SQLException _)))] - (dorun (map-indexed (fn [ix value] - (let [ix* (inc ix) - sql-type (when metadata - (try (.getParameterType metadata ix*) - (catch SQLException _)))] - (if sql-type - (if (nil? value) - (.setNull stmt ix* sql-type) - (.setObject stmt ix* value)) - (.setObject stmt ix* value)))) - params)))) + (dorun (map-indexed (fn [ix value] + (.setObject stmt (inc ix) value)) + params))) (defn create-table-ddl "Given a table name and column specs with an optional table-spec From d046fee9403932426a2124569e7f440bfe75042c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 17 Apr 2013 17:59:20 -0700 Subject: [PATCH 086/630] Correct test to use :as-arrays? instead of :as-arrays --- src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index e8669ac8..77ff9724 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -435,7 +435,7 @@ (create-test-table :fruit db)) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)) - :as-arrays true)] + :as-arrays? true)] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [[:id :name :appearance :cost :grade] [(generated-key db 1) "Apple" nil nil nil] From 039432e18a76742f0275d3854863e3cba5377514 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 17 Apr 2013 18:07:58 -0700 Subject: [PATCH 087/630] Note the revert of JDBC-40 --- CHANGES.md | 2 ++ README.md | 1 + 2 files changed, 3 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index bebbb0d1..16202d77 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha2 +* Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean * Add curried version of clojure.java.jdbc.sql/as-quoted-str * Officially deprecate resultset-seq @@ -28,6 +29,7 @@ Major overhaul of the API and deprecation of most of the old API! [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) * Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) + Note: JDBC-40 has been reverted in 0.3.0-alpha2 because it introduced regressions for PostgreSQL * db-do-command allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) * Remove reflection warning from execute-batch diff --git a/README.md b/README.md index 9270e1d7..802e3615 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ Change Log * Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) * Add :as-arrays to query / result-set-seq [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) * Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) + Note: JDBC-40 is being reverted in 0.3.0-alpha2 because it introduces regressions in PostgreSQL * db-do-command allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies From 35e96ec0a3dc9efc63a0fcb7db35c3f0b20a7ce4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 19 Apr 2013 19:16:32 -0700 Subject: [PATCH 088/630] Add desired behavior tests for JDBC-52 (execute! ... :multi? true/false) --- src/test/clojure/clojure/java/test_jdbc.clj | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 77ff9724..ec5d3e68 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -554,3 +554,33 @@ (is (= 1 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-execute!-fails-with-multi-param-groups + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + ;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException + (is (thrown? Exception + (sql/execute! + db + ["INSERT INTO fruit (name,appearance) VALUES (?,?)" + ["Apple" "rosy"] + ["Pear" "yellow"] + ["Orange" "round"]]))))) + +(deftest test-execute!-with-multi?-true-param-groups + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db)) + ;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException + (let [counts (sql/execute! + db + ["INSERT INTO fruit (name,appearance) VALUES (?,?)" + ["Apple" "rosy"] + ["Pear" "yellow"] + ["Orange" "round"]] + :multi? true) + rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + (is (= [1 1 1] counts)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance "rosy" :cost nil :grade nil} + {:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil} + {:id (generated-key db 2) :name "Pear" :appearance "yellow" :cost nil :grade nil}] rows))))) \ No newline at end of file From b25627a2c11a00031488ec4077cfe27cc4719a5d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 19 Apr 2013 19:16:56 -0700 Subject: [PATCH 089/630] Implement JDBC-52 (execute! ... :multi? true/false) --- src/main/clojure/clojure/java/jdbc.clj | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index bb1bad60..62923866 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -629,13 +629,13 @@ made at some future date." } "Given a database connection and a vector containing SQL and optional parameters, perform a general (non-select) SQL operation. The optional keyword argument specifies whether to run the operation in a transaction or not (default true)." - [db sql-params & {:keys [transaction?] - :or {transaction? true}}] - (let [execute-helper (fn [db] - (db-do-prepared db - transaction? - (first sql-params) - (rest sql-params)))] + [db sql-params & {:keys [transaction? multi?] + :or {transaction? true multi? false}}] + (let [execute-helper + (fn [db] + (if multi? + (apply db-do-prepared db transaction? (first sql-params) (rest sql-params)) + (db-do-prepared db transaction? (first sql-params) (rest sql-params))))] (if-let [con (and (map? db) (:connection db))] (execute-helper db) (with-open [con (get-connection db)] From a56264983735f8c12edee08821a5e15760aeb3db Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 19 Apr 2013 19:17:19 -0700 Subject: [PATCH 090/630] Document JDBC-52 (execute! ... :multi? true/false) --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 16202d77..832430f9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha2 +* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52) * Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean * Add curried version of clojure.java.jdbc.sql/as-quoted-str From e63d48f485d46e75b8afd129d333de7476d60315 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 19 Apr 2013 19:28:33 -0700 Subject: [PATCH 091/630] Apply Gary Fredericks' JDBC-46 patch 3 Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 16 +++++++++++++- src/test/clojure/clojure/java/test_jdbc.clj | 24 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index bb1bad60..782b8d8c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -238,6 +238,20 @@ made at some future date." } cols (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) +(defprotocol IResultSetReadColumn + "Protocol for reading objects from the java.sql.ResultSet. Default + implementations (for Object and nil) return the argument, but it can + be extended to provide custom behavior for special types." + (result-set-read-column [_] "Function for transforming values after reading them + from the database")) + +(extend-protocol IResultSetReadColumn + Object + (result-set-read-column [x] x) + + nil + (result-set-read-column [_] nil)) + (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it @@ -251,7 +265,7 @@ made at some future date." } (map (fn [^Integer i] (.getColumnLabel rsmeta i))) make-cols-unique (map (comp keyword identifiers))) - row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) + row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i))) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 77ff9724..af17aa86 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -554,3 +554,27 @@ (is (= 1 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-resultset-read-column + (extend-protocol sql/IResultSetReadColumn + String + (result-set-read-column [s] ::FOO)) + + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost] + ["Crepes" 12] + ["Vegetables" -88] + ["Teenage Mutant Ninja Turtles" 0]) + (is (= {:name ::FOO, :cost -88} + (sql/with-query-results res ["SELECT name, cost FROM fruit WHERE name = ?" + "Vegetables"] + (first res)))))) + + ;; somewhat "undo" the first extension + (extend-protocol sql/IResultSetReadColumn + String + (result-set-read-column [s] s))) \ No newline at end of file From 4f0926a5ebd3d5f9ced4255a883edd0d3316b10f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 19 Apr 2013 19:34:15 -0700 Subject: [PATCH 092/630] Document addition of IResultSetReadColumn protocol for JDBC-46 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 832430f9..39531e6b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha2 +* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52) * Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean From b1d2aa949820faaa6da0287d212364ee1b1e7e69 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 19 Apr 2013 19:52:26 -0700 Subject: [PATCH 093/630] Address JDBC-51 by removing reflection warnings (uses of get-connection result). --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 39531e6b..0821175a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha2 +* Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52) * Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index fa580483..594a3c5b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -44,7 +44,7 @@ API is still supported but will be deprecated before a 1.0.0 release is made at some future date." } clojure.java.jdbc (:import [java.net URI] - [java.sql BatchUpdateException DriverManager ParameterMetaData + [java.sql BatchUpdateException Connection DriverManager PreparedStatement ResultSet SQLException Statement Types] [java.util Hashtable Map Properties] [javax.naming InitialContext Name] @@ -174,6 +174,7 @@ made at some future date." } String: subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." + ^Connection [{:keys [connection factory connection-uri From 174e1373008a31481258a1f8a0a8cf95f8fa88bc Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 3 May 2013 12:58:15 -0500 Subject: [PATCH 094/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-alpha2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1e97083d..9215f8ce 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-alpha2 ${project.artifactId} From 6eac46b1709399bcaf6617982e0a9f3440c03675 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 3 May 2013 12:58:16 -0500 Subject: [PATCH 095/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9215f8ce..1e97083d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-alpha2 + 0.3.0-SNAPSHOT ${project.artifactId} From a1f916aff3fdc1bf44916aee56d78e6f25dd85ec Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 3 May 2013 17:26:33 -0700 Subject: [PATCH 096/630] Update CHANGES/README to reflect alpha2 release to Maven --- CHANGES.md | 2 +- README.md | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0821175a..c9cea59e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.0-alpha2 +Changes in 0.3.0-alpha2 * Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) diff --git a/README.md b/README.md index 802e3615..e141501e 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Formerly known as clojure.contrib.sql. Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-alpha1 +Latest stable release: 0.3.0-alpha2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -16,14 +16,14 @@ Latest stable release: 0.3.0-alpha1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-alpha1"] +[org.clojure/java.jdbc "0.3.0-alpha2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-alpha1 + 0.3.0-alpha2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -104,6 +104,15 @@ Developer Information Change Log ==================== +* Release 0.3.0-alpha2 on 2013-05-03 + * Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection + * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) + * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52) + * Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) + * Rename :as-arrays to :as-arrays? since it is boolean + * Add curried version of clojure.java.jdbc.sql/as-quoted-str + * Officially deprecate resultset-seq + * Release 0.3.0-alpha1 on 2013-04-07 * MAJOR API OVERHAUL! * Most of the old 0.2.x API has been deprecated and a new, more idiomatic API introduced, along with a minimal DSL to generate basic SQL From d7e77cce67e6b07bf7a4ad20385b58960fd6bbe0 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 4 May 2013 08:51:01 -0700 Subject: [PATCH 097/630] Fix macro / import interaction with unqualified Connection type --- src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 594a3c5b..7cca632f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -44,7 +44,7 @@ API is still supported but will be deprecated before a 1.0.0 release is made at some future date." } clojure.java.jdbc (:import [java.net URI] - [java.sql BatchUpdateException Connection DriverManager + [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement Types] [java.util Hashtable Map Properties] [javax.naming InitialContext Name] @@ -174,7 +174,7 @@ made at some future date." } String: subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." - ^Connection + ^java.sql.Connection [{:keys [connection factory connection-uri From 68b1c58d14b625dbf2d1b328c16986ae6e9a1d2a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 4 May 2013 08:53:58 -0700 Subject: [PATCH 098/630] Update CHANGES / README for alpha3 --- CHANGES.md | 4 ++++ README.md | 9 ++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c9cea59e..b4c745ad 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.3.0-alpha3 + +* Fix macro / import interaction by fully qualifying Connection type. + Changes in 0.3.0-alpha2 * Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection diff --git a/README.md b/README.md index e141501e..d48a6174 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Formerly known as clojure.contrib.sql. Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-alpha2 +Latest stable release: 0.3.0-alpha3 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -16,14 +16,14 @@ Latest stable release: 0.3.0-alpha2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-alpha2"] +[org.clojure/java.jdbc "0.3.0-alpha3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-alpha2 + 0.3.0-alpha3 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -104,6 +104,9 @@ Developer Information Change Log ==================== +* Release 0.3.0-alpha3 on 2013-05-04 + * Fix macro / import interaction by fully qualifying Connection type. + * Release 0.3.0-alpha2 on 2013-05-03 * Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) From 587361fe53c8e07920387628c208424335b3e3d4 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 4 May 2013 10:55:12 -0500 Subject: [PATCH 099/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-alpha3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1e97083d..3458f8b2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-alpha3 ${project.artifactId} From cbde4c9386ceea28fc7ba62a162dd7222651b7a9 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 4 May 2013 10:55:12 -0500 Subject: [PATCH 100/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3458f8b2..1e97083d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-alpha3 + 0.3.0-SNAPSHOT ${project.artifactId} From 56bf7e3485a486f94cc5fd9f11b92441a289e780 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 6 May 2013 23:37:16 -0700 Subject: [PATCH 101/630] Bump parent pom per Clojure/core --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1e97083d..2f7427a7 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ org.clojure pom.contrib - 0.0.25 + 0.1.2 From 27ef4b11066f7bb4181a274fad15b157127ad1db Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 6 May 2013 23:39:46 -0700 Subject: [PATCH 102/630] Bump MySQL connector from 5.1.6 to 5.1.25 --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d48a6174..9f015e64 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ shown as Leiningen dependencies: ;; Microsoft SQL Server using the jTDS driver [net.sourceforge.jtds/jtds "1.2.4"] ;; MySQL -[mysql/mysql-connector-java "5.1.6"] +[mysql/mysql-connector-java "5.1.25"] ;; PostgreSQL [postgresql/postgresql "8.4-702.jdbc4"] ;; SQLite diff --git a/pom.xml b/pom.xml index 2f7427a7..836ebcc7 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ mysql mysql-connector-java - 5.1.6 + 5.1.25 test From 42e59b35a6ac706cf6479a56816592527dd62808 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 7 May 2013 17:28:05 -0700 Subject: [PATCH 103/630] Correct docstring now set-parameters is back to earlier simple version. --- src/main/clojure/clojure/java/jdbc.clj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7cca632f..5a27ab37 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -359,8 +359,7 @@ made at some future date." } stmt)) (defn- set-parameters - "Add the parameters to the given statement. Use parameter metadata if it is - available, which allows us to specify the SQL type and support NULL better." + "Add the parameters to the given statement." [^PreparedStatement stmt params db] (dorun (map-indexed (fn [ix value] (.setObject stmt (inc ix) value)) From 953ff09f60204cac128f1afad11ff12c8f902b73 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 7 May 2013 18:25:28 -0700 Subject: [PATCH 104/630] Removed unused db parameter from set-parameters --- src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5a27ab37..8d5c6613 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -360,7 +360,7 @@ made at some future date." } (defn- set-parameters "Add the parameters to the given statement." - [^PreparedStatement stmt params db] + [^PreparedStatement stmt params] (dorun (map-indexed (fn [ix value] (.setObject stmt (inc ix) value)) params))) @@ -965,7 +965,7 @@ made at some future date." } :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special)))] (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (get-connection *db*) sql prepare-args))] - (set-parameters stmt params *db*) + (set-parameters stmt params) (with-open [rset (.executeQuery stmt)] (binding [*db* (assoc *db* :connection (.getConnection stmt))] (func (resultset-seq rset))))))) From 165c9d2c3151a244e5a323e817edba970f6bfbb5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 7 May 2013 18:31:51 -0700 Subject: [PATCH 105/630] Reworked code that calls get-connection to conditionally call db-find-connection first so connections can be added (and closed!) correctly on-demand at any point in the workflow. --- src/main/clojure/clojure/java/jdbc.clj | 195 +++++++++++++------------ 1 file changed, 104 insertions(+), 91 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8d5c6613..7bb4e89d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -473,23 +473,25 @@ made at some future date." } complete." [db func] (if (zero? (get-level db)) - (let [^java.sql.Connection con (get-connection db) - nested-db (inc-level (add-connection db con)) - auto-commit (.getAutoCommit con)] - (io! - (.setAutoCommit con false) - (try - (let [result (func nested-db)] - (if (db-is-rollback-only nested-db) + (if-let [^java.sql.Connection con (db-find-connection db)] + (let [nested-db (inc-level db) + auto-commit (.getAutoCommit con)] + (io! + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-is-rollback-only nested-db) + (.rollback con) + (.commit con)) + result) + (catch Throwable t (.rollback con) - (.commit con)) - result) - (catch Throwable t - (.rollback con) - (throw-non-rte t)) - (finally - (db-unset-rollback-only! nested-db) - (.setAutoCommit con auto-commit))))) + (throw-non-rte t)) + (finally + (db-unset-rollback-only! nested-db) + (.setAutoCommit con auto-commit))))) + (with-open [^java.sql.Connection con (get-connection db)] + (db-transaction* (add-connection db con) func))) (try (func (inc-level db)) (catch Exception e @@ -508,16 +510,19 @@ made at some future date." } "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true." [db transaction? & commands] - (with-open [^Statement stmt (let [^java.sql.Connection con (get-connection db)] (.createStatement con))] - (doseq [^String cmd commands] - (.addBatch stmt cmd)) - (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (try - (execute-batch stmt) - (catch Exception e - (throw-non-rte e)))))) + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^Statement stmt (.createStatement con)] + (doseq [^String cmd commands] + (.addBatch stmt cmd)) + (if transaction? + (db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e))))) + (with-open [^java.sql.Connection con (get-connection db)] + (apply db-do-commands (add-connection db con) transaction? commands)))) (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the @@ -525,27 +530,30 @@ made at some future date." } the parameters. Return the generated keys for the (single) update/insert." [db transaction? sql param-group] - (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql :return-keys true)] - (set-parameters stmt param-group db) - (letfn [(exec-and-return-keys [] - (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))] - (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (exec-and-return-keys)) - (try - (exec-and-return-keys) - (catch Exception e - (throw-non-rte e))))))) + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] + (set-parameters stmt param-group) + (letfn [(exec-and-return-keys [] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (result-set-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] + (if transaction? + (db-transaction [t-db (add-connection db (.getConnection stmt))] + (exec-and-return-keys)) + (try + (exec-and-return-keys) + (catch Exception e + (throw-non-rte e)))))) + (with-open [^java.sql.Connection con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group)))) (defn db-do-prepared "Executes an (optionally parameterized) SQL prepared statement on the @@ -553,28 +561,31 @@ made at some future date." } the parameters. Return a seq of update counts (one count for each param-group)." [db transaction? sql & param-groups] - (with-open [^PreparedStatement stmt (prepare-statement (get-connection db) sql)] - (if (empty? param-groups) - (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) - (try - (vector (.executeUpdate stmt)) - (catch Exception e - (throw-non-rte e)))) - (do - (doseq [param-group param-groups] - (set-parameters stmt param-group db) - (.addBatch stmt)) + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql)] + (if (empty? param-groups) (if transaction? (db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) + (vector (.executeUpdate stmt))) (try - (execute-batch stmt) + (vector (.executeUpdate stmt)) (catch Exception e - (throw-non-rte e)))))))) - -(defn db-with-query-results* + (throw-non-rte e)))) + (do + (doseq [param-group param-groups] + (set-parameters stmt param-group) + (.addBatch stmt)) + (if transaction? + (db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e))))))) + (with-open [^java.sql.Connection con (get-connection db)] + (apply db-do-prepared (add-connection db con) transaction? sql param-groups)))) + +(defn- db-with-query-results* "Executes a query, then evaluates func passing in a seq of the results as an argument. The first argument is a vector containing either: [sql & params] - a SQL query, followed by any parameters it needs @@ -601,13 +612,22 @@ made at some future date." } params (vec (cond sql-is-first (rest sql-params) options-are-first (rest (rest sql-params)) :else (rest sql-params))) - prepare-args (when (map? special) (flatten (seq special)))] - (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) - special - (apply prepare-statement (get-connection db) sql prepare-args))] - (set-parameters stmt params db) - (with-open [rset (.executeQuery stmt)] - (func (result-set-seq rset :identifiers identifiers :as-arrays? as-arrays?)))))) + prepare-args (when (map? special) (flatten (seq special))) + run-query-with-params (fn [stmt] + (set-parameters stmt params) + (with-open [rset (.executeQuery stmt)] + (func (result-set-seq rset + :identifiers identifiers + :as-arrays? as-arrays?))))] + (if (instance? PreparedStatement special) + (let [^PreparedStatement stmt special] + (run-query-with-params stmt)) + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^PreparedStatement stmt (apply prepare-statement con sql prepare-args)] + (run-query-with-params stmt)) + (with-open [^java.sql.Connection con (get-connection db)] + (with-open [^PreparedStatement stmt (apply prepare-statement con sql prepare-args)] + (run-query-with-params stmt))))))) ;; top-level API for actual SQL operations @@ -623,21 +643,14 @@ made at some future date." } :or {result-set-fn doall row-fn identity identifiers sql/lower-case}}] - (let [query-helper (fn [db] - (db-with-query-results* db - (vec sql-params) - (fn [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (vec (map row-fn (rest rs)))) - (map row-fn rs)))) - identifiers - as-arrays?))] - (if-let [con (and (map? db) (:connection db))] - (query-helper db) - (with-open [con (get-connection db)] - (query-helper - (add-connection db con)))))) + (db-with-query-results* db (vec sql-params) + (fn [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (vec (map row-fn (rest rs)))) + (map row-fn rs)))) + identifiers + as-arrays?)) (defn execute! "Given a database connection and a vector containing SQL and optional parameters, @@ -650,9 +663,9 @@ made at some future date." } (if multi? (apply db-do-prepared db transaction? (first sql-params) (rest sql-params)) (db-do-prepared db transaction? (first sql-params) (rest sql-params))))] - (if-let [con (and (map? db) (:connection db))] + (if-let [con (db-find-connection db)] (execute-helper db) - (with-open [con (get-connection db)] + (with-open [^java.sql.Connection con (get-connection db)] (execute-helper (add-connection db con)))))) (defn delete! @@ -707,9 +720,9 @@ made at some future date." } [db table & options] (let [[transaction? maps-or-cols-and-values-etc] (extract-transaction? options) stmts (apply sql/insert table maps-or-cols-and-values-etc)] - (if-let [con (and (map? db) (:connection db))] + (if-let [con (db-find-connection db)] (insert-helper db transaction? stmts) - (with-open [con (get-connection db)] + (with-open [^java.sql.Connection con (get-connection db)] (insert-helper (add-connection db con) transaction? stmts))))) (defn update! From bd32412b0243a957b86a451f95c3e862e165b80f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 7 May 2013 19:23:13 -0700 Subject: [PATCH 106/630] Added JDBC-54 to CHANGES (upcoming version) --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index b4c745ad..349c104a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming up in 0.3.0-alpha4 + +* Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) + Changes in 0.3.0-alpha3 * Fix macro / import interaction by fully qualifying Connection type. From f9ecadd03c1c2e01f107155b03061ac0b20f976c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 7 May 2013 21:17:28 -0700 Subject: [PATCH 107/630] order-by should accept empty sequence and return empty string --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc/sql.clj | 11 +++++++---- src/test/clojure/clojure/java/test_sql.clj | 1 + 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 349c104a..9a2994e7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming up in 0.3.0-alpha4 * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) +* Allow order-by to accept empty sequence (and return empty string) Changes in 0.3.0-alpha3 diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 34d95d1b..142b0548 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -218,10 +218,13 @@ and update! high-level operations within clojure.java.jdbc directly." } SQL string for the ORDER BY clause. A column order spec may be a column name or a map of the column name to the desired order." [cols & {:keys [entities] :or {entities as-is}}] - (str "ORDER BY " - (if (or (string? cols) (keyword? cols) (map? cols)) - (order-direction cols entities) - (str/join "," (map #(order-direction % entities) cols))))) + (let [singleton (or (string? cols) (keyword? cols) (map? cols))] + (if (or singleton (seq cols)) + (str "ORDER BY " + (if singleton + (order-direction cols entities) + (str/join "," (map #(order-direction % entities) cols)))) + ""))) (defn select "Given a sequence of column names (or *) and a table name, followed by optional SQL diff --git a/src/test/clojure/clojure/java/test_sql.clj b/src/test/clojure/clojure/java/test_sql.clj index 89d76fbf..9f9a9b86 100644 --- a/src/test/clojure/clojure/java/test_sql.clj +++ b/src/test/clojure/clojure/java/test_sql.clj @@ -59,6 +59,7 @@ (select * :a (where {:b 2 :c nil}))))) (deftest order-by-dsl + (is (= "" (order-by []))) (is (= "ORDER BY a ASC" (order-by :a))) (is (= "ORDER BY a ASC" (order-by [:a]))) (is (= "ORDER BY a DESC" (order-by {:a :desc}))) From 5abbb2257fc44d84e6172e4b1923c9e9946e2c7d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 11 May 2013 10:03:55 -0700 Subject: [PATCH 108/630] Update CHANGES / README for 0.3.0-alpha4 --- CHANGES.md | 2 +- README.md | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 9a2994e7..027ad8e5 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming up in 0.3.0-alpha4 +Changes in 0.3.0-alpha4 * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) diff --git a/README.md b/README.md index 9f015e64..040aa887 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Formerly known as clojure.contrib.sql. Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-alpha3 +Latest stable release: 0.3.0-alpha4 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -16,14 +16,14 @@ Latest stable release: 0.3.0-alpha3 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-alpha3"] +[org.clojure/java.jdbc "0.3.0-alpha4"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-alpha3 + 0.3.0-alpha4 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -104,6 +104,11 @@ Developer Information Change Log ==================== +* Release 0.3.0-alpha4 on 2013-05-11 + * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) + * Allow order-by to accept empty sequence (and return empty string) + + * Release 0.3.0-alpha3 on 2013-05-04 * Fix macro / import interaction by fully qualifying Connection type. From eac43692e62a955224cf8b38c4bd3afba6631d9f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 11 May 2013 16:22:27 -0500 Subject: [PATCH 109/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-alpha4 --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 836ebcc7..999ed1c5 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-alpha4 ${project.artifactId} @@ -23,6 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git + java.jdbc-0.3.0-alpha4 From c976a71fec5e2b06d454c48ad0aab7a314bc84e9 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 11 May 2013 16:22:27 -0500 Subject: [PATCH 110/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 999ed1c5..734e6734 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-alpha4 + 0.3.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.0-alpha4 + HEAD From 90494abae363066112b891251ca9b35816c470fe Mon Sep 17 00:00:00 2001 From: Manish Handa Date: Mon, 20 May 2013 10:44:10 -0400 Subject: [PATCH 111/630] updated protocol Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7bb4e89d..a43103d0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -243,15 +243,15 @@ made at some future date." } "Protocol for reading objects from the java.sql.ResultSet. Default implementations (for Object and nil) return the argument, but it can be extended to provide custom behavior for special types." - (result-set-read-column [_] "Function for transforming values after reading them + (result-set-read-column [val rsmeta idx] "Function for transforming values after reading them from the database")) (extend-protocol IResultSetReadColumn Object - (result-set-read-column [x] x) + (result-set-read-column [x _ _] x) nil - (result-set-read-column [_] nil)) + (result-set-read-column [_ _ _] nil)) (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the @@ -266,7 +266,7 @@ made at some future date." } (map (fn [^Integer i] (.getColumnLabel rsmeta i))) make-cols-unique (map (comp keyword identifiers))) - row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i))) idxs)) + row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't From a9c78716f2e634dad739e47b67352fb91521f0d5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 20 May 2013 20:49:17 -0700 Subject: [PATCH 112/630] Fix protocol tests --- src/test/clojure/clojure/java/test_jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 1e2d8405..5580eee2 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -588,7 +588,7 @@ (deftest test-resultset-read-column (extend-protocol sql/IResultSetReadColumn String - (result-set-read-column [s] ::FOO)) + (result-set-read-column [s _ _] ::FOO)) (doseq [db (test-specs)] (sql/with-connection db @@ -607,4 +607,4 @@ ;; somewhat "undo" the first extension (extend-protocol sql/IResultSetReadColumn String - (result-set-read-column [s] s))) + (result-set-read-column [s _ _] s))) From 499868b26811ffcf7996ffcef40b29a68241b643 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 20 May 2013 20:52:24 -0700 Subject: [PATCH 113/630] Note fix for JDBC-57 --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 027ad8e5..213021ea 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.0-alpha5 + +* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) + Changes in 0.3.0-alpha4 * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) From 06146de42a8a372b3a4a581e63100fee207b32e9 Mon Sep 17 00:00:00 2001 From: Andy Fingerhut Date: Wed, 15 May 2013 08:32:10 -0700 Subject: [PATCH 114/630] Eliminate a couple of reflection warnings Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a43103d0..b50144f1 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -613,7 +613,7 @@ made at some future date." } options-are-first (rest (rest sql-params)) :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special))) - run-query-with-params (fn [stmt] + run-query-with-params (fn [^PreparedStatement stmt] (set-parameters stmt params) (with-open [rset (.executeQuery stmt)] (func (result-set-seq rset From f625ed015e65bcf18ece0b9321d2c44b8053d34c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 21 May 2013 08:07:38 -0700 Subject: [PATCH 115/630] Note fix for JDBC-55 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 213021ea..4f586a4b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.0-alpha5 * Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) +* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) Changes in 0.3.0-alpha4 From 1603e02a22557d53029de32d51a916160b270581 Mon Sep 17 00:00:00 2001 From: Dan Dillinger Date: Sat, 25 May 2013 16:39:00 -0400 Subject: [PATCH 116/630] * postgres? predicate * defmulti for dispatching create-test-table - mysql and postgres both need special care and feeding for auto incrementing primary keys. Signed-off-by: Sean Corfield --- src/test/clojure/clojure/java/test_jdbc.clj | 42 +++++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 5580eee2..1e3e6725 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -128,18 +128,52 @@ (re-find #"mysql:" db) (= "mysql" (:subprotocol db)))) -(defn- create-test-table +(defn- postgres? [db] + (if (string? db) + (re-find #"postgres" db) + (= "postgresql" (:subprotocol db)))) + +(defmulti create-test-table "Create a standard test table. Must be inside with-connection. For MySQL, ensure table uses an engine that supports transactions!" + (fn [table db] + (cond + (mysql? db) :mysql + (postgres? db) :postgres + :else :default))) + +(defmethod create-test-table :mysql + [table db] + (sql/create-table + table + [:id :int "PRIMARY KEY AUTO_INCREMENT"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec "ENGINE=InnoDB")) + +(defmethod create-test-table :postgres + [table db] + (sql/create-table + table + [:id :serial "PRIMARY KEY"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec "")) + +(defmethod create-test-table :default [table db] (sql/create-table table - [:id :int (if (mysql? db) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] - [:name "VARCHAR(32)" (if (mysql? db) "" "PRIMARY KEY")] + [:id :int "DEFAULT 0"] + [:name "VARCHAR(32)" "PRIMARY KEY"] [:appearance "VARCHAR(32)"] [:cost :int] [:grade :real] - :table-spec (if (mysql? db) "ENGINE=InnoDB" ""))) + :table-spec "")) (deftest test-create-table (doseq [db (test-specs)] From 6aa4f8277fc5462b1ff2b11e69c25b1fc532531d Mon Sep 17 00:00:00 2001 From: Dan Dillinger Date: Sat, 25 May 2013 16:39:50 -0400 Subject: [PATCH 117/630] float-or-double needs a postgres case Signed-off-by: Sean Corfield --- src/test/clojure/clojure/java/test_jdbc.clj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 1e3e6725..d248c478 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -432,6 +432,7 @@ "derby" (Float. v) "jtds:sqlserver" (Float. v) "sqlserver" (Float. v) + "postgresql" (Float. v) v)) (deftest empty-query From 3c1751f3a4d272b2484055031c3197637d334d89 Mon Sep 17 00:00:00 2001 From: Dan Dillinger Date: Sat, 25 May 2013 16:43:52 -0400 Subject: [PATCH 118/630] Pull the :id column out when necessary. Some databases -- and postgres is one of these, firebird is another -- implement .getGeneratedKeys() to simply return the record. Typically, that is because the db in question is unable to easily determine which columns are autogenerated ones, because reasons. So when a whole entire record map comes back, we pull :id off of it, because we know (since we created it) which column we're interested in. Kind of just one of those things. postgres mailing list discussion: http://www.postgresql.org/message-id/004801cb7518$cbc632e0$635298a0$@pravdin@disi.unitn.it Signed-off-by: Sean Corfield --- src/test/clojure/clojure/java/test_jdbc.clj | 22 ++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index d248c478..4ebe0b86 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -445,20 +445,25 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (is (= [(returned-key db 1)] (sql/insert! db :fruit {:name "Apple"}))))) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [(returned-key db 1)] new-keys))))) (deftest insert-query (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (is (= [(returned-key db 1)] (sql/insert! db :fruit {:name "Apple"}))) - (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db (dsl/select * :fruit)))))) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [(returned-key db 1)] new-keys)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db (dsl/select * :fruit))))))) (deftest insert-two-by-map-and-query (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} @@ -469,6 +474,7 @@ (sql/with-connection db (create-test-table :fruit db)) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)) :as-arrays? true)] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) @@ -490,11 +496,12 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (let [new-key (sql/insert! db :fruit {:name "Apple"}) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} (dsl/where {:id (generated-key db 1)})) rows (sql/query db (dsl/select * :fruit))] - (is (= [(returned-key db 1)] new-key)) + (is (= [(returned-key db 1)] new-keys)) (is (= [1] update-result)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance "Green" @@ -505,11 +512,12 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (let [new-key (sql/insert! db :fruit {:name "Apple"}) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) delete-result (sql/delete! db :fruit (dsl/where {:id (generated-key db 1)})) rows (sql/query db (dsl/select * :fruit))] - (is (= [(returned-key db 1)] new-key)) + (is (= [(returned-key db 1)] new-keys)) (is (= [1] delete-result)) (is (= [] rows))))) From 00ae87f328570664ba199b633f934774f69d3068 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 May 2013 08:21:18 -0700 Subject: [PATCH 119/630] Correct PostgreSQL setup instructions. --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 040aa887..8bdc496b 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ Developer Information * To test against PostgreSQL, first create the user and database: - $ sudo -u postgres createuser clojure_test -P # password: clojure_test + $ sudo -u postgres createuser clojure_test -P clojure_test $ sudo -u postgres createdb clojure_test -O clojure_test * Or similarly with MySQL: @@ -108,7 +108,6 @@ Change Log * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) - * Release 0.3.0-alpha3 on 2013-05-04 * Fix macro / import interaction by fully qualifying Connection type. From fa058278c23369c60e1d8d91bed82546cb3e0138 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 May 2013 08:22:07 -0700 Subject: [PATCH 120/630] Add PostgreSQL-related support notes. --- CHANGES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 4f586a4b..7384921d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,7 @@ Changes coming in 0.3.0-alpha5 +* Update README to clarify PostgreSQL instructions. +* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) * Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) * Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) From 9edf85327bd2e76d0f75125b50f3cc53776c45e3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 22 Jun 2013 10:50:21 -0700 Subject: [PATCH 121/630] Add DDL namespace and move create-table / drop-table stuff there --- src/main/clojure/clojure/java/jdbc.clj | 62 ++++++++++------------ src/main/clojure/clojure/java/jdbc/ddl.clj | 50 +++++++++++++++++ 2 files changed, 77 insertions(+), 35 deletions(-) create mode 100644 src/main/clojure/clojure/java/jdbc/ddl.clj diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b50144f1..2b26a369 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -51,6 +51,7 @@ made at some future date." } [javax.sql DataSource]) (:refer-clojure :exclude [resultset-seq]) (:require [clojure.string :as str] + [clojure.java.jdbc.ddl :as ddl] [clojure.java.jdbc.sql :as sql])) ;; technically deprecated but still used as defaults in a couple of @@ -365,25 +366,6 @@ made at some future date." } (.setObject stmt (inc ix) value)) params))) -(defn create-table-ddl - "Given a table name and column specs with an optional table-spec - return the DDL string for creating a table based on that." - [name & specs] - (let [split-specs (partition-by #(= :table-spec %) specs) - col-specs (first split-specs) - table-spec (first (second (rest split-specs))) - table-spec-str (or (and table-spec (str " " table-spec)) "") - specs-to-string (fn [specs] - (apply str - (map (sql/as-str identity) - (apply concat - (interpose [", "] - (map (partial interpose " ") specs))))))] - (format "CREATE TABLE %s (%s)%s" - (sql/as-str identity name) - (specs-to-string col-specs) - table-spec-str))) - (defn print-sql-exception "Prints the contents of an SQLException to *out*" [^SQLException exception] @@ -847,25 +829,35 @@ made at some future date." } :deprecated "0.3.0"} do-prepared [sql & param-groups] - (apply db-do-prepared *db* true sql param-groups)) - -(defn create-table - "Creates a table on the open database connection given a table name and - specs. Each spec is either a column spec: a vector containing a column - name and optionally a type and other constraints, or a table-level - constraint: a vector containing words that express the constraint. An - optional suffix to the CREATE TABLE DDL describing table attributes may - by provided as :table-spec {table-attributes-string}. All words used to - describe the table may be supplied as strings or keywords." + (apply db-do-prepared *db* sql param-groups)) + +(defn ^{:doc "See clojure.java.jdbc.ddl/create-table for details. + This version is deprecated in favor of the version in the DDL namespace." + :deprecated "0.3.0"} + create-table-ddl + [name & specs] + (apply ddl/create-table name specs)) + +(defn + ^{:doc "Creates a table on the open database connection given a table name and + specs. Each spec is either a column spec: a vector containing a column + name and optionally a type and other constraints, or a table-level + constraint: a vector containing words that express the constraint. An + optional suffix to the CREATE TABLE DDL describing table attributes may + by provided as :table-spec {table-attributes-string}. All words used to + describe the table may be supplied as strings or keywords." + :deprecated "0.3.0"} + create-table [name & specs] - (do-commands (apply create-table-ddl name specs))) + (db-do-commands *db* (apply ddl/create-table name specs))) -(defn drop-table - "Drops a table on the open database connection given its name, a string - or keyword" +(defn + ^{:doc "Drops a table on the open database connection given its name, a string + or keyword" + :deprecated "0.3.0"} + drop-table [name] - (do-commands - (format "DROP TABLE %s" (sql/as-str identity name)))) + (db-do-commands *db* (ddl/drop-table name))) (defn ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the diff --git a/src/main/clojure/clojure/java/jdbc/ddl.clj b/src/main/clojure/clojure/java/jdbc/ddl.clj new file mode 100644 index 00000000..947727e4 --- /dev/null +++ b/src/main/clojure/clojure/java/jdbc/ddl.clj @@ -0,0 +1,50 @@ +;; Copyright (c) Sean Corfield. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; ddl.clj +;; +;; A basic DDL DSL for use with clojure.java.jdbc (or you can use any +;; other DDL DSL you want to...) +;; +;; seancorfield (gmail) +;; December 2013 + +(ns + ^{:author "Sean Corfield", + :doc "An optional DSL for generating DDL. + +Intended to be used with clojure.java.jdbc, this provides a simple DSL - +Domain Specific Language - that generates raw DDL strings. Any other DSL +can be used instead. This DSL is entirely optional and is deliberately +not very sophisticated." } + clojure.java.jdbc.ddl + (:require [clojure.java.jdbc.sql :as sql])) + +(defn create-table + "Given a table name and column specs with an optional table-spec + return the DDL string for creating that table." + [name & specs] + (let [split-specs (partition-by #(= :table-spec %) specs) + col-specs (first split-specs) + table-spec (first (second (rest split-specs))) + table-spec-str (or (and table-spec (str " " table-spec)) "") + specs-to-string (fn [specs] + (apply str + (map (sql/as-str identity) + (apply concat + (interpose [", "] + (map (partial interpose " ") specs))))))] + (format "CREATE TABLE %s (%s)%s" + (sql/as-str identity name) + (specs-to-string col-specs) + table-spec-str))) + +(defn drop-table + "Given a table name, return the DDL string for dropping that table." + [name] + (format "DROP TABLE %s" (sql/as-str identity name))) \ No newline at end of file From 75fffebf36310839a5907308fb0a56b726bb79b2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 22 Jun 2013 10:51:54 -0700 Subject: [PATCH 122/630] Clean up doc/deprecated metadata and function names --- src/main/clojure/clojure/java/jdbc.clj | 39 +++++++++++++++++--------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 2b26a369..b7478077 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -285,10 +285,11 @@ made at some future date." } (cons (vec keys) (rows)) (records)))) -(defn resultset-seq +(defn ^{:doc "A deprecated version of result-set-seq that uses the dynamic *as-key* variable." :deprecated "0.3.0"} + resultset-seq [^ResultSet rs & {:keys [identifiers] :or {identifiers *as-key*}}] (result-set-seq rs :identifiers identifiers)) @@ -752,7 +753,7 @@ made at some future date." } [db-spec & body] `(with-connection* ~db-spec (fn [] ~@body))) -(defn transaction* +(defn ^{:doc "Evaluates func as a transaction on the open database connection. Any nested transactions are absorbed into the outermost transaction. By default, all database updates are committed together as a group after @@ -761,6 +762,7 @@ made at some future date." } the entire transaction will be rolled back rather than committed when complete." :deprecated "0.3.0"} + transaction* [func] (binding [*db* (update-in *db* [:level] inc)] (if (= (:level *db*) 1) @@ -881,11 +883,12 @@ made at some future date." } [table column-names & value-groups] (apply insert! *db* table column-names (concat value-groups [:entities *as-str*]))) -(defn insert-rows +(defn ^{:doc "Inserts complete rows into a table. Each row is a vector of values for each of the table's columns in order. If a single row is inserted, returns a map of the generated keys." :deprecated "0.3.0"} + insert-rows [table & rows] (apply insert! *db* table nil (concat rows [:entities *as-str*]))) @@ -989,25 +992,27 @@ made at some future date." } [results sql-params & body] `(with-query-results* ~sql-params (fn [~results] ~@body))) -(defn as-key +(defn ^{:doc "Given a naming strategy and a string, return the string as a keyword per that naming strategy. Given (a naming strategy and) a keyword, return it as-is." :deprecated "0.3.0"} + as-key [f x] (if (instance? clojure.lang.Named x) x (keyword (f (str x))))) -(defn as-keyword +(defn ^{:doc "Given an entity name (string), convert it to a keyword using the current naming strategy. Given a keyword, return it as-is." :deprecated "0.3.0"} + as-keyword ([x] (as-keyword x *as-key*)) ([x f-keyword] (as-key f-keyword x))) -(defn as-named-keyword +(defn ^{:doc "Given a naming strategy and a string, return the string as a keyword using the keyword naming strategy. Given a naming strategy and a keyword, return the keyword as-is. @@ -1017,10 +1022,11 @@ made at some future date." } Note that providing a single function will cause the default keyword naming strategy to be used!" :deprecated "0.3.0"} + as-named-keyword [naming-strategy x] (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) -(defn as-str +(defn ^{:doc "Given a naming strategy and a keyword, return the keyword as a string per that naming strategy. Given (a naming strategy and) a string, return it as-is. @@ -1029,27 +1035,30 @@ made at some future date." } joined back together so :x.y might become `x`.`y` if the naming strategy quotes identifiers with `." :deprecated "0.3.0"} + as-str [f x] (sql/as-str f x)) -(defn as-identifier +(defn ^{:doc "Given a keyword, convert it to a string using the current naming strategy. Given a string, return it as-is." :deprecated "0.3.0"} + as-identifier ([x] (as-identifier x *as-str*)) ([x f-entity] (as-str f-entity x))) -(defn as-quoted-str +(defn ^{:doc "Given a quoting pattern - either a single character or a vector pair of characters - and a string, return the quoted string: (as-quoted-str X foo) will return XfooX (as-quoted-str [A B] foo) will return AfooB" :deprecated "0.3.0"} + as-quoted-str [q x] (sql/as-quoted-str q x)) -(defn as-named-identifier +(defn ^{:doc "Given a naming strategy and a keyword, return the keyword as a string using the entity naming strategy. Given a naming strategy and a string, return the string as-is. @@ -1057,10 +1066,11 @@ made at some future date." } or a map containing :entity and/or :keyword keys which provide the entity naming strategy and/or keyword naming strategy respectively." :deprecated "0.3.0"} + as-named-identifier [naming-strategy x] (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) -(defn as-quoted-identifier +(defn ^{:doc "Given a quote pattern - either a single character or a pair of characters in a vector - and a keyword, return the keyword as a string using a simple quoting naming strategy. @@ -1068,16 +1078,18 @@ made at some future date." } (as-quoted-identifier X :name) will return XnameX as a string. (as-quoted-identifier [A B] :name) will return AnameB as a string." :deprecated "0.3.0"} + as-quoted-identifier [q x] (as-identifier x (sql/as-quoted-str q))) -(defmacro with-quoted-identifiers +(defmacro ^{:doc "Evaluates body in the context of a simple quoting naming strategy." :deprecated "0.3.0"} + with-quoted-identifiers [q & body ] `(binding [*as-str* (sql/as-quoted-str ~q)] ~@body)) -(defmacro with-naming-strategy +(defmacro ^{:doc "Evaluates body in the context of a naming strategy. The naming strategy is either a function - the entity naming strategy - or a map containing :entity and/or :keyword keys which provide the entity naming @@ -1085,6 +1097,7 @@ made at some future date." } naming strategy is identity; the default keyword naming strategy is lower-case." :deprecated "0.3.0"} + with-naming-strategy [naming-strategy & body ] `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) \ No newline at end of file From dd3c05b940b9a9c7a739247e2508ea6a5d55df65 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 22 Jun 2013 10:52:44 -0700 Subject: [PATCH 123/630] Allow transaction? boolean argument to be ommitted in db-do-* functions --- src/main/clojure/clojure/java/jdbc.clj | 133 +++++++++++++------------ 1 file changed, 70 insertions(+), 63 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b7478077..406ec4c1 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -491,82 +491,89 @@ made at some future date." } (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands - in a transaction if transaction? is true." + in a transaction if transaction? is true. transaction? can be ommitted and it + defaults to true." [db transaction? & commands] - (if-let [^java.sql.Connection con (db-find-connection db)] - (with-open [^Statement stmt (.createStatement con)] - (doseq [^String cmd commands] - (.addBatch stmt cmd)) - (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (try - (execute-batch stmt) - (catch Exception e - (throw-non-rte e))))) - (with-open [^java.sql.Connection con (get-connection db)] - (apply db-do-commands (add-connection db con) transaction? commands)))) + (if (string? transaction?) + (apply db-do-commands db true transaction? commands) + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^Statement stmt (.createStatement con)] + (doseq [^String cmd commands] + (.addBatch stmt cmd)) + (if transaction? + (db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e))))) + (with-open [^java.sql.Connection con (get-connection db)] + (apply db-do-commands (add-connection db con) transaction? commands))))) (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the open database connection. The param-group is a seq of values for all of - the parameters. + the parameters. transaction? can be ommitted and will default to true. Return the generated keys for the (single) update/insert." - [db transaction? sql param-group] - (if-let [^java.sql.Connection con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] - (set-parameters stmt param-group) - (letfn [(exec-and-return-keys [] - (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))] - (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (exec-and-return-keys)) - (try - (exec-and-return-keys) - (catch Exception e - (throw-non-rte e)))))) - (with-open [^java.sql.Connection con (get-connection db)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group)))) + ([db sql param-group] + (db-do-prepared-return-keys db true sql param-group)) + ([db transaction? sql param-group] + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] + (set-parameters stmt param-group) + (letfn [(exec-and-return-keys [] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (result-set-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] + (if transaction? + (db-transaction [t-db (add-connection db (.getConnection stmt))] + (exec-and-return-keys)) + (try + (exec-and-return-keys) + (catch Exception e + (throw-non-rte e)))))) + (with-open [^java.sql.Connection con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) (defn db-do-prepared "Executes an (optionally parameterized) SQL prepared statement on the open database connection. Each param-group is a seq of values for all of - the parameters. + the parameters. transaction? can be omitted and defaults to true. Return a seq of update counts (one count for each param-group)." - [db transaction? sql & param-groups] - (if-let [^java.sql.Connection con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql)] - (if (empty? param-groups) - (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) - (try - (vector (.executeUpdate stmt)) - (catch Exception e - (throw-non-rte e)))) - (do - (doseq [param-group param-groups] - (set-parameters stmt param-group) - (.addBatch stmt)) + [db transaction? & [sql & param-groups :as opts]] + (if (string? transaction?) + (apply db-do-prepared db true transaction? opts) + (if-let [^java.sql.Connection con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql)] + (if (empty? param-groups) (if transaction? (db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) + (vector (.executeUpdate stmt))) (try - (execute-batch stmt) + (vector (.executeUpdate stmt)) (catch Exception e - (throw-non-rte e))))))) - (with-open [^java.sql.Connection con (get-connection db)] - (apply db-do-prepared (add-connection db con) transaction? sql param-groups)))) + (throw-non-rte e)))) + (do + (doseq [param-group param-groups] + (set-parameters stmt param-group) + (.addBatch stmt)) + (if transaction? + (db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e))))))) + (with-open [^java.sql.Connection con (get-connection db)] + (apply db-do-prepared (add-connection db con) transaction? sql param-groups))))) (defn- db-with-query-results* "Executes a query, then evaluates func passing in a seq of the results as @@ -821,7 +828,7 @@ made at some future date." } :deprecated "0.3.0"} do-commands [& commands] - (apply db-do-commands *db* true commands)) + (apply db-do-commands *db* commands)) (defn ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the @@ -869,7 +876,7 @@ made at some future date." } :deprecated "0.3.0"} do-prepared-return-keys [sql param-group] - (db-do-prepared-return-keys *db* true sql param-group)) + (db-do-prepared-return-keys *db* sql param-group)) (defn ^{:doc "Inserts rows into a table with values for specified columns only. From 36b05dee453a457ed6fc7fe7e2c81d4fe785d54f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 22 Jun 2013 21:57:20 -0700 Subject: [PATCH 124/630] Add latest changes (DDL namespace, optional `transaction?` argument) --- CHANGES.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 7384921d..41b116f8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,11 @@ Changes coming in 0.3.0-alpha5 +* Make transaction? boolean optional in various db-do-* functions + * It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with +* Create clojure.java.jdbc.ddl namespace + * Add create-table and drop-table + * Deprecate create-table, create-table-ddl and drop-table in main namespace + * More DDL is coming soon * Update README to clarify PostgreSQL instructions. * Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) * Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) From 7fc9a32de550b4daa4aae5671b9f4b4fa7469e6f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 22 Jun 2013 21:57:50 -0700 Subject: [PATCH 125/630] Add notes about DSL (SQL, DDL namespaces) and recommendations for HoneySQL and Korma. --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bdc496b..b7dbf88d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ clojure.java.jdbc ======================================== -A Clojure wrapper for JDBC-based access to databases. +A low-level Clojure wrapper for JDBC-based access to databases. A minimal DSL is provided to generate basic SQL (in clojure.java.jdbc.sql) and basic DDL (in clojure.java.jdbc.ddl). For a more sophisticated DSL that is compatible with this library, consider: + +* [HoneySQL](https://github.com/jkk/honeysql) +* [Korma](http://sqlkorma.com) Formerly known as clojure.contrib.sql. From fbfa5492c646a0b76204eb261750ed121930c01e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 24 Jun 2013 10:13:42 -0700 Subject: [PATCH 126/630] Added cautionary note that auxiliary documentation will be moving to clojure-doc.org soon! --- doc/clojure/java/jdbc/ConnectionPooling.md | 4 +++- doc/clojure/java/jdbc/NameMapping.md | 2 ++ doc/clojure/java/jdbc/UsingDDL.md | 2 ++ doc/clojure/java/jdbc/UsingSQL.md | 2 ++ 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/doc/clojure/java/jdbc/ConnectionPooling.md b/doc/clojure/java/jdbc/ConnectionPooling.md index 502e78b6..2dc9e2c8 100644 --- a/doc/clojure/java/jdbc/ConnectionPooling.md +++ b/doc/clojure/java/jdbc/ConnectionPooling.md @@ -1,3 +1,5 @@ +*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* + # Connection Pooling clojure.java.jdbc does not provide connection pooling directly but it is relatively easy to add to your project. The following example shows how to configure connection pooling use c3p0. ## Add the c3p0 dependency @@ -49,4 +51,4 @@ Now you can create a single connection pool: (defn db-connection [] @pooled-db) -And then call (db-connection) wherever you need access to it. \ No newline at end of file +And then call (db-connection) wherever you need access to it. diff --git a/doc/clojure/java/jdbc/NameMapping.md b/doc/clojure/java/jdbc/NameMapping.md index 35499780..621f9d18 100644 --- a/doc/clojure/java/jdbc/NameMapping.md +++ b/doc/clojure/java/jdbc/NameMapping.md @@ -1,3 +1,5 @@ +*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* + # Mapping Keywords to/from Entity Names Entity names in SQL may be specified as strings or as keywords. It's convenient to represent records as Clojure maps with keywords for the keys but this means that a mapping is required when moving from Clojure to SQL and back again. Historically, clojure.contrib.sql simply called (name) on keywords passed in and used clojure.core/resultset-seq to convert Java ResultSet objects back to Clojure maps, which had the side-effect of lowercasing all entity names as they became keywords. Whilst that is still the default behavior of clojure.java.jdbc, it is now possible to override this behavior in a couple of ways. ## Quoted Entities diff --git a/doc/clojure/java/jdbc/UsingDDL.md b/doc/clojure/java/jdbc/UsingDDL.md index 03a236d3..0504fab3 100644 --- a/doc/clojure/java/jdbc/UsingDDL.md +++ b/doc/clojure/java/jdbc/UsingDDL.md @@ -1,3 +1,5 @@ +*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* + # Manipulating Tables with DDL Currently you can create and drop tables using clojure.java.jdbc. To see how to manipulate data with SQL, see [Manipulating Data with SQL](https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/UsingSQL.md). ## Creating a table diff --git a/doc/clojure/java/jdbc/UsingSQL.md b/doc/clojure/java/jdbc/UsingSQL.md index 5b9ddbc8..d53dfc04 100644 --- a/doc/clojure/java/jdbc/UsingSQL.md +++ b/doc/clojure/java/jdbc/UsingSQL.md @@ -1,3 +1,5 @@ +*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* + # Manipulating Data with SQL Here are some examples of using clojure.java.jdbc to manipulate data with SQL. These examples assume a simple table called fruit (see [Manipulating Tables with DDL](https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/UsingDDL.md)). From 563c9a2c4d8ed03f8335df06435a0561a56b242d Mon Sep 17 00:00:00 2001 From: Matt Oquist Date: Sun, 23 Jun 2013 21:48:57 -0400 Subject: [PATCH 127/630] Add fns ddl/create-index and ddl/drop-index. Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc/ddl.clj | 30 +++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/ddl.clj b/src/main/clojure/clojure/java/jdbc/ddl.clj index 947727e4..7231e333 100644 --- a/src/main/clojure/clojure/java/jdbc/ddl.clj +++ b/src/main/clojure/clojure/java/jdbc/ddl.clj @@ -47,4 +47,32 @@ not very sophisticated." } (defn drop-table "Given a table name, return the DDL string for dropping that table." [name] - (format "DROP TABLE %s" (sql/as-str identity name))) \ No newline at end of file + (format "DROP TABLE %s" (sql/as-str identity name))) + +(defn create-index + "Given an index name, table name, vector of column names, and + (optional) is-unique, return the DDL string for creating an index. + + Examples: + (create-index :indexname :tablename [:field1 :field2] :unique) + \"CREATE UNIQUE INDEX indexname ON tablename (field1, field2)\" + + (create-index :indexname :tablename [:field1 :field2]) + \"CREATE INDEX indexname ON tablename (field1, field2)\"" + [index-name table-name cols & is-unique] + (let [cols-string (apply str + (interpose ", " + (map (sql/as-str identity) + cols))) + is-unique (if is-unique "UNIQUE" "")] + (format "CREATE %s INDEX %s ON %s (%s)" + is-unique + (sql/as-str identity index-name) + (sql/as-str identity table-name) + cols-string))) + +(defn drop-index + "Given an index name, return the DDL string for dropping that index." + [name] + (format "DROP INDEX %s" (sql/as-str identity name))) + From 7de571d73f7bf979c3558e5656f572a62b973ce7 Mon Sep 17 00:00:00 2001 From: Matt Oquist Date: Sun, 23 Jun 2013 22:06:50 -0400 Subject: [PATCH 128/630] add tests for ddl/create-* and ddl/drop-* fns Signed-off-by: Sean Corfield --- src/test/clojure/clojure/java/test_ddl.clj | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/test/clojure/clojure/java/test_ddl.clj diff --git a/src/test/clojure/clojure/java/test_ddl.clj b/src/test/clojure/clojure/java/test_ddl.clj new file mode 100644 index 00000000..46cca9bd --- /dev/null +++ b/src/test/clojure/clojure/java/test_ddl.clj @@ -0,0 +1,46 @@ +;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; test_ddl.clj +;; +;; This namespace contains tests of all the functions within +;; java.jdbc.ddl and does not rely on any databases. +;; +;; scgilardi (gmail) +;; Created 13 September 2008 +;; +;; seancorfield (gmail) +;; Migrated from clojure.contrib.test-sql 17 April 2011 +;; +;; moquist (gmail) +;; Migrated test-create-table from clojure.java.test-utilities, added +;; new tests. 23 June 2013 + +(ns clojure.java.test-ddl + (:use clojure.test) + (:require [clojure.java.jdbc.ddl :as ddl])) + +(deftest test-create-table + (is (= "CREATE TABLE table (col1 int, col2 int)" + (ddl/create-table :table ["col1 int"] [:col2 :int]))) + (is (= "CREATE TABLE table (col1 int, col2 int) ENGINE=MyISAM" + (ddl/create-table :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM")))) + +(deftest test-drop-table + (is (= "DROP TABLE table") + (ddl/drop-table :table))) + +(deftest test-create-index + (is (= "CREATE INDEX index ON table (col1, col2)" + (ddl/create-index :index :table [:col1 "col2"]))) + (is (= "CREATE UNIQUE INDEX index ON table (col1, col2)" + (ddl/create-index :index :table [:col1 "col2"] :unique)))) + +(deftest test-drop-index + (is (= "DROP INDEX index") + (ddl/drop-index :index))) From 45f3d990040a5b8e6ec8bd322fe8c04cab4bd933 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 27 Jun 2013 10:25:00 -0700 Subject: [PATCH 129/630] Some whitespace cleanup. --- src/main/clojure/clojure/java/jdbc/ddl.clj | 6 +++--- src/test/clojure/clojure/java/test_ddl.clj | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/ddl.clj b/src/main/clojure/clojure/java/jdbc/ddl.clj index 7231e333..dc21efa1 100644 --- a/src/main/clojure/clojure/java/jdbc/ddl.clj +++ b/src/main/clojure/clojure/java/jdbc/ddl.clj @@ -58,14 +58,14 @@ not very sophisticated." } \"CREATE UNIQUE INDEX indexname ON tablename (field1, field2)\" (create-index :indexname :tablename [:field1 :field2]) - \"CREATE INDEX indexname ON tablename (field1, field2)\"" + \"CREATE INDEX indexname ON tablename (field1, field2)\"" [index-name table-name cols & is-unique] (let [cols-string (apply str (interpose ", " (map (sql/as-str identity) cols))) - is-unique (if is-unique "UNIQUE" "")] - (format "CREATE %s INDEX %s ON %s (%s)" + is-unique (if is-unique "UNIQUE " "")] + (format "CREATE %sINDEX %s ON %s (%s)" is-unique (sql/as-str identity index-name) (sql/as-str identity table-name) diff --git a/src/test/clojure/clojure/java/test_ddl.clj b/src/test/clojure/clojure/java/test_ddl.clj index 46cca9bd..f56411c4 100644 --- a/src/test/clojure/clojure/java/test_ddl.clj +++ b/src/test/clojure/clojure/java/test_ddl.clj @@ -36,7 +36,7 @@ (ddl/drop-table :table))) (deftest test-create-index - (is (= "CREATE INDEX index ON table (col1, col2)" + (is (= "CREATE INDEX index ON table (col1, col2)" (ddl/create-index :index :table [:col1 "col2"]))) (is (= "CREATE UNIQUE INDEX index ON table (col1, col2)" (ddl/create-index :index :table [:col1 "col2"] :unique)))) From 3e2e63f43c1bdfbacd92b4c3cf83e9d57e4523f8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 27 Jun 2013 10:32:44 -0700 Subject: [PATCH 130/630] Added note of new DDL functions --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 41b116f8..1f5544c3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha5 +* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist * Make transaction? boolean optional in various db-do-* functions * It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with * Create clojure.java.jdbc.ddl namespace From cda5f1d99e4a05c22e05a791d97044129a2e17e0 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 28 Jun 2013 15:46:03 -0700 Subject: [PATCH 131/630] Added Leiningen support to make it easier to test / work with locally --- .gitignore | 1 + project.clj | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 project.clj diff --git a/.gitignore b/.gitignore index 69d99cab..4d4f0778 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ target test-all.sh settings.xml /clojure_test_sqlite +/.lein-failures diff --git a/project.clj b/project.clj new file mode 100644 index 00000000..d4cc558b --- /dev/null +++ b/project.clj @@ -0,0 +1,26 @@ +(defproject org.clojure/java.jdbc "0.3.0-SNAPSHOT" + :description "A low-level Clojure wrapper for JDBC-based access to databases." + :parent [org.clojure/pom.contrib "0.1.2"] + :url "https://github.com/clojure/java.jdbc" + :license {:name "Eclipse Public License" + :url "http://www.eclipse.org/legal/epl-v10.html"} + :source-paths ["src/main/clojure"] + :test-paths ["src/test/clojure"] + :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} + :dependencies [[org.clojure/clojure "1.6.0-master-SNAPSHOT"] + [mysql/mysql-connector-java "5.1.25"] + [org.apache.derby/derby "10.8.1.2"] + [hsqldb "1.8.0.10"] + [postgresql "8.4-702.jdbc4"] + [org.xerial/sqlite-jdbc "3.7.2"] + [net.sourceforge.jtds/jtds "1.2.4"] + ;; if you have the MS driver in your local repo + ;; [sqljdbc4 "3.0"] + ] + :profiles {:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} + :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} + :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} + :1.6 {:dependencies [[org.clojure/clojure "1.6.0-master-SNAPSHOT"]]}} + :aliases {"test-all" ["with-profile" "test,1.3:test,1.4:test,1.5:test,1.6" "test"] + "check-all" ["with-profile" "1.3:1.4:1.5:1.6" "check"]} + :min-lein-version "2.0.0") From 0d2f00b2e974d4ee5cec865bd7879a9075c06e76 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 28 Jun 2013 16:52:13 -0700 Subject: [PATCH 132/630] Add 1.2.1 for test/check since we still support it. --- project.clj | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/project.clj b/project.clj index d4cc558b..be3fc44e 100644 --- a/project.clj +++ b/project.clj @@ -17,10 +17,11 @@ ;; if you have the MS driver in your local repo ;; [sqljdbc4 "3.0"] ] - :profiles {:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} + :profiles {:1.2 {:dependencies [[org.clojure/clojure "1.2.1"]]} + :1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0-master-SNAPSHOT"]]}} - :aliases {"test-all" ["with-profile" "test,1.3:test,1.4:test,1.5:test,1.6" "test"] - "check-all" ["with-profile" "1.3:1.4:1.5:1.6" "check"]} + :aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6" "test"] + "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6" "check"]} :min-lein-version "2.0.0") From b5ea1a084e46a55baf4dafecc0a4a4f4a2445f65 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 9 Jul 2013 12:10:43 -0500 Subject: [PATCH 133/630] Add link to clojure-doc.org section for java.jdbc. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b7dbf88d..b5019df5 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ A low-level Clojure wrapper for JDBC-based access to databases. A minimal DSL is Formerly known as clojure.contrib.sql. +Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). + Releases and Dependency Information ======================================== From e53188c4586c01c40306bb7602679abd8f1b5481 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 9 Jul 2013 12:13:01 -0500 Subject: [PATCH 134/630] Delete old documentation. Add new location to namespace docstring. --- doc/clojure/java/jdbc/ConnectionPooling.md | 54 ------ doc/clojure/java/jdbc/NameMapping.md | 41 ----- doc/clojure/java/jdbc/UsingDDL.md | 38 ----- doc/clojure/java/jdbc/UsingSQL.md | 181 --------------------- src/main/clojure/clojure/java/jdbc.clj | 4 + 5 files changed, 4 insertions(+), 314 deletions(-) delete mode 100644 doc/clojure/java/jdbc/ConnectionPooling.md delete mode 100644 doc/clojure/java/jdbc/NameMapping.md delete mode 100644 doc/clojure/java/jdbc/UsingDDL.md delete mode 100644 doc/clojure/java/jdbc/UsingSQL.md diff --git a/doc/clojure/java/jdbc/ConnectionPooling.md b/doc/clojure/java/jdbc/ConnectionPooling.md deleted file mode 100644 index 2dc9e2c8..00000000 --- a/doc/clojure/java/jdbc/ConnectionPooling.md +++ /dev/null @@ -1,54 +0,0 @@ -*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* - -# Connection Pooling -clojure.java.jdbc does not provide connection pooling directly but it is relatively easy to add to your project. The following example shows how to configure connection pooling use c3p0. -## Add the c3p0 dependency -If you're using Leiningen, you can just add the following to your dependencies: - - [c3p0/c3p0 "0.9.1.2"] - -In Maven, it would be: - - - c3p0 - c3p0 - 0.9.1.2 - - -## Create the pooled datasource from your db-spec -Define your db-spec as usual, for example (for MySQL): - - (def db-spec - {:classname "com.mysql.jdbc.Driver" - :subprotocol "mysql" - :subname "//127.0.0.1:3306/mydb" - :user "myaccount" - :password "secret"}) - -Import the c3p0 class as part of your namespace declaration, for example: - - (ns example.db - (:import com.mchange.v2.c3p0.ComboPooledDataSource)) - -Define a function that creates a pooled datasource: - - (defn pool - [spec] - (let [cpds (doto (ComboPooledDataSource.) - (.setDriverClass (:classname spec)) - (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) - (.setUser (:user spec)) - (.setPassword (:password spec)) - ;; expire excess connections after 30 minutes of inactivity: - (.setMaxIdleTimeExcessConnections (* 30 60)) - ;; expire connections after 3 hours of inactivity: - (.setMaxIdleTime (* 3 60 60)))] - {:datasource cpds})) - -Now you can create a single connection pool: - - (def pooled-db (delay (pool db-spec))) - - (defn db-connection [] @pooled-db) - -And then call (db-connection) wherever you need access to it. diff --git a/doc/clojure/java/jdbc/NameMapping.md b/doc/clojure/java/jdbc/NameMapping.md deleted file mode 100644 index 621f9d18..00000000 --- a/doc/clojure/java/jdbc/NameMapping.md +++ /dev/null @@ -1,41 +0,0 @@ -*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* - -# Mapping Keywords to/from Entity Names -Entity names in SQL may be specified as strings or as keywords. It's convenient to represent records as Clojure maps with keywords for the keys but this means that a mapping is required when moving from Clojure to SQL and back again. Historically, clojure.contrib.sql simply called (name) on keywords passed in and used clojure.core/resultset-seq to convert Java ResultSet objects back to Clojure maps, which had the side-effect of lowercasing all entity names as they became keywords. Whilst that is still the default behavior of clojure.java.jdbc, it is now possible to override this behavior in a couple of ways. -## Quoted Entities -The first problem that the old approach exposed was when table names or column names were the same as a SQL keyword. Databases provide a way to quote identifier names so that entity names do not get treated as SQL keywords (often referred to as 'stropping'). Unfortunately, the way quoting works tends to be vendor-specific so that Microsoft SQL Server accepts \[name\] and "name" whilst MySQL traditionally uses \`name\` (although recent versions also accept "name"). In order to support multiple approaches to quoting, clojure.java.jdbc supports the concept of identifier functions and entity functions. The former are used to convert entity names in result sets into Clojure identifiers. The latter are used to convert Clojure identifiers (table names, keys in maps) into SQL entity names. - -The function clojure.java.jdbc.sql/quoted can be used to create an entity function. It takes a quote spec and returns a function that will quote its argument appropriately. Other entity functions are clojure.java.jdbc.sql/as-is which leaves names untouched (and is the default) and clojure.java.jdbc.sql/lower-case which lowercases name (and is the default identifier function for result-set-seq. - -A quote spec is either a single character or a pair of characters in a vector. For the former, the entity name is wrapped in a pair of that character. For the latter, the entity name is wrapped in the specified pair: - - ((s/quoted \`) "name") ;; produces "`name`" - ((s/quoted [\[ \]]) "name") ;; produces "[name]" - -Code can either be passed an entity function or be wrapped in the *entities* macro to influence how keywords are mapped to entity names: - - (j/insert! mysql-db :fruit - {:name "Pear" :appearance "green" :cost 99} - :entities (s/quoted \`)) - - (s/entities (s/quoted \`) - (j/insert! mysql-db :fruit - {:name "Pear" :appearance "green" :cost 99})) - - ;; INSERT INTO `fruit` ( `name`, `appearance`, `cost` ) - ;; VALUES ( 'Pear', 'green', 99 ) - -Note that if a string is used for an entity name, rather than a keyword, it is passed through unchanged, on the assumption that if you're explicitly passing strings, you want to control exactly what goes into the SQL. -## Entity to Identifier -The second problem with the old approach was that in returned results, all entity names were mapped to lowercase so any case sensitivity in the original entity names was lost. In addition to the option to determine a quoting strategy, clojure.java.jdbc support identifier functions for *query* and *result-set-seq*. - - (j/query mysql-db - (s/select * :fruit) - :identifiers clojure.string/upper-case) - - (s/identifiers clojure.string/upper-case - (j/query mysql-db - (s/select * :fruit))) - - ;; ({:GRADE nil, :COST 24, :APPEARANCE "rosy", :NAME "Apple", :ID 1} - ;; ...) diff --git a/doc/clojure/java/jdbc/UsingDDL.md b/doc/clojure/java/jdbc/UsingDDL.md deleted file mode 100644 index 0504fab3..00000000 --- a/doc/clojure/java/jdbc/UsingDDL.md +++ /dev/null @@ -1,38 +0,0 @@ -*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* - -# Manipulating Tables with DDL -Currently you can create and drop tables using clojure.java.jdbc. To see how to manipulate data with SQL, see [Manipulating Data with SQL](https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/UsingSQL.md). -## Creating a table -To create a table, use *create-table* with the table name and a vector for each column spec. Currently, table-level specifications are not supported. - - (defn create-fruit - "Create a table" - [] - (sql/create-table - :fruit - [:name "varchar(32)" "PRIMARY KEY"] - [:appearance "varchar(32)"] - [:cost :int] - [:grade :real])) - -## Dropping a table -To drop a table, use *drop-table* with the table name. - - (defn drop-fruit - "Drop a table" - [] - (try - (sql/drop-table :fruit) - (catch Exception _))) - -## Accessing table metadata -To retrieve the metadata for a table, you can operate on the connection itself. In future, functions may be added to make this easier. - - (defn db-get-tables - "Demonstrate getting table info" - [db] - (into [] - (j/result-set-seq - (-> (j/get-connection db) - (.getMetaData) - (.getTables nil nil nil (into-array ["TABLE" "VIEW"])))))) diff --git a/doc/clojure/java/jdbc/UsingSQL.md b/doc/clojure/java/jdbc/UsingSQL.md deleted file mode 100644 index d53dfc04..00000000 --- a/doc/clojure/java/jdbc/UsingSQL.md +++ /dev/null @@ -1,181 +0,0 @@ -*Note: this documentation will soon move to [clojure-doc.org](http://clojure-doc.org) where it can be more easily maintained and accept community contributions.* - -# Manipulating Data with SQL -Here are some examples of using clojure.java.jdbc to manipulate data with SQL. -These examples assume a simple table called fruit (see [Manipulating Tables with DDL](https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/UsingDDL.md)). -## Inserting multiple rows -If you want to insert complete rows, you can use *insert!* and provide the values as a simple vector for each row. Every column's value must be present in the same order the columns are declared in the table. This performs a series of insert statement. If you attempt to insert a single row, a map of the generated keys will be returned. - - (defn insert-rows-fruit - "Insert complete rows" - [db] - (j/insert! db - :fruit - nil ; column names not supplied - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])) - ;; (1 1 1 1) - row counts modified - -## Inserting partial rows -If you want to insert rows but only specify some columns' values, you can use *insert!* and provide the names of the columns following by vectors containing values for those columns. This performs a single insert statement. If you attempt to insert a single row, a map of the generated keys will be returned. - - (defn insert-values-fruit - "Insert rows with values for only specific columns" - [db] - (j/insert! db - :fruit - [:name :cost] - ["Mango" 722] - ["Feijoa" 441])) - -## Inserting a record -If you want to insert a single record, you can use *insert!* and specify the columns and their values as a map. This performs a single insert statement. A map of the generated keys will be returned. - - (defn insert-record-fruit - "Insert a single record, map from keys specifying columsn to values" - [db] - (j/insert! db - :fruit - {:name "Pear" :appearance "green" :cost 99})) - -## Inserting multiple records -If you want to insert multiple records, you can use *insert!* and specify each record as a map of columns and their values. This performs a separate insert statement for each record. The generated keys are returned in a sequence of maps. - - (defn insert-records-fruit - "Insert records, maps from keys specifying columns to values" - [db] - (j/insert! db - :fruit - {:name "Pomegranate" :appearance "fresh" :cost 585} - {:name "Kiwifruit" :grade 93})) - -## Using transactions -You can write multiple operations in a transaction to ensure they are either all performed, or all rolled back. - - (defn db-write - "Write initial values to the database as a transaction" - [db] - (j/db-transaction [t-con db] - (insert-rows-fruit t-con) - (insert-values-fruit t-con) - (insert-records-fruit t-con))) - -The *db-transaction* macro creates a transaction-aware connection from the database specification and that should be used in the body of the transaction code. - -## Reading and processing rows -To execute code against each row in a result set, use *query* with SQL. - - (defn db-read - "Read the entire fruit table" - [db] - (j/query db - ["SELECT * FROM fruit"] - :row-fn println)) - - (defn db-read-all - "Return all the rows of the fruit table as a vector" - [db] - (j/query db - ["SELECT * FROM fruit"] - :as-arrays? true)) - - ;; ([:id :name :appearance :cost :grade] - ;; [1 "Apple" "red" 59 87.0] - ;; [2 "Banana" "yellow" 29 92.2] - ;; ...) - - (defn db-grade-range - "Print rows describing fruit that are within a grade range" - [db min max] - (j/query db - [(str "SELECT name, cost, grade " - "FROM fruit " - "WHERE grade >= ? AND grade <= ?") - min max] - :row-fn println)) - - (defn db-grade-a - "Print rows describing all grade a fruit (grade between 90 and 100)" - [db] - (db-grade-range db 90 100)) - -## Updating values across a table -To update column values based on a SQL predicate, use *update!* with a SQL where clause and a map of columns to new values. The result is a sequence of update counts, indicating the number of records affected by each update (in this case, a single update and therefore a single count in the sequence). - - (defn db-update-appearance-cost - "Update the appearance and cost of the named fruit" - [db name appearance cost] - (j/update! mysql-db - :fruit - {:appearance appearance :cost cost} - ["name=?" name])) - - (defn db-update - "Update two fruits as a transaction" - [db] - (j/db-transaction [t-con db] - (db-update-appearance-cost t-con "Banana" "bruised" 14) - (db-update-appearance-cost t-con "Feijoa" "green" 400))) - -## Updating values or Inserting records conditionally -If you want to update existing records that match a SQL predicate or insert a new record if no existing records match, you can use a transaction wrapped around an *update!* and a conditional *insert!*. -use *update-or-insert-values* with a SQL where clause and a map of columns to values. This calls *update-values* first and if no rows were updated, this calls *insert-values*. The result is either the sequence of update counts from the update or the sequence of generated key maps from the insert. - - (defn db-update-or-insert - "Updates or inserts a fruit" - [db record where-clause] - (j/db-transaction [t-con db] - (let [result (j/update! t-con :fruit record where-clause)] - (if (zero? (first result)) - (j/insert! t-con :fruit record) - result)))) - - (db-update-or-insert mysql-db - {:name "Cactus" :appearance "Spiky" :cost 2000} - ["name = ?" "Cactus"]) - ;; inserts Cactus - (db-update-or-insert mysql-db - {:name "Cactus" :appearance "Spiky" :cost 2500} - ["name = ?" "Cactus"]) - ;; updates the Cactus we just inserted - -## Exception Handling and Transaction Rollback -Transactions are rolled back if an exception is thrown, as shown in these examples. - - (defn db-exception - "Demonstrate rolling back a partially completed transaction on exception" - [db] - (j/db-transaction [t-con db] - (j/insert! t-con - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - ;; at this point the insert-values call is complete, but the transaction - ;; is not. the exception will cause it to roll back leaving the database - ;; untouched. - (throw (Exception. "sql/test exception"))))) - -Transactions can also be set explicitly to rollback instead of commit: - - (defn db-rollback - "Demonstrate a rollback-only trasaction" - [db] - (j/db-transaction [t-con db] - (prn "is-rollback-only" (j/db-is-rollback-only t-con)) - (j/db-set-rollback-only! t-con) - (j/insert! t-con - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - (prn "is-rollback-only" (j/db-is-rollback-only t-con)) - (j/query t-con - ["SELECT * FROM fruit"] - :row-fn println)) - (prn) - (j/query db - ["SELECT * FROM fruit"] - :row-fn println)) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 406ec4c1..a9f2a13b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -37,6 +37,10 @@ are the parameter values to be substituted. In general, operations return the number of rows affected, except for a single record insert where any generated keys are returned (as a map). +For more documentation, see: + +http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html + As of release 0.3.0, the API has undergone a major overhaul and most of the original API has been deprecated in favor of a more idiomatic API, and a minimal DSL for generating SQL has been added as an option. The original From 95cac6eb9298c110181b6ea8fd6f8bef9544129d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 7 Sep 2013 14:17:43 -0700 Subject: [PATCH 135/630] Minor indentation fix. --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a9f2a13b..9da78bf3 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -270,7 +270,7 @@ made at some future date." } keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) make-cols-unique - (map (comp keyword identifiers))) + (map (comp keyword identifiers))) row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As From 4890d4ced13c6cba251d366e12459d84ea86acb7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Sep 2013 11:59:18 -0700 Subject: [PATCH 136/630] Use ^{:once true} fn* instead of plain fn to reduce memory leaks due to closures. --- src/main/clojure/clojure/java/jdbc.clj | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9da78bf3..945cb90a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -491,7 +491,7 @@ made at some future date." } See db-transaction* for more details." [binding & body] `(db-transaction* ~(second binding) - (fn [~(first binding)] ~@body))) + (^{:once true} fn* [~(first binding)] ~@body))) (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands @@ -638,11 +638,11 @@ made at some future date." } row-fn identity identifiers sql/lower-case}}] (db-with-query-results* db (vec sql-params) - (fn [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (vec (map row-fn (rest rs)))) - (map row-fn rs)))) + (^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (vec (map row-fn (rest rs)))) + (map row-fn rs)))) identifiers as-arrays?)) @@ -762,7 +762,7 @@ made at some future date." } :deprecated "0.3.0"} with-connection [db-spec & body] - `(with-connection* ~db-spec (fn [] ~@body))) + `(with-connection* ~db-spec (^{:once true} fn* [] ~@body))) (defn ^{:doc "Evaluates func as a transaction on the open database connection. Any @@ -809,7 +809,7 @@ made at some future date." } :deprecated "0.3.0"} transaction [& body] - `(transaction* (fn [] ~@body))) + `(transaction* (^{:once true} fn* [] ~@body))) (defn ^{:doc "Marks the outermost transaction such that it will rollback rather than @@ -1001,7 +1001,7 @@ made at some future date." } :deprecated "0.3.0"} with-query-results [results sql-params & body] - `(with-query-results* ~sql-params (fn [~results] ~@body))) + `(with-query-results* ~sql-params (^{:once true} fn* [~results] ~@body))) (defn ^{:doc "Given a naming strategy and a string, return the string as a From a04c427eddab2b317197addf1053730963cb6653 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Sep 2013 12:35:00 -0700 Subject: [PATCH 137/630] A few more 'once' functions and a little layout cleanup. --- src/main/clojure/clojure/java/jdbc.clj | 48 ++++++++++++++------------ 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 945cb90a..3ac01820 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -242,7 +242,8 @@ made at some future date." } [cols] (if (or (empty? cols) (apply distinct? cols)) cols - (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) + (reduce (fn [unique-cols col-name] + (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default @@ -525,18 +526,19 @@ made at some future date." } (if-let [^java.sql.Connection con (db-find-connection db)] (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] (set-parameters stmt param-group) - (letfn [(exec-and-return-keys [] - (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))] + (let [exec-and-return-keys + (^{:once true} fn* [] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (result-set-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] (if transaction? (db-transaction [t-db (add-connection db (.getConnection stmt))] (exec-and-return-keys)) @@ -607,12 +609,12 @@ made at some future date." } options-are-first (rest (rest sql-params)) :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special))) - run-query-with-params (fn [^PreparedStatement stmt] - (set-parameters stmt params) - (with-open [rset (.executeQuery stmt)] - (func (result-set-seq rset - :identifiers identifiers - :as-arrays? as-arrays?))))] + run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] + (set-parameters stmt params) + (with-open [rset (.executeQuery stmt)] + (func (result-set-seq rset + :identifiers identifiers + :as-arrays? as-arrays?))))] (if (instance? PreparedStatement special) (let [^PreparedStatement stmt special] (run-query-with-params stmt)) @@ -653,10 +655,10 @@ made at some future date." } [db sql-params & {:keys [transaction? multi?] :or {transaction? true multi? false}}] (let [execute-helper - (fn [db] - (if multi? - (apply db-do-prepared db transaction? (first sql-params) (rest sql-params)) - (db-do-prepared db transaction? (first sql-params) (rest sql-params))))] + (^{:once true} fn* [db] + (if multi? + (apply db-do-prepared db transaction? (first sql-params) (rest sql-params)) + (db-do-prepared db transaction? (first sql-params) (rest sql-params))))] (if-let [con (db-find-connection db)] (execute-helper db) (with-open [^java.sql.Connection con (get-connection db)] From 3925b98d67f12edf6fd94e03d1ff7e333f71aa9e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Sep 2013 14:36:04 -0700 Subject: [PATCH 138/630] Updated changes to include recent commits. --- CHANGES.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 1f5544c3..01b1d883 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,8 @@ Changes coming in 0.3.0-alpha5 +* Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). +* Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) +* Added Leiningen support for easier development/testing (Maven is still the primary build tool). * Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist * Make transaction? boolean optional in various db-do-* functions * It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with From 1602c824505608b8192f798bac3eb7db0a9599a2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 15 Sep 2013 13:37:42 -0700 Subject: [PATCH 139/630] Fixes JDBC-53 by supporting entities as a keyword argument and in the walk macro --- src/main/clojure/clojure/java/jdbc/ddl.clj | 33 ++++++++++-------- src/main/clojure/clojure/java/jdbc/sql.clj | 3 +- src/test/clojure/clojure/java/test_ddl.clj | 40 +++++++++++++++++++--- 3 files changed, 56 insertions(+), 20 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/ddl.clj b/src/main/clojure/clojure/java/jdbc/ddl.clj index dc21efa1..2c359c2a 100644 --- a/src/main/clojure/clojure/java/jdbc/ddl.clj +++ b/src/main/clojure/clojure/java/jdbc/ddl.clj @@ -29,25 +29,27 @@ not very sophisticated." } "Given a table name and column specs with an optional table-spec return the DDL string for creating that table." [name & specs] - (let [split-specs (partition-by #(= :table-spec %) specs) - col-specs (first split-specs) - table-spec (first (second (rest split-specs))) + (let [col-specs (take-while (fn [s] + (not (or (= :table-spec s) + (= :entities s)))) specs) + other-specs (drop (count col-specs) specs) + {:keys [table-spec entities] :or {entities sql/as-is}} other-specs table-spec-str (or (and table-spec (str " " table-spec)) "") specs-to-string (fn [specs] (apply str - (map (sql/as-str identity) + (map (sql/as-str entities) (apply concat (interpose [", "] (map (partial interpose " ") specs))))))] (format "CREATE TABLE %s (%s)%s" - (sql/as-str identity name) + (sql/as-str entities name) (specs-to-string col-specs) table-spec-str))) (defn drop-table "Given a table name, return the DDL string for dropping that table." - [name] - (format "DROP TABLE %s" (sql/as-str identity name))) + [name & {:keys [entities] :or {entities sql/as-is}}] + (format "DROP TABLE %s" (sql/as-str entities name))) (defn create-index "Given an index name, table name, vector of column names, and @@ -59,20 +61,23 @@ not very sophisticated." } (create-index :indexname :tablename [:field1 :field2]) \"CREATE INDEX indexname ON tablename (field1, field2)\"" - [index-name table-name cols & is-unique] - (let [cols-string (apply str + [index-name table-name cols & specs] + (let [is-unique (seq (filter #(= :unique %) specs)) + entities-spec (drop-while #(not= :entities %) specs) + {:keys [entities] :or {entities sql/as-is}} (take 2 entities-spec) + cols-string (apply str (interpose ", " - (map (sql/as-str identity) + (map (sql/as-str entities) cols))) is-unique (if is-unique "UNIQUE " "")] (format "CREATE %sINDEX %s ON %s (%s)" is-unique - (sql/as-str identity index-name) - (sql/as-str identity table-name) + (sql/as-str entities index-name) + (sql/as-str entities table-name) cols-string))) (defn drop-index "Given an index name, return the DDL string for dropping that index." - [name] - (format "DROP INDEX %s" (sql/as-str identity name))) + [name & {:keys [entities] :or {entities sql/as-is}}] + (format "DROP INDEX %s" (sql/as-str entities name))) diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj index 142b0548..4cc75f2a 100644 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ b/src/main/clojure/clojure/java/jdbc/sql.clj @@ -86,7 +86,8 @@ and update! high-level operations within clojure.java.jdbc directly." } #{"delete" "delete!" "insert" "insert!" "select" "join" "where" "order-by" - "update" "update!"}) + "update" "update!" + "create-table" "drop-table" "create-index" "drop-index"}) (def ^{:private true :doc "Symbols that need to be processed for identifiers within their forms."} diff --git a/src/test/clojure/clojure/java/test_ddl.clj b/src/test/clojure/clojure/java/test_ddl.clj index f56411c4..fd3b2e36 100644 --- a/src/test/clojure/clojure/java/test_ddl.clj +++ b/src/test/clojure/clojure/java/test_ddl.clj @@ -23,24 +23,54 @@ (ns clojure.java.test-ddl (:use clojure.test) - (:require [clojure.java.jdbc.ddl :as ddl])) + (:require [clojure.java.jdbc.ddl :as ddl] + [clojure.java.jdbc.sql :as sql] + [clojure.string :as str])) (deftest test-create-table (is (= "CREATE TABLE table (col1 int, col2 int)" (ddl/create-table :table ["col1 int"] [:col2 :int]))) + (is (= "CREATE TABLE TABLE (col1 int, COL2 INT)" + (ddl/create-table :table ["col1 int"] [:col2 :int] :entities str/upper-case))) + (is (= "CREATE TABLE TABLE (col1 int, COL2 INT)" + (sql/entities str/upper-case + (ddl/create-table :table ["col1 int"] [:col2 :int])))) (is (= "CREATE TABLE table (col1 int, col2 int) ENGINE=MyISAM" - (ddl/create-table :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM")))) + (ddl/create-table :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM"))) + (is (= "CREATE TABLE TABLE (COL1 int, col2 INT) ENGINE=MyISAM" + (ddl/create-table :table [:col1 "int"] ["col2" :int] :entities str/upper-case :table-spec "ENGINE=MyISAM"))) + (is (= "CREATE TABLE TABLE (COL1 int, col2 INT) ENGINE=MyISAM" + (ddl/create-table :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM" :entities str/upper-case)))) (deftest test-drop-table (is (= "DROP TABLE table") - (ddl/drop-table :table))) + (ddl/drop-table :table)) + (is (= "DROP TABLE TABLE") + (ddl/drop-table :table :entities str/upper-case)) + (is (= "DROP TABLE TABLE") + (sql/entities str/upper-case + (ddl/drop-table :table)))) (deftest test-create-index (is (= "CREATE INDEX index ON table (col1, col2)" (ddl/create-index :index :table [:col1 "col2"]))) + (is (= "CREATE INDEX INDEX ON TABLE (COL1, col2)" + (ddl/create-index :index :table [:col1 "col2"] :entities str/upper-case))) + (is (= "CREATE INDEX INDEX ON TABLE (COL1, col2)" + (sql/entities str/upper-case + (ddl/create-index :index :table [:col1 "col2"])))) (is (= "CREATE UNIQUE INDEX index ON table (col1, col2)" - (ddl/create-index :index :table [:col1 "col2"] :unique)))) + (ddl/create-index :index :table [:col1 "col2"] :unique))) + (is (= "CREATE UNIQUE INDEX INDEX ON TABLE (COL1, col2)" + (ddl/create-index :index :table [:col1 "col2"] :unique :entities str/upper-case))) + (is (= "CREATE UNIQUE INDEX INDEX ON TABLE (COL1, col2)" + (ddl/create-index :index :table [:col1 "col2"] :entities str/upper-case :unique)))) (deftest test-drop-index (is (= "DROP INDEX index") - (ddl/drop-index :index))) + (ddl/drop-index :index)) + (is (= "DROP INDEX INDEX") + (ddl/drop-index :index :entities str/upper-case)) + (is (= "DROP INDEX INDEX") + (sql/entities str/upper-case + (ddl/drop-index :index)))) From df5e4156c68b1796777fa658d4d6128ba754ece7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 15 Sep 2013 13:38:55 -0700 Subject: [PATCH 140/630] Update CHANGES for JDBC-53 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 01b1d883..dfe24128 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha5 +* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). From 4224a31e51b184585d7a082b2ac2bef2eff82747 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 15 Sep 2013 20:11:04 -0700 Subject: [PATCH 141/630] Update README / CHANGES for alpha5 --- CHANGES.md | 2 +- README.md | 23 ++++++++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index dfe24128..464d98c9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.0-alpha5 +Changes in 0.3.0-alpha5 * DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). diff --git a/README.md b/README.md index b5019df5..20f3eb53 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-alpha4 +Latest stable release: 0.3.0-alpha5 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -21,14 +21,14 @@ Latest stable release: 0.3.0-alpha4 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-alpha4"] +[org.clojure/java.jdbc "0.3.0-alpha5"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-alpha4 + 0.3.0-alpha5 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -109,6 +109,23 @@ Developer Information Change Log ==================== +* Release 0.3.0-alpha5 on 2013-09-15 + * DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). + * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). + * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) + * Added Leiningen support for easier development/testing (Maven is still the primary build tool). + * Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist + * Make transaction? boolean optional in various db-do-* functions + * It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with + * Create clojure.java.jdbc.ddl namespace + * Add create-table and drop-table + * Deprecate create-table, create-table-ddl and drop-table in main namespace + * More DDL is coming soon + * Update README to clarify PostgreSQL instructions. + * Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) + * Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) + * Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) + * Release 0.3.0-alpha4 on 2013-05-11 * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) From e392d12c82501ae963a72182e35a59de45471bf3 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 15 Sep 2013 22:21:30 -0500 Subject: [PATCH 142/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-alpha5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 734e6734..33e76811 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-alpha5 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.0-alpha5 From dad67de1831ddbb77a4d1b4c469310971e6186ed Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 15 Sep 2013 22:21:30 -0500 Subject: [PATCH 143/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 33e76811..734e6734 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-alpha5 + 0.3.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.0-alpha5 + HEAD From 211d357aa65d62a3486bdc238179e7d362e422a4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 15 Sep 2013 20:31:16 -0700 Subject: [PATCH 144/630] Correct some README / CHANGES notes --- CHANGES.md | 14 ++++++++++++++ README.md | 6 ++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 464d98c9..89ba4f98 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,19 @@ Changes in 0.3.0-alpha5 +* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). +* Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). +* Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) +* Added Leiningen support for easier development/testing (Maven is still the primary build tool). +* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist +* Make transaction? boolean optional in various db-do-* functions +* Create clojure.java.jdbc.ddl namespace +* Add create-table, drop-table, create-index and drop-index +* Deprecate create-table, create-table-ddl and drop-table in main namespace +* Update README to clarify PostgreSQL instructions. +* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) +* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) +* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) + * DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) diff --git a/README.md b/README.md index 20f3eb53..b079a416 100644 --- a/README.md +++ b/README.md @@ -116,11 +116,9 @@ Change Log * Added Leiningen support for easier development/testing (Maven is still the primary build tool). * Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist * Make transaction? boolean optional in various db-do-* functions - * It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with * Create clojure.java.jdbc.ddl namespace - * Add create-table and drop-table - * Deprecate create-table, create-table-ddl and drop-table in main namespace - * More DDL is coming soon + * Add create-table, drop-table, create-index and drop-index + * Deprecate create-table, create-table-ddl and drop-table in main namespace * Update README to clarify PostgreSQL instructions. * Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) * Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) From 21c758d4608c1413206f05506d957e47453a6a88 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 21 Oct 2013 11:45:01 -0700 Subject: [PATCH 145/630] Add h2 protocol as shorthand for org.h2.Driver --- src/main/clojure/clojure/java/jdbc.clj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 3ac01820..ffcd0cc3 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -117,6 +117,7 @@ made at some future date." } "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" "derby" "org.apache.derby.jdbc.EmbeddedDriver" "hsqldb" "org.hsqldb.jdbcDriver" + "h2" "org.h2.Driver" "sqlite" "org.sqlite.JDBC"}) (def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols From 534b6a7fdca0a21f5e2f2f67deaf12138dd33114 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 21 Oct 2013 11:46:22 -0700 Subject: [PATCH 146/630] Add H2 protocol to CHANGES --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 89ba4f98..1b866fee 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.0-alpha6 (or beta1) + +* "h2" is recognized as a protocol shorthand for org.h2.Driver + Changes in 0.3.0-alpha5 * DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). From ad1cd3f80b27b2233580c108fe9a1364fd2a4c1f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 28 Oct 2013 14:48:35 -0700 Subject: [PATCH 147/630] Fix JDBC-71 by changing tests to not use numeric keyword literals. --- CHANGES.md | 1 + src/test/clojure/clojure/java/test_jdbc.clj | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1b866fee..1f9b889a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.0-alpha6 (or beta1) * "h2" is recognized as a protocol shorthand for org.h2.Driver +* Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). Changes in 0.3.0-alpha5 diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 4ebe0b86..ff4ab447 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -269,7 +269,7 @@ "hsqldb" (is (= '(1 1) r)) "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} {(keyword "last_insert_rowid()") 2}) r)) - "derby" (is (= '({:1 nil} {:1 nil}) r)))) + "derby" (is (= (list {(keyword "1") nil} {(keyword "1") nil}) r)))) (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) (is (= "Pomegranate" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 585] (:name (first res)))))))) @@ -407,7 +407,7 @@ (defn- returned-key [db k] (condp = (:subprotocol db) - "derby" {:1 nil} + "derby" {(keyword "1") nil} "hsqldb" 1 "mysql" {:generated_key k} nil (if (mysql? db) ; string-based tests From cc52667ee241cd5b936e4df0ca279bf1bbe96634 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 3 Nov 2013 19:38:27 -0800 Subject: [PATCH 148/630] Fixes JDBC-72 by removing vec call from rest of result set and defaulting result-set-fn to vec if as-arrays? true. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 16 +++++++++------- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1f9b889a..875ab512 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-alpha6 (or beta1) +* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver * Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ffcd0cc3..bbc83d38 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -632,20 +632,22 @@ made at some future date." } "Given a database connection and a vector containing SQL and optional parameters, perform a simple database query. The optional keyword arguments specify how to construct the result set: - :result-set-fn - applied to the entire result set, default doall + :result-set-fn - applied to the entire result set, default doall / vec + if :as-arrays? true, :result-set-fn will default to vec + if :as-arrays? false, :result-set-fn will default to doall :row-fn - applied to each row as the result set is constructed, default identity :identifiers - applied to each column name in the result set, default lower-case :as-arrays? - return the results as a set of arrays, default false." [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] - :or {result-set-fn doall - row-fn identity + :or {row-fn identity identifiers sql/lower-case}}] (db-with-query-results* db (vec sql-params) (^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (vec (map row-fn (rest rs)))) - (map row-fn rs)))) + (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs))))) identifiers as-arrays?)) From cab2d5a78cf3a8989656ae13ccebb8d516e9a7e1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 3 Nov 2013 20:03:43 -0800 Subject: [PATCH 149/630] Fixes JDBC-69 by using when-available macro to enable use on Android --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 19 ++++++++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 875ab512..2ab55dec 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,7 @@ Changes coming in 0.3.0-alpha6 (or beta1) * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver * Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). +* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69). Changes in 0.3.0-alpha5 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index bbc83d38..cf31bcfd 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -51,7 +51,6 @@ made at some future date." } [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement Types] [java.util Hashtable Map Properties] - [javax.naming InitialContext Name] [javax.sql DataSource]) (:refer-clojure :exclude [resultset-seq]) (:require [clojure.string :as str] @@ -142,6 +141,14 @@ made at some future date." } (.substring spec 5) spec)) +;; feature testing macro, based on suggestion from Chas Emerick: +(defmacro when-available + [sym & body] + (try + (when (resolve sym) + (list* 'do body)) + (catch ClassNotFoundException _#))) + (defn get-connection "Creates a connection to a database. db-spec is a map containing connection parameters. db-spec is a map containing values for one of the following @@ -218,10 +225,12 @@ made at some future date." } (.getConnection ^DataSource datasource) name - (let [env (and environment (Hashtable. ^Map environment)) - context (InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (.getConnection datasource)) + (when-available + javax.naming.InitialContext + (let [env (and environment (Hashtable. ^Map environment)) + context (javax.naming.InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (.getConnection datasource))) :else (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] From 6ffe2be69b0e7642d73e2f6a4d49b48d1266f5cb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 3 Nov 2013 20:44:01 -0800 Subject: [PATCH 150/630] Fixes JDBC-63 by exposing a query function that hands off a ResultSet (and updating the query function to do the conversion to a result-set-seq). --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 30 ++++++++++++-------------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 2ab55dec..c38f877f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,7 @@ Changes coming in 0.3.0-alpha6 (or beta1) * "h2" is recognized as a protocol shorthand for org.h2.Driver * Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69). +* New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63). Changes in 0.3.0-alpha5 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index cf31bcfd..64035bc2 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -591,16 +591,16 @@ made at some future date." } (with-open [^java.sql.Connection con (get-connection db)] (apply db-do-prepared (add-connection db con) transaction? sql param-groups))))) -(defn- db-with-query-results* - "Executes a query, then evaluates func passing in a seq of the results as - an argument. The first argument is a vector containing either: +(defn db-query-with-resultset + "Executes a query, then evaluates func passing in the raw ResultSet as an + argument. The first argument is a vector containing either: [sql & params] - a SQL query, followed by any parameters it needs [stmt & params] - a PreparedStatement, followed by any parameters it needs (the PreparedStatement already contains the SQL query) [options sql & params] - options and a SQL query for creating a PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." - [db sql-params func identifiers as-arrays?] + [db sql-params func] (when-not (vector? sql-params) (let [^Class sql-params-class (class sql-params) ^String msg (format "\"%s\" expected %s %s, found %s %s" @@ -622,9 +622,7 @@ made at some future date." } run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] (set-parameters stmt params) (with-open [rset (.executeQuery stmt)] - (func (result-set-seq rset - :identifiers identifiers - :as-arrays? as-arrays?))))] + (func rset)))] (if (instance? PreparedStatement special) (let [^PreparedStatement stmt special] (run-query-with-params stmt)) @@ -650,15 +648,15 @@ made at some future date." } [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] :or {row-fn identity identifiers sql/lower-case}}] - (db-with-query-results* db (vec sql-params) - (^{:once true} fn* [rs] - (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs))))) - identifiers - as-arrays?)) + (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (db-query-with-resultset db (vec sql-params) + (^{:once true} fn* [rset] + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rset :identifiers identifiers :as-arrays? as-arrays?)))))) (defn execute! "Given a database connection and a vector containing SQL and optional parameters, From 3d3c402f65eb9db1fca055f1a0fe3d6db0889215 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 3 Nov 2013 21:13:20 -0800 Subject: [PATCH 151/630] Fixes JDBC-40 by allowing per-db-spec override of set-parameters function. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c38f877f..8959dc60 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -5,6 +5,7 @@ Changes coming in 0.3.0-alpha6 (or beta1) * Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69). * New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63). +* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40). Changes in 0.3.0-alpha5 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 64035bc2..fd58e424 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -535,7 +535,7 @@ made at some future date." } ([db transaction? sql param-group] (if-let [^java.sql.Connection con (db-find-connection db)] (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] - (set-parameters stmt param-group) + ((or (:set-parameters db) set-parameters) stmt param-group) (let [exec-and-return-keys (^{:once true} fn* [] (let [counts (.executeUpdate stmt)] @@ -579,7 +579,7 @@ made at some future date." } (throw-non-rte e)))) (do (doseq [param-group param-groups] - (set-parameters stmt param-group) + ((or (:set-parameters db) set-parameters) stmt param-group) (.addBatch stmt)) (if transaction? (db-transaction [t-db (add-connection db (.getConnection stmt))] @@ -620,7 +620,7 @@ made at some future date." } :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special))) run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] - (set-parameters stmt params) + ((or (:set-parameters db) set-parameters) stmt params) (with-open [rset (.executeQuery stmt)] (func rset)))] (if (instance? PreparedStatement special) @@ -996,7 +996,7 @@ made at some future date." } :else (rest sql-params))) prepare-args (when (map? special) (flatten (seq special)))] (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (get-connection *db*) sql prepare-args))] - (set-parameters stmt params) + (set-parameters stmt params) ; cannot override this in legacy API! (with-open [rset (.executeQuery stmt)] (binding [*db* (assoc *db* :connection (.getConnection stmt))] (func (resultset-seq rset))))))) From b1909bedae59f724d0343928daf2a635f81fb827 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 3 Nov 2013 21:16:27 -0800 Subject: [PATCH 152/630] Update CHANGES/README for 0.3.0-beta1 --- CHANGES.md | 2 +- README.md | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 8959dc60..22949a6b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.0-alpha6 (or beta1) +Changes in 0.3.0-beta1 * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver diff --git a/README.md b/README.md index b079a416..37b5334c 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-alpha5 +Latest stable release: 0.3.0-beta1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -21,14 +21,14 @@ Latest stable release: 0.3.0-alpha5 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-alpha5"] +[org.clojure/java.jdbc "0.3.0-beta1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-alpha5 + 0.3.0-beta1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -109,6 +109,14 @@ Developer Information Change Log ==================== +* Release 0.3.0-beta1 on 2013-11-03 + * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). + * "h2" is recognized as a protocol shorthand for org.h2.Driver + * Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). + * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69). + * New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63). + * Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40). + * Release 0.3.0-alpha5 on 2013-09-15 * DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). From 9d3527f74b549c17fffa6cca1d1b21e571b757e0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 3 Nov 2013 23:26:51 -0600 Subject: [PATCH 153/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-beta1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 734e6734..c410c551 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-beta1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.0-beta1 From 3bd271c2678c9a52025932e2c6906469be0b554f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 3 Nov 2013 23:26:51 -0600 Subject: [PATCH 154/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c410c551..734e6734 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-beta1 + 0.3.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.0-beta1 + HEAD From bc76bd5e316dc13373e5767db0c6c27e65b77e1d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Nov 2013 19:55:37 -0800 Subject: [PATCH 155/630] Remove dependency on DSL in the main JDBC namespace and associated tests. --- src/main/clojure/clojure/java/jdbc.clj | 248 +++++++++++++++----- src/test/clojure/clojure/java/test_jdbc.clj | 29 ++- 2 files changed, 203 insertions(+), 74 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 3ac01820..e721d2fc 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -54,9 +54,7 @@ made at some future date." } [javax.naming InitialContext Name] [javax.sql DataSource]) (:refer-clojure :exclude [resultset-seq]) - (:require [clojure.string :as str] - [clojure.java.jdbc.ddl :as ddl] - [clojure.java.jdbc.sql :as sql])) + (:require [clojure.string :as str])) ;; technically deprecated but still used as defaults in a couple of ;; places for backward compatibility... @@ -73,13 +71,33 @@ made at some future date." } ;; end of deprecated API artifacts... +(defn as-str + "Given a naming strategy and a keyword, return the keyword as a + string per that naming strategy. Given (a naming strategy and) + a string, return it as-is. + A keyword of the form :x.y is treated as keywords :x and :y, + both are turned into strings via the naming strategy and then + joined back together so :x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." + ([f] + (fn [x] + (as-str f x))) + ([f x] + (if (instance? clojure.lang.Named x) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))) + (str x)))) + (defn- ^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. - Uses sql/as-str to convert both keys and values into strings." + Uses as-str to convert both keys and values into strings." [m] (let [p (Properties.)] (doseq [[k v] m] - (.setProperty p (sql/as-str identity k) (sql/as-str identity v))) + (.setProperty p (as-str identity k) (as-str identity v))) p)) (defprotocol Connectable @@ -638,7 +656,7 @@ made at some future date." } [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] :or {result-set-fn doall row-fn identity - identifiers sql/lower-case}}] + identifiers str/lower-case}}] (db-with-query-results* db (vec sql-params) (^{:once true} fn* [rs] (result-set-fn (if as-arrays? @@ -664,6 +682,24 @@ made at some future date." } (with-open [^java.sql.Connection con (get-connection db)] (execute-helper (add-connection db con)))))) +(defn- table-str + "Transform a table spec to an entity name for SQL. The table spec may be a + string, a keyword or a map with a single pair - table name and alias." + [table entities] + (if (map? table) + (let [[k v] (first table)] + (str (as-str entities k) " " (as-str entities v))) + (as-str entities table))) + +(defn- delete-sql + "Given a table name, a where class and its parameters and an optional entities spec, + return a vector of the SQL for that delete operation followed by its parameters. The + entities spec (default 'as-is') specifies how to transform column names." + [table [where & params] & {:keys [entities] :or {entities identity}}] + (into [(str "DELETE FROM " (table-str table entities) + (when where " WHERE ") where)] + params)) + (defn delete! "Given a database connection, a table name and a where clause of columns to match, perform a delete. The optional keyword arguments specify how to transform @@ -674,9 +710,9 @@ made at some future date." } is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" [db table where-clause & {:keys [entities transaction?] - :or {entities sql/as-is transaction? true}}] + :or {entities identity transaction? true}}] (execute! db - (sql/delete table where-clause :entities entities) + (delete-sql table where-clause :entities entities) :transaction? transaction?)) (defn- multi-insert-helper @@ -708,6 +744,70 @@ made at some future date." } [(second after) (concat before (nnext after))] [true data]))) +(defn- col-str + "Transform a column spec to an entity name for SQL. The column spec may be a + string, a keyword or a map with a single pair - column name and alias." + [col entities] + (if (map? col) + (let [[k v] (first col)] + (str (as-str entities k) " AS " (as-str entities v))) + (as-str entities col))) + +(defn- insert-multi-row-sql + "Given a table and a list of columns, followed by a list of column value sequences, + return a vector of the SQL needed for the insert followed by the list of column + value sequences. The entities function specifies how column names are transformed." + [table columns values entities] + (let [nc (count columns) + vcs (map count values)] + (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) + (throw (IllegalArgumentException. "insert called with inconsistent number of columns / values")) + (into [(str "INSERT INTO " (table-str table entities) + (when (seq columns) + (str " ( " + (str/join ", " (map (fn [col] (col-str col entities)) columns)) + " )")) + " VALUES ( " + (str/join ", " (repeat (first vcs) "?")) + " )")] + values)))) + +(defn- insert-single-row-sql + "Given a table and a map representing a row, return a vector of the SQL needed for + the insert followed by the list of column values. The entities function specifies + how column names are transformed." + [table row entities] + (let [ks (keys row)] + (into [(str "INSERT INTO " (table-str table entities) " ( " + (str/join ", " (map (fn [col] (col-str col entities)) ks)) + " ) VALUES ( " + (str/join ", " (repeat (count ks) "?")) + " )")] + (vals row)))) + +(defn insert-sql + "Given a table name and either column names and values or maps representing rows, retun + return a vector of the SQL for that insert operation followed by its parameters. An + optional entities spec (default 'as-is') specifies how to transform column names." + [table & clauses] + (let [rows (take-while map? clauses) + n-rows (count rows) + cols-and-vals-etc (drop n-rows clauses) + cols-and-vals (take-while (comp not keyword?) cols-and-vals-etc) + n-cols-and-vals (count cols-and-vals) + no-cols-and-vals (zero? n-cols-and-vals) + options (drop (+ (count rows) (count cols-and-vals)) clauses) + {:keys [entities] :or {entities identity}} (apply hash-map options)] + (if (zero? n-rows) + (if no-cols-and-vals + (throw (IllegalArgumentException. "insert called without data to insert")) + (if (< n-cols-and-vals 2) + (throw (IllegalArgumentException. "insert called with columns but no values")) + (insert-multi-row-sql table (first cols-and-vals) (rest cols-and-vals) entities))) + (if no-cols-and-vals + (map (fn [row] (insert-single-row-sql table row entities)) rows) + (throw (IllegalArgumentException. "insert may take records or columns and values, not both")))))) + (defn insert! "Given a database connection, a table name and either maps representing rows or a list of column names followed by lists of column values, perform an insert. @@ -715,12 +815,37 @@ made at some future date." } The default is true (use a transaction)." [db table & options] (let [[transaction? maps-or-cols-and-values-etc] (extract-transaction? options) - stmts (apply sql/insert table maps-or-cols-and-values-etc)] + stmts (apply insert-sql table maps-or-cols-and-values-etc)] (if-let [con (db-find-connection db)] (insert-helper db transaction? stmts) (with-open [^java.sql.Connection con (get-connection db)] (insert-helper (add-connection db con) transaction? stmts))))) +(defn- update-sql + "Given a table name and a map of columns to set, and optional map of columns to + match (and an optional entities spec), return a vector of the SQL for that update + followed by its parameters. Example: + (update :person {:zip 94540} (where {:zip 94546})) + returns: + [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" + [table set-map & where-etc] + (let [[where-clause & options] (when-not (keyword? (first where-etc)) where-etc) + [where & params] where-clause + {:keys [entities] :or {entities identity}} (if (keyword? (first where-etc)) where-etc options) + ks (keys set-map) + vs (vals set-map)] + (cons (str "UPDATE " (table-str table entities) + " SET " (str/join + "," + (map (fn [k v] + (str (as-str entities k) + " = " + (if (nil? v) "NULL" "?"))) + ks vs)) + (when where " WHERE ") + where) + (concat (remove nil? vs) params)))) + (defn update! "Given a database connection, a table name, a map of column values to set and a where clause of columns to match, perform an update. The optional keyword arguments @@ -731,9 +856,9 @@ made at some future date." } is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" [db table set-map where-clause & {:keys [entities transaction?] - :or {entities sql/as-is transaction? true}}] + :or {entities identity transaction? true}}] (execute! db - (sql/update table set-map where-clause :entities entities) + (update-sql table set-map where-clause :entities entities) :transaction? transaction?)) ;; original API mostly rewritten in terms of new API primarily without dynamic binding @@ -846,33 +971,48 @@ made at some future date." } [sql & param-groups] (apply db-do-prepared *db* sql param-groups)) -(defn ^{:doc "See clojure.java.jdbc.ddl/create-table for details. - This version is deprecated in favor of the version in the DDL namespace." - :deprecated "0.3.0"} - create-table-ddl +(defn create-table-ddl + "Given a table name and column specs with an optional table-spec + return the DDL string for creating that table." [name & specs] - (apply ddl/create-table name specs)) - -(defn - ^{:doc "Creates a table on the open database connection given a table name and - specs. Each spec is either a column spec: a vector containing a column - name and optionally a type and other constraints, or a table-level - constraint: a vector containing words that express the constraint. An - optional suffix to the CREATE TABLE DDL describing table attributes may - by provided as :table-spec {table-attributes-string}. All words used to - describe the table may be supplied as strings or keywords." - :deprecated "0.3.0"} - create-table + (let [col-specs (take-while (fn [s] + (not (or (= :table-spec s) + (= :entities s)))) specs) + other-specs (drop (count col-specs) specs) + {:keys [table-spec entities] :or {entities identity}} other-specs + table-spec-str (or (and table-spec (str " " table-spec)) "") + specs-to-string (fn [specs] + (apply str + (map (as-str entities) + (apply concat + (interpose [", "] + (map (partial interpose " ") specs))))))] + (format "CREATE TABLE %s (%s)%s" + (as-str entities name) + (specs-to-string col-specs) + table-spec-str))) + +(defn create-table + "Creates a table on the open database connection given a table name and + specs. Each spec is either a column spec: a vector containing a column + name and optionally a type and other constraints, or a table-level + constraint: a vector containing words that express the constraint. An + optional suffix to the CREATE TABLE DDL describing table attributes may + by provided as :table-spec {table-attributes-string}. All words used to + describe the table may be supplied as strings or keywords." [name & specs] - (db-do-commands *db* (apply ddl/create-table name specs))) + (db-do-commands *db* (apply create-table-ddl name specs))) -(defn - ^{:doc "Drops a table on the open database connection given its name, a string - or keyword" - :deprecated "0.3.0"} - drop-table +(defn drop-table-ddl + "Given a table name, return the DDL string for dropping that table." + [name & {:keys [entities] :or {entities identity}}] + (format "DROP TABLE %s" (as-str entities name))) + +(defn drop-table + "Drops a table on the open database connection given its name, a string + or keyword" [name] - (db-do-commands *db* (ddl/drop-table name))) + (db-do-commands *db* (drop-table-ddl name))) (defn ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the @@ -1039,19 +1179,6 @@ made at some future date." } [naming-strategy x] (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) -(defn - ^{:doc "Given a naming strategy and a keyword, return the keyword as a - string per that naming strategy. Given (a naming strategy and) - a string, return it as-is. - A keyword of the form :x.y is treated as keywords :x and :y, - both are turned into strings via the naming strategy and then - joined back together so :x.y might become `x`.`y` if the naming - strategy quotes identifiers with `." - :deprecated "0.3.0"} - as-str - [f x] - (sql/as-str f x)) - (defn ^{:doc "Given a keyword, convert it to a string using the current naming strategy. @@ -1061,15 +1188,18 @@ made at some future date." } ([x] (as-identifier x *as-str*)) ([x f-entity] (as-str f-entity x))) -(defn - ^{:doc "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (as-quoted-str X foo) will return XfooX - (as-quoted-str [A B] foo) will return AfooB" - :deprecated "0.3.0"} - as-quoted-str - [q x] - (sql/as-quoted-str q x)) +(defn as-quoted-str + "Given a quoting pattern - either a single character or a vector pair of + characters - and a string, return the quoted string: + (as-quoted-str X foo) will return XfooX + (as-quoted-str [A B] foo) will return AfooB" + ([q] + (fn [x] + (as-quoted-str q x))) + ([q x] + (if (vector? q) + (str (first q) x (last q)) + (str q x q)))) (defn ^{:doc "Given a naming strategy and a keyword, return the keyword as a string using @@ -1093,14 +1223,14 @@ made at some future date." } :deprecated "0.3.0"} as-quoted-identifier [q x] - (as-identifier x (sql/as-quoted-str q))) + (as-identifier x (as-quoted-str q))) (defmacro ^{:doc "Evaluates body in the context of a simple quoting naming strategy." :deprecated "0.3.0"} with-quoted-identifiers [q & body ] - `(binding [*as-str* (sql/as-quoted-str ~q)] ~@body)) + `(binding [*as-str* (as-quoted-str ~q)] ~@body)) (defmacro ^{:doc "Evaluates body in the context of a naming strategy. @@ -1113,4 +1243,4 @@ made at some future date." } with-naming-strategy [naming-strategy & body ] `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) - *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) \ No newline at end of file + *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 4ebe0b86..42e16b65 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -22,8 +22,7 @@ (ns clojure.java.test-jdbc (:use clojure.test) - (:require [clojure.java.jdbc :as sql] - [clojure.java.jdbc.sql :as dsl])) + (:require [clojure.java.jdbc :as sql])) ;; Set test-databases according to whether you have the local database available: ;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] @@ -439,7 +438,7 @@ (doseq [db (test-specs)] (sql/with-connection db (create-test-table :fruit db)) - (is (= [] (sql/query db (dsl/select * :fruit)))))) + (is (= [] (sql/query db ["SELECT * FROM fruit"]))))) (deftest insert-one-row (doseq [db (test-specs)] @@ -456,7 +455,7 @@ (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys)] (is (= [(returned-key db 1)] new-keys)) - (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db (dsl/select * :fruit))))))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db ["SELECT * FROM fruit"])))))) (deftest insert-two-by-map-and-query (doseq [db (test-specs)] @@ -464,7 +463,7 @@ (create-test-table :fruit db)) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) - rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) @@ -475,7 +474,7 @@ (create-test-table :fruit db)) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) - rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] :as-arrays? true)] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [[:id :name :appearance :cost :grade] @@ -487,7 +486,7 @@ (sql/with-connection db (create-test-table :fruit db)) (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) - rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [1 1] update-counts)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) @@ -499,8 +498,8 @@ (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} - (dsl/where {:id (generated-key db 1)})) - rows (sql/query db (dsl/select * :fruit))] + ["id = ?" (generated-key db 1)]) + rows (sql/query db ["SELECT * FROM fruit"])] (is (= [(returned-key db 1)] new-keys)) (is (= [1] update-result)) (is (= [{:id (generated-key db 1) @@ -515,8 +514,8 @@ (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) delete-result (sql/delete! db :fruit - (dsl/where {:id (generated-key db 1)})) - rows (sql/query db (dsl/select * :fruit))] + ["id = ?" (generated-key db 1)]) + rows (sql/query db ["SELECT * FROM fruit"])] (is (= [(returned-key db 1)] new-keys)) (is (= [1] delete-result)) (is (= [] rows))))) @@ -524,11 +523,11 @@ (deftest illegal-insert-arguments (doseq [db (test-specs)] (is (thrown? IllegalArgumentException (sql/insert! db))) - (is (thrown? IllegalArgumentException (sql/insert! db :entities dsl/as-is))) + (is (thrown? IllegalArgumentException (sql/insert! db :entities identity))) (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :entities dsl/as-is))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :entities identity))) (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db [:name] :entities dsl/as-is))))) + (is (thrown? IllegalArgumentException (sql/insert! db [:name] :entities identity))))) (deftest test-partial-exception-with-db (doseq [db (test-specs)] @@ -622,7 +621,7 @@ ["Pear" "yellow"] ["Orange" "round"]] :multi? true) - rows (sql/query db (dsl/select * :fruit (dsl/order-by :name)))] + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [1 1 1] counts)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance "rosy" :cost nil :grade nil} {:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil} From 99e23cfde8621f945fa3b8374f5a4e96564910a4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Nov 2013 21:04:02 -0800 Subject: [PATCH 156/630] List the retirement of the DSL namespaces as the next change --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 22949a6b..1f8a78cb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.0-beta2 + +* The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). + Changes in 0.3.0-beta1 * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). From 133ee4c81311e033f2b8f62d30078b13ad64e085 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Nov 2013 21:12:21 -0800 Subject: [PATCH 157/630] Retire the DSL namespaces - users can get them from java-jdbc/dsl as java-jdbc.sql and java-jdbc.ddl --- src/main/clojure/clojure/java/jdbc/ddl.clj | 83 ------ src/main/clojure/clojure/java/jdbc/sql.clj | 308 --------------------- src/test/clojure/clojure/java/test_ddl.clj | 76 ----- src/test/clojure/clojure/java/test_sql.clj | 135 --------- 4 files changed, 602 deletions(-) delete mode 100644 src/main/clojure/clojure/java/jdbc/ddl.clj delete mode 100644 src/main/clojure/clojure/java/jdbc/sql.clj delete mode 100644 src/test/clojure/clojure/java/test_ddl.clj delete mode 100644 src/test/clojure/clojure/java/test_sql.clj diff --git a/src/main/clojure/clojure/java/jdbc/ddl.clj b/src/main/clojure/clojure/java/jdbc/ddl.clj deleted file mode 100644 index 2c359c2a..00000000 --- a/src/main/clojure/clojure/java/jdbc/ddl.clj +++ /dev/null @@ -1,83 +0,0 @@ -;; Copyright (c) Sean Corfield. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. -;; -;; ddl.clj -;; -;; A basic DDL DSL for use with clojure.java.jdbc (or you can use any -;; other DDL DSL you want to...) -;; -;; seancorfield (gmail) -;; December 2013 - -(ns - ^{:author "Sean Corfield", - :doc "An optional DSL for generating DDL. - -Intended to be used with clojure.java.jdbc, this provides a simple DSL - -Domain Specific Language - that generates raw DDL strings. Any other DSL -can be used instead. This DSL is entirely optional and is deliberately -not very sophisticated." } - clojure.java.jdbc.ddl - (:require [clojure.java.jdbc.sql :as sql])) - -(defn create-table - "Given a table name and column specs with an optional table-spec - return the DDL string for creating that table." - [name & specs] - (let [col-specs (take-while (fn [s] - (not (or (= :table-spec s) - (= :entities s)))) specs) - other-specs (drop (count col-specs) specs) - {:keys [table-spec entities] :or {entities sql/as-is}} other-specs - table-spec-str (or (and table-spec (str " " table-spec)) "") - specs-to-string (fn [specs] - (apply str - (map (sql/as-str entities) - (apply concat - (interpose [", "] - (map (partial interpose " ") specs))))))] - (format "CREATE TABLE %s (%s)%s" - (sql/as-str entities name) - (specs-to-string col-specs) - table-spec-str))) - -(defn drop-table - "Given a table name, return the DDL string for dropping that table." - [name & {:keys [entities] :or {entities sql/as-is}}] - (format "DROP TABLE %s" (sql/as-str entities name))) - -(defn create-index - "Given an index name, table name, vector of column names, and - (optional) is-unique, return the DDL string for creating an index. - - Examples: - (create-index :indexname :tablename [:field1 :field2] :unique) - \"CREATE UNIQUE INDEX indexname ON tablename (field1, field2)\" - - (create-index :indexname :tablename [:field1 :field2]) - \"CREATE INDEX indexname ON tablename (field1, field2)\"" - [index-name table-name cols & specs] - (let [is-unique (seq (filter #(= :unique %) specs)) - entities-spec (drop-while #(not= :entities %) specs) - {:keys [entities] :or {entities sql/as-is}} (take 2 entities-spec) - cols-string (apply str - (interpose ", " - (map (sql/as-str entities) - cols))) - is-unique (if is-unique "UNIQUE " "")] - (format "CREATE %sINDEX %s ON %s (%s)" - is-unique - (sql/as-str entities index-name) - (sql/as-str entities table-name) - cols-string))) - -(defn drop-index - "Given an index name, return the DDL string for dropping that index." - [name & {:keys [entities] :or {entities sql/as-is}}] - (format "DROP INDEX %s" (sql/as-str entities name))) - diff --git a/src/main/clojure/clojure/java/jdbc/sql.clj b/src/main/clojure/clojure/java/jdbc/sql.clj deleted file mode 100644 index 4cc75f2a..00000000 --- a/src/main/clojure/clojure/java/jdbc/sql.clj +++ /dev/null @@ -1,308 +0,0 @@ -;; Copyright (c) Sean Corfield. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. -;; -;; sql.clj -;; -;; A basic SQL DSL for use with clojure.java.jdbc (or you can use any -;; other SQL DSL you want to...) -;; -;; seancorfield (gmail) -;; December 2012 - -(ns - ^{:author "Sean Corfield", - :doc "An optional DSL for generating SQL. - -Intended to be used with clojure.java.jdbc, this provides a simple DSL - -Domain Specific Language - that generates raw SQL strings. Any other DSL -can be used instead. This DSL is entirely optional and is deliberately -not very sophisticated. It is sufficient to support the delete!, insert! -and update! high-level operations within clojure.java.jdbc directly." } - clojure.java.jdbc.sql - (:require [clojure.string :as str] - [clojure.walk :as walk])) - -;; implementation utilities - -(defn as-str - "Given a naming strategy and a keyword, return the keyword as a - string per that naming strategy. Given (a naming strategy and) - a string, return it as-is. - A keyword of the form :x.y is treated as keywords :x and :y, - both are turned into strings via the naming strategy and then - joined back together so :x.y might become `x`.`y` if the naming - strategy quotes identifiers with `." - ([f] - (fn [x] - (as-str f x))) - ([f x] - (if (instance? clojure.lang.Named x) - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))) - (str x)))) - -(defn as-quoted-str - "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (as-quoted-str X foo) will return XfooX - (as-quoted-str [A B] foo) will return AfooB" - ([q] - (fn [x] - (as-quoted-str q x))) - ([q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q)))) - -(defn- col-str - "Transform a column spec to an entity name for SQL. The column spec may be a - string, a keyword or a map with a single pair - column name and alias." - [col entities] - (if (map? col) - (let [[k v] (first col)] - (str (as-str entities k) " AS " (as-str entities v))) - (as-str entities col))) - -(defn- table-str - "Transform a table spec to an entity name for SQL. The table spec may be a - string, a keyword or a map with a single pair - table name and alias." - [table entities] - (if (map? table) - (let [[k v] (first table)] - (str (as-str entities k) " " (as-str entities v))) - (as-str entities table))) - -(def ^{:private true - :doc "Symbols that need to be processed for entities within their forms."} - entity-symbols - #{"delete" "delete!" - "insert" "insert!" - "select" "join" "where" "order-by" - "update" "update!" - "create-table" "drop-table" "create-index" "drop-index"}) - -(def ^{:private true - :doc "Symbols that need to be processed for identifiers within their forms."} - identifier-symbols - #{"query"}) - -(defn- order-direction - "Transform a column order spec to an order by entity for SQL. The order spec may be a - string, a keyword or a map with a single pair - column name and direction. If the order - spec is not a map, the default direction is ascending." - [col entities] - (if (map? col) - (str (as-str entities (first (keys col))) - " " - (let [dir (first (vals col))] - (get {:asc "ASC" :desc "DESC"} dir dir))) - (str (as-str entities col) " ASC"))) - -(defn- insert-multi-row - "Given a table and a list of columns, followed by a list of column value sequences, - return a vector of the SQL needed for the insert followed by the list of column - value sequences. The entities function specifies how column names are transformed." - [table columns values entities] - (let [nc (count columns) - vcs (map count values)] - (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) - (throw (IllegalArgumentException. "insert called with inconsistent number of columns / values")) - (into [(str "INSERT INTO " (table-str table entities) - (when (seq columns) - (str " ( " - (str/join ", " (map (fn [col] (col-str col entities)) columns)) - " )")) - " VALUES ( " - (str/join ", " (repeat (first vcs) "?")) - " )")] - values)))) - -(defn- insert-single-row - "Given a table and a map representing a row, return a vector of the SQL needed for - the insert followed by the list of column values. The entities function specifies - how column names are transformed." - [table row entities] - (let [ks (keys row)] - (into [(str "INSERT INTO " (table-str table entities) " ( " - (str/join ", " (map (fn [col] (col-str col entities)) ks)) - " ) VALUES ( " - (str/join ", " (repeat (count ks) "?")) - " )")] - (vals row)))) - -;; quoting strategy helpers - -(defmacro entities - "Given an entities function and a SQL-generating DSL form, transform the DSL form - to inject an :entities keyword argument with the function at the end of each appropriate - form." - [entities sql] - (walk/postwalk (fn [form] - (if (and (seq? form) - (symbol? (first form)) - (entity-symbols (name (first form)))) - (concat form [:entities entities]) - form)) sql)) - -(defmacro identifiers - "Given an identifiers function and a SQL-generating DSL form, transform the DSL form - to inject an :identifiers keyword argument with the function at the end of each - appropriate form." - [identifiers sql] - (walk/postwalk (fn [form] - (if (and (seq? form) - (symbol? (first form)) - (identifier-symbols (name (first form)))) - (concat form [:identifiers identifiers]) - form)) sql)) - -;; some common entity/identifier strategies - -(def as-is identity) -(def lower-case str/lower-case) -(defn quoted [q] (as-quoted-str q)) - -;; SQL generation functions - -(defn delete - "Given a table name, a where class and its parameters and an optional entities spec, - return a vector of the SQL for that delete operation followed by its parameters. The - entities spec (default 'as-is') specifies how to transform column names." - [table [where & params] & {:keys [entities] :or {entities as-is}}] - (into [(str "DELETE FROM " (table-str table entities) - (when where " WHERE ") where)] - params)) - -(defn insert - "Given a table name and either column names and values or maps representing rows, retun - return a vector of the SQL for that insert operation followed by its parameters. An - optional entities spec (default 'as-is') specifies how to transform column names." - [table & clauses] - (let [rows (take-while map? clauses) - n-rows (count rows) - cols-and-vals-etc (drop n-rows clauses) - cols-and-vals (take-while (comp not keyword?) cols-and-vals-etc) - n-cols-and-vals (count cols-and-vals) - no-cols-and-vals (zero? n-cols-and-vals) - options (drop (+ (count rows) (count cols-and-vals)) clauses) - {:keys [entities] :or {entities as-is}} (apply hash-map options)] - (if (zero? n-rows) - (if no-cols-and-vals - (throw (IllegalArgumentException. "insert called without data to insert")) - (if (< n-cols-and-vals 2) - (throw (IllegalArgumentException. "insert called with columns but no values")) - (insert-multi-row table (first cols-and-vals) (rest cols-and-vals) entities))) - (if no-cols-and-vals - (map (fn [row] (insert-single-row table row entities)) rows) - (throw (IllegalArgumentException. "insert may take records or columns and values, not both")))))) - -(defn join - "Given a table name and a map of how to join it (to the existing SQL fragment), - retun the SQL string for the JOIN clause. The optional entities spec (default 'as-is') - specifies how to transform column names." - [table on-map & {:keys [entities] :or {entities as-is}}] - (str "JOIN " (table-str table entities) " ON " - (str/join - " AND " - (map (fn [[k v]] (str (as-str entities k) " = " (as-str entities v))) on-map)))) - -(defn order-by - "Given a sequence of column order specs, and an optional entities spec, return the - SQL string for the ORDER BY clause. A column order spec may be a column name or a - map of the column name to the desired order." - [cols & {:keys [entities] :or {entities as-is}}] - (let [singleton (or (string? cols) (keyword? cols) (map? cols))] - (if (or singleton (seq cols)) - (str "ORDER BY " - (if singleton - (order-direction cols entities) - (str/join "," (map #(order-direction % entities) cols)))) - ""))) - -(defn select - "Given a sequence of column names (or *) and a table name, followed by optional SQL - clauses, return a vector for the SQL followed by its parameters. The general form is: - (select [columns] table joins [where params] order-by options) - where joins are optional strings, as is order-by, and the where clause is a vector - of a where SQL clause followed by its parameters. The options may may include an - entities spec to specify how column names should be transformed. - The intent is that the joins, where clause and order by clause are generated by - other parts of the DSL: - (select * {:person :p} - (join {:address :a} {:p.addressId :a.id}) - (where {:a.zip 94546}) - (order-by :p.name))" - [col-seq table & clauses] - (let [joins (take-while string? clauses) - where-etc (drop (count joins) clauses) - [where-clause & more] where-etc - [where & params] (when-not (keyword? where-clause) where-clause) - order-etc (if (keyword? where-clause) where-etc more) - [order-clause & more] order-etc - order-by (when (string? order-clause) order-clause) - options (if order-by more order-etc) - {:keys [entities] :or {entities as-is}} (apply hash-map options)] - (cons (str "SELECT " - (cond - (= * col-seq) "*" - (or (string? col-seq) - (keyword? col-seq) - (map? col-seq)) (col-str col-seq entities) - :else (str/join "," (map #(col-str % entities) col-seq))) - " FROM " (table-str table entities) - (when (seq joins) (str/join " " (cons "" joins))) - (when where " WHERE ") - where - (when order-by " ") - order-by) - params))) - -(defn update - "Given a table name and a map of columns to set, and optional map of columns to - match (and an optional entities spec), return a vector of the SQL for that update - followed by its parameters. Example: - (update :person {:zip 94540} (where {:zip 94546})) - returns: - [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" - [table set-map & where-etc] - (let [[where-clause & options] (when-not (keyword? (first where-etc)) where-etc) - [where & params] where-clause - {:keys [entities] :or {entities as-is}} (if (keyword? (first where-etc)) where-etc options) - ks (keys set-map) - vs (vals set-map)] - (cons (str "UPDATE " (table-str table entities) - " SET " (str/join - "," - (map (fn [k v] - (str (as-str entities k) - " = " - (if (nil? v) "NULL" "?"))) - ks vs)) - (when where " WHERE ") - where) - (concat (remove nil? vs) params)))) - -(defn where - "Given a map of columns and values, return a vector containing the where clause SQL - followed by its parameters. Example: - (where {:a 42 :b nil}) - returns: - [\"a = ? AND b IS NULL\" 42]" - [param-map & {:keys [entities] :or {entities as-is}}] - (let [ks (keys param-map) - vs (vals param-map)] - (cons (str/join - " AND " - (map (fn [k v] - (str (as-str entities k) - (if (nil? v) " IS NULL" " = ?"))) - ks vs)) - (remove nil? vs)))) diff --git a/src/test/clojure/clojure/java/test_ddl.clj b/src/test/clojure/clojure/java/test_ddl.clj deleted file mode 100644 index fd3b2e36..00000000 --- a/src/test/clojure/clojure/java/test_ddl.clj +++ /dev/null @@ -1,76 +0,0 @@ -;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. -;; -;; test_ddl.clj -;; -;; This namespace contains tests of all the functions within -;; java.jdbc.ddl and does not rely on any databases. -;; -;; scgilardi (gmail) -;; Created 13 September 2008 -;; -;; seancorfield (gmail) -;; Migrated from clojure.contrib.test-sql 17 April 2011 -;; -;; moquist (gmail) -;; Migrated test-create-table from clojure.java.test-utilities, added -;; new tests. 23 June 2013 - -(ns clojure.java.test-ddl - (:use clojure.test) - (:require [clojure.java.jdbc.ddl :as ddl] - [clojure.java.jdbc.sql :as sql] - [clojure.string :as str])) - -(deftest test-create-table - (is (= "CREATE TABLE table (col1 int, col2 int)" - (ddl/create-table :table ["col1 int"] [:col2 :int]))) - (is (= "CREATE TABLE TABLE (col1 int, COL2 INT)" - (ddl/create-table :table ["col1 int"] [:col2 :int] :entities str/upper-case))) - (is (= "CREATE TABLE TABLE (col1 int, COL2 INT)" - (sql/entities str/upper-case - (ddl/create-table :table ["col1 int"] [:col2 :int])))) - (is (= "CREATE TABLE table (col1 int, col2 int) ENGINE=MyISAM" - (ddl/create-table :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM"))) - (is (= "CREATE TABLE TABLE (COL1 int, col2 INT) ENGINE=MyISAM" - (ddl/create-table :table [:col1 "int"] ["col2" :int] :entities str/upper-case :table-spec "ENGINE=MyISAM"))) - (is (= "CREATE TABLE TABLE (COL1 int, col2 INT) ENGINE=MyISAM" - (ddl/create-table :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM" :entities str/upper-case)))) - -(deftest test-drop-table - (is (= "DROP TABLE table") - (ddl/drop-table :table)) - (is (= "DROP TABLE TABLE") - (ddl/drop-table :table :entities str/upper-case)) - (is (= "DROP TABLE TABLE") - (sql/entities str/upper-case - (ddl/drop-table :table)))) - -(deftest test-create-index - (is (= "CREATE INDEX index ON table (col1, col2)" - (ddl/create-index :index :table [:col1 "col2"]))) - (is (= "CREATE INDEX INDEX ON TABLE (COL1, col2)" - (ddl/create-index :index :table [:col1 "col2"] :entities str/upper-case))) - (is (= "CREATE INDEX INDEX ON TABLE (COL1, col2)" - (sql/entities str/upper-case - (ddl/create-index :index :table [:col1 "col2"])))) - (is (= "CREATE UNIQUE INDEX index ON table (col1, col2)" - (ddl/create-index :index :table [:col1 "col2"] :unique))) - (is (= "CREATE UNIQUE INDEX INDEX ON TABLE (COL1, col2)" - (ddl/create-index :index :table [:col1 "col2"] :unique :entities str/upper-case))) - (is (= "CREATE UNIQUE INDEX INDEX ON TABLE (COL1, col2)" - (ddl/create-index :index :table [:col1 "col2"] :entities str/upper-case :unique)))) - -(deftest test-drop-index - (is (= "DROP INDEX index") - (ddl/drop-index :index)) - (is (= "DROP INDEX INDEX") - (ddl/drop-index :index :entities str/upper-case)) - (is (= "DROP INDEX INDEX") - (sql/entities str/upper-case - (ddl/drop-index :index)))) diff --git a/src/test/clojure/clojure/java/test_sql.clj b/src/test/clojure/clojure/java/test_sql.clj deleted file mode 100644 index 9f9a9b86..00000000 --- a/src/test/clojure/clojure/java/test_sql.clj +++ /dev/null @@ -1,135 +0,0 @@ -;; Copyright (c) Sean Corfield. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. -;; -;; test_sql.clj -;; -;; This namespace contains tests that exercise the optional DSL -;; portion of java.jdbc. -;; -;; seancorfield (gmail) -;; Constructured from tests for jsql DSL December 2012 - -(ns clojure.java.test-sql - (:use clojure.test - clojure.java.jdbc.sql)) - -(deftest select-dsl - (is (= ["SELECT * FROM table"] (select * :table))) - (is (= ["SELECT id FROM table"] (select :id :table))) - (is (= ["SELECT id,name FROM table"] (select [:id :name] :table))) - (is (= ["SELECT id AS foo,name FROM table"] (select [{:id :foo} :name] :table))) - (is (= ["SELECT t.id FROM table t"] (select :t.id {:table :t})))) - -(deftest quoting-fns - (is (= "`a`" ((quoted \`) "a"))) - (is (= "`A`" ((quoted \`) "A"))) - (is (= "a" (as-is "a"))) - (is (= "A" (as-is "A"))) - (is (= "a" (lower-case "a"))) - (is (= "a" (lower-case "A")))) - -(deftest select-entities - (is (= ["SELECT * FROM `table`"] (entities (quoted \`) (select * :table)))) - (is (= ["SELECT * FROM table"] (entities as-is (select * :table)))) - (is (= ["SELECT `t`.`id` FROM `table` `t`"] (entities (quoted \`) (select :t.id {:table :t}))))) - -(deftest join-dsl - (is (= "JOIN t ON a.id = t.id" (join :t {:a.id :t.id})))) - -(deftest select-join-dsl - (is (= ["SELECT * FROM a JOIN b ON a.id = b.id"] (select * :a (join :b {:a.id :b.id})))) - (is (= ["SELECT * FROM a JOIN b ON a.id = b.id JOIN c ON c.id = b.id"] - (select * :a (join :b {:a.id :b.id}) (join :c {:c.id :b.id}))))) - -(deftest where-dsl - (is (= ["id = ?" 42] (where {:id 42}))) - (is (= ["id IS NULL"] (where {:id nil})))) - -(deftest select-where-dsl - (is (#{["SELECT * FROM a WHERE c = ? AND b = ?" 3 2] - ["SELECT * FROM a WHERE b = ? AND c = ?" 2 3]} - (select * :a (where {:b 2 :c 3})))) - (is (#{["SELECT * FROM a WHERE c IS NULL AND b = ?" 2] - ["SELECT * FROM a WHERE b = ? AND c IS NULL" 2]} - (select * :a (where {:b 2 :c nil}))))) - -(deftest order-by-dsl - (is (= "" (order-by []))) - (is (= "ORDER BY a ASC" (order-by :a))) - (is (= "ORDER BY a ASC" (order-by [:a]))) - (is (= "ORDER BY a DESC" (order-by {:a :desc}))) - (is (= "ORDER BY a ASC,b ASC" (order-by [:a :b]))) - (is (= "ORDER BY a DESC,b ASC" (order-by [{:a :desc} :b]))) - (is (= "ORDER BY a DESC,b DESC" (order-by [{:a :desc} {:b :desc}]))) - (is (= "ORDER BY `a` ASC,`b` DESC" (entities (quoted \`) (order-by [{:a :asc} {:b :desc}])))) - (is (= "ORDER BY `a` ASC,`b` DESC" (order-by [{:a :asc} {:b :desc}] :entities (quoted \`))))) - -(deftest select-order-dsl - (is (= ["SELECT id FROM person ORDER BY name ASC"] (select :id :person (order-by :name)))) - (is (= ["SELECT a FROM b JOIN c ON b.id = c.id ORDER BY d ASC" - (select :a :b (join :c {:b.id :c.id}) (order-by :d))])) - (is (= ["SELECT a FROM b WHERE c = ? ORDER BY d ASC" 3] - (select :a :b (where {:c 3}) (order-by :d)))) - (is (= ["SELECT a FROM b JOIN c ON b.id = c.id WHERE d = ? ORDER BY e ASC" 4] - (select :a :b (join :c {:b.id :c.id}) (where {:d 4}) (order-by :e))))) - -(deftest select-join-alias-dsl - (is (= ["SELECT a.id,b.name FROM aa a JOIN bb b ON a.id = b.id WHERE b.test = ?" 42] - (select [:a.id :b.name] {:aa :a} - (join {:bb :b} {:a.id :b.id}) - (where {:b.test 42})))) - (is (= ["SELECT `a`.`id`,`b`.`name` FROM `aa` `a` JOIN `bb` `b` ON `a`.`id` = `b`.`id` WHERE `b`.`test` = ?" 42] - (entities (quoted \`) - (select [:a.id :b.name] {:aa :a} - (join {:bb :b} {:a.id :b.id}) - (where {:b.test 42})))))) - -(deftest update-dsl - (is (= ["UPDATE a SET b = ?" 2] (update :a {:b 2}))) - (is (= ["UPDATE a SET b = ? WHERE c = ?" 2 3] (update :a {:b 2} (where {:c 3})))) - (is (= ["UPDATE `a` SET `b` = ? WHERE `c` = ?" 2 3] - (entities (quoted \`) (update :a {:b 2} (where {:c 3})))))) - -(deftest delete-dsl - (is (= ["DELETE FROM a WHERE b = ?" 2] (delete :a (where {:b 2})))) - (is (#{["DELETE FROM a WHERE c IS NULL AND b = ?" 2] - ["DELETE FROM a WHERE b = ? AND c IS NULL" 2]} - (delete :a (where {:b 2 :c nil})))) - (is (= ["DELETE FROM `a` WHERE `b` = ?" 2] - (entities (quoted \`) (delete :a (where {:b 2})))))) - -(deftest insert-dsl - (is (= ["INSERT INTO a ( b ) VALUES ( ? )" [2]] (insert :a [:b] [2]))) - (is (= ["INSERT INTO a VALUES ( ? )" [2]] (insert :a nil [2]))) - (is (= ["INSERT INTO a VALUES ( ? )" [2]] (insert :a [] [2]))) - (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2]] (insert :a {:b 2}))) - (is (= ["INSERT INTO a ( b ) VALUES ( ? )" [2] [3]] (insert :a [:b] [2] [3]))) - (is (= ["INSERT INTO a VALUES ( ? )" [2] [3]] (insert :a nil [2] [3]))) - (is (= ["INSERT INTO a VALUES ( ? )" [2] [3]] (insert :a [] [2] [3]))) - (is (= ["INSERT INTO a ( b, c, d ) VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] - (insert :a [:b :c :d] [2 3 4] [3 4 5]))) - (is (= ["INSERT INTO a VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] - (insert :a nil [2 3 4] [3 4 5]))) - (is (= ["INSERT INTO a VALUES ( ?, ?, ? )" [2 3 4] [3 4 5]] - (insert :a [] [2 3 4] [3 4 5]))) - (is (= [["INSERT INTO a ( b ) VALUES ( ? )" 2] - ["INSERT INTO a ( b ) VALUES ( ? )" 3]] - (insert :a {:b 2} {:b 3}))) - (is (= ["INSERT INTO `a` ( `b` ) VALUES ( ? )" [2]] - (entities (quoted \`) (insert :a [:b] [2])))) - (is (= ["INSERT INTO `a` VALUES ( ? )" [2]] - (entities (quoted \`) (insert :a nil [2])))) - (is (= ["INSERT INTO `a` VALUES ( ? )" [2]] - (entities (quoted \`) (insert :a [] [2]))))) - -(deftest bad-insert-args - (is (thrown? IllegalArgumentException (insert))) - (is (thrown? IllegalArgumentException (insert :a))) - (is (thrown? IllegalArgumentException (insert :a [:b]))) - (is (thrown? IllegalArgumentException (insert :a {:b 1} [:c] [2]))) - (is (thrown? IllegalArgumentException (insert :a [:b] [2 3])))) \ No newline at end of file From 7867868750dfbba2fa57aec938a132c969d0d8bb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Nov 2013 22:48:22 -0800 Subject: [PATCH 158/630] Update docstrings to avoid references to DSLs --- src/main/clojure/clojure/java/jdbc.clj | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e1d65914..d50926df 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -716,7 +716,7 @@ made at some future date." } column names in the map (default 'as-is') and whether to run the delete in a transaction (default true). Example: - (delete! db :person (where {:zip 94546})) + (delete! db :person ["zip = ?" 94546]) is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" [db table where-clause & {:keys [entities transaction?] @@ -835,7 +835,7 @@ made at some future date." } "Given a table name and a map of columns to set, and optional map of columns to match (and an optional entities spec), return a vector of the SQL for that update followed by its parameters. Example: - (update :person {:zip 94540} (where {:zip 94546})) + (update :person {:zip 94540} ["zip = ?" 94546]) returns: [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" [table set-map & where-etc] @@ -862,7 +862,7 @@ made at some future date." } specify how column names (in the set / match maps) should be transformed (default 'as-is') and whether to run the update in a transaction (default true). Example: - (update! db :person {:zip 94540} (where {:zip 94546})) + (update! db :person {:zip 94540} ["zip = ?" 94546]) is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" [db table set-map where-clause & {:keys [entities transaction?] From 1e5969c6ba5211773e6a8d20dd4150c546e0001e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 15:41:43 -0800 Subject: [PATCH 159/630] Fix typos in docstrings --- src/main/clojure/clojure/java/jdbc.clj | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d50926df..8a2b7e1a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -716,7 +716,7 @@ made at some future date." } column names in the map (default 'as-is') and whether to run the delete in a transaction (default true). Example: - (delete! db :person ["zip = ?" 94546]) + (delete! db :person [\"zip = ?\" 94546]) is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" [db table where-clause & {:keys [entities transaction?] @@ -835,7 +835,7 @@ made at some future date." } "Given a table name and a map of columns to set, and optional map of columns to match (and an optional entities spec), return a vector of the SQL for that update followed by its parameters. Example: - (update :person {:zip 94540} ["zip = ?" 94546]) + (update :person {:zip 94540} [\"zip = ?\" 94546]) returns: [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" [table set-map & where-etc] @@ -862,7 +862,7 @@ made at some future date." } specify how column names (in the set / match maps) should be transformed (default 'as-is') and whether to run the update in a transaction (default true). Example: - (update! db :person {:zip 94540} ["zip = ?" 94546]) + (update! db :person {:zip 94540} [\"zip = ?\" 94546]) is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" [db table set-map where-clause & {:keys [entities transaction?] From 37e7e4894f3e1f9860eabe46f7f132f490490287 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 15:42:00 -0800 Subject: [PATCH 160/630] Update docstring about deprecated API --- src/main/clojure/clojure/java/jdbc.clj | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8a2b7e1a..24c293b6 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -42,10 +42,9 @@ For more documentation, see: http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html As of release 0.3.0, the API has undergone a major overhaul and most of the -original API has been deprecated in favor of a more idiomatic API, and a -minimal DSL for generating SQL has been added as an option. The original -API is still supported but will be deprecated before a 1.0.0 release is -made at some future date." } +original API has been deprecated in favor of a more idiomatic API. The +original API has been moved to java.jdbc.deprecated for backward +compatibility but it will be removed before a 1.0.0 release." } clojure.java.jdbc (:import [java.net URI] [java.sql BatchUpdateException DriverManager From bcc6d9c92d42f02c55c3a3b2d1af1ec935d19a65 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 15:42:32 -0800 Subject: [PATCH 161/630] Add 0.2.3 API as clojure.java.jdbc.deprecated namespace will full set of tests. --- .../clojure/clojure/java/jdbc/deprecated.clj | 728 ++++++++++++++++++ .../clojure/clojure/java/test_deprecated.clj | 357 +++++++++ 2 files changed, 1085 insertions(+) create mode 100644 src/main/clojure/clojure/java/jdbc/deprecated.clj create mode 100644 src/test/clojure/clojure/java/test_deprecated.clj diff --git a/src/main/clojure/clojure/java/jdbc/deprecated.clj b/src/main/clojure/clojure/java/jdbc/deprecated.clj new file mode 100644 index 00000000..c576dbe7 --- /dev/null +++ b/src/main/clojure/clojure/java/jdbc/deprecated.clj @@ -0,0 +1,728 @@ +;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; jdbc.clj +;; +;; A Clojure interface to sql databases via jdbc +;; +;; scgilardi (gmail) +;; Created 2 April 2008 +;; +;; seancorfield (gmail) +;; Migrated from clojure.contrib.sql 17 April 2011 + +(ns + ^{ + :author "Stephen C. Gilardi, Sean Corfield", + :doc "A Clojure interface to SQL databases via JDBC + +This namespace contains the old API (0.2.3) which was deprecated in the 0.3.0 +release and is provided for backward compatibility. This API will be removed +completely before a 1.0.0 release so will need to migrate code to the new API +before that release. + +clojure.java.jdbc provides a simple abstraction for CRUD (create, read, +update, delete) operations on a SQL database, along with basic transaction +support. Basic DDL operations are also supported (create table, drop table, +access to table metadata). + +Maps are used to represent records, making it easy to store and retrieve +data. Results can be processed using any standard sequence operations. + +For most operations, Java's PreparedStatement is used so your SQL and +parameters can be represented as simple vectors where the first element +is the SQL string, with ? for each parameter, and the remaining elements +are the parameter values to be substituted. In general, operations return +the number of rows affected, except for a single record insert where any +generated keys are returned (as a map)." } + clojure.java.jdbc.deprecated + (:import [java.net URI] + [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement] + [java.util Hashtable Map Properties] + [javax.naming InitialContext Name] + [javax.sql DataSource]) + (:refer-clojure :exclude [resultset-seq]) + (:require [clojure.string :as str])) + +(def ^{:private true :dynamic true + :doc "The default entity naming strategy is to do nothing."} + *as-str* + identity) + +(def ^{:private true :dynamic true + :doc "The default keyword naming strategy is to lowercase the entity."} + *as-key* + str/lower-case) + +(defn as-str + "Given a naming strategy and a keyword, return the keyword as a + string per that naming strategy. Given (a naming strategy and) + a string, return it as-is. + A keyword of the form :x.y is treated as keywords :x and :y, + both are turned into strings via the naming strategy and then + joined back together so :x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." + [f x] + (if (instance? clojure.lang.Named x) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))) + (str x))) + +(defn as-key + "Given a naming strategy and a string, return the string as a + keyword per that naming strategy. Given (a naming strategy and) + a keyword, return it as-is." + [f x] + (if (instance? clojure.lang.Named x) + x + (keyword (f (str x))))) + +(defn as-identifier + "Given a keyword, convert it to a string using the current naming + strategy. + Given a string, return it as-is." + ([x] (as-identifier x *as-str*)) + ([x f-entity] (as-str f-entity x))) + +(defn as-keyword + "Given an entity name (string), convert it to a keyword using the + current naming strategy. + Given a keyword, return it as-is." + ([x] (as-keyword x *as-key*)) + ([x f-keyword] (as-key f-keyword x))) + +(defn- ^Properties as-properties + "Convert any seq of pairs to a java.utils.Properties instance. + Uses as-str to convert both keys and values into strings." + [m] + (let [p (Properties.)] + (doseq [[k v] m] + (.setProperty p (as-str identity k) (as-str identity v))) + p)) + +(def ^{:private true :dynamic true} *db* {:connection nil :level 0}) + +(def ^{:private true :doc "Map of classnames to subprotocols"} classnames + {"postgresql" "org.postgresql.Driver" + "mysql" "com.mysql.jdbc.Driver" + "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver" + "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" + "derby" "org.apache.derby.jdbc.EmbeddedDriver" + "hsqldb" "org.hsqldb.jdbcDriver" + "sqlite" "org.sqlite.JDBC"}) + +(def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols + {"postgres" "postgresql"}) + +(defn find-connection + "Returns the current database connection (or nil if there is none)" + ^java.sql.Connection [] + (:connection *db*)) + +(defn connection + "Returns the current database connection (or throws if there is none)" + ^java.sql.Connection [] + (or (find-connection) + (throw (Exception. "no current database connection")))) + +(defn- parse-properties-uri [^URI uri] + (let [host (.getHost uri) + port (if (pos? (.getPort uri)) (.getPort uri)) + path (.getPath uri) + scheme (.getScheme uri)] + (merge + {:subname (if port + (str "//" host ":" port path) + (str "//" host path)) + :subprotocol (subprotocols scheme scheme)} + (if-let [user-info (.getUserInfo uri)] + {:user (first (str/split user-info #":")) + :password (second (str/split user-info #":"))})))) + +(defn- strip-jdbc [^String spec] + (if (.startsWith spec "jdbc:") + (.substring spec 5) + spec)) + +(defn- get-connection + "Creates a connection to a database. db-spec is a map containing connection + parameters - see with-connection for full details." + [{:keys [factory + connection-uri + classname subprotocol subname + datasource username password + name environment] + :as db-spec}] + (cond + (instance? URI db-spec) + (get-connection (parse-properties-uri db-spec)) + + (string? db-spec) + (get-connection (URI. (strip-jdbc db-spec))) + + factory + (factory (dissoc db-spec :factory)) + + connection-uri + (DriverManager/getConnection connection-uri) + + (and subprotocol subname) + (let [url (format "jdbc:%s:%s" subprotocol subname) + etc (dissoc db-spec :classname :subprotocol :subname) + classname (or classname (classnames subprotocol))] + (clojure.lang.RT/loadClassForName classname) + (DriverManager/getConnection url (as-properties etc))) + + (and datasource username password) + (.getConnection ^DataSource datasource ^String username ^String password) + + datasource + (.getConnection ^DataSource datasource) + + name + (let [env (and environment (Hashtable. ^Map environment)) + context (InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (.getConnection datasource)) + + :else + (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] + (throw (IllegalArgumentException. msg))))) + +(defn- make-name-unique + "Given a collection of column names and a new column name, + return the new column name made unique, if necessary, by + appending _N where N is some unique integer suffix." + [cols col-name n] + (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] + (if (apply distinct? suffixed-name cols) + suffixed-name + (recur cols col-name (inc n))))) + +(defn- make-cols-unique + "Given a collection of column names, rename duplicates so + that the result is a collection of unique column names." + [cols] + (if (or (empty? cols) (apply distinct? cols)) + cols + (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) + +(defn resultset-seq + "Creates and returns a lazy sequence of maps corresponding to + the rows in the java.sql.ResultSet rs. Based on clojure.core/resultset-seq + but it respects the current naming strategy. Duplicate column names are + made unique by appending _N before applying the naming strategy (where + N is a unique integer)." + [^ResultSet rs] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (->> idxs + (map (fn [^Integer i] (.getColumnLabel rsmeta i))) + make-cols-unique + (map (comp keyword *as-key*))) + row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) + ;; This used to use create-struct (on keys) and then struct to populate each row. + ;; That had the side effect of preserving the order of columns in each row. As + ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't + ;; want to switch to records so we're using regular maps instead. We no longer + ;; guarantee column order in rows but using into {} should preserve order for up + ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying + ;; on the order-preserving behavior of structmaps, we can reconsider... + rows (fn thisfn [] + (when (.next rs) + (cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))] + (rows))) + +(defn as-quoted-str + "Given a quoting pattern - either a single character or a vector pair of + characters - and a string, return the quoted string: + (as-quoted-str X foo) will return XfooX + (as-quoted-str [A B] foo) will return AfooB" + [q x] + (if (vector? q) + (str (first q) x (last q)) + (str q x q))) + +(defn as-named-identifier + "Given a naming strategy and a keyword, return the keyword as a string using the + entity naming strategy. + Given a naming strategy and a string, return the string as-is. + The naming strategy should either be a function (the entity naming strategy) or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or keyword naming strategy respectively." + [naming-strategy x] + (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) + +(defn as-named-keyword + "Given a naming strategy and a string, return the string as a keyword using the + keyword naming strategy. + Given a naming strategy and a keyword, return the keyword as-is. + The naming strategy should either be a function (the entity naming strategy) or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or keyword naming strategy respectively. + Note that providing a single function will cause the default keyword naming + strategy to be used!" + [naming-strategy x] + (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) + +(defn as-quoted-identifier + "Given a quote pattern - either a single character or a pair of characters in + a vector - and a keyword, return the keyword as a string using a simple + quoting naming strategy. + Given a qote pattern and a string, return the string as-is. + (as-quoted-identifier X :name) will return XnameX as a string. + (as-quoted-identifier [A B] :name) will return AnameB as a string." + [q x] + (as-identifier x (partial as-quoted-str q))) + +(defmacro with-naming-strategy + "Evaluates body in the context of a naming strategy. + The naming strategy is either a function - the entity naming strategy - or + a map containing :entity and/or :keyword keys which provide the entity naming + strategy and/or the keyword naming strategy respectively. The default entity + naming strategy is identity; the default keyword naming strategy is lower-case." + [naming-strategy & body ] + `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) + *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) + +(defmacro with-quoted-identifiers + "Evaluates body in the context of a simple quoting naming strategy." + [q & body ] + `(binding [*as-str* (partial as-quoted-str ~q)] ~@body)) + +(defn with-connection* + "Evaluates func in the context of a new connection to a database then + closes the connection." + [db-spec func] + (with-open [^java.sql.Connection con (get-connection db-spec)] + (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] + (func)))) + +(defmacro with-connection + "Evaluates body in the context of a new connection to a database then + closes the connection. db-spec is a map containing values for one of the + following parameter sets: + + Factory: + :factory (required) a function of one argument, a map of params + (others) (optional) passed to the factory function in a map + + DriverManager: + :subprotocol (required) a String, the jdbc subprotocol + :subname (required) a String, the jdbc subname + :classname (optional) a String, the jdbc driver class name + (others) (optional) passed to the driver as properties. + + DataSource: + :datasource (required) a javax.sql.DataSource + :username (optional) a String + :password (optional) a String, required if :username is supplied + + JNDI: + :name (required) a String or javax.naming.Name + :environment (optional) a java.util.Map + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + + URI: + Parsed JDBC connection string - see below + + String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." + [db-spec & body] + `(with-connection* ~db-spec (fn [] ~@body))) + +(defn- rollback + "Accessor for the rollback flag on the current connection" + ([] + (deref (:rollback *db*))) + ([val] + (swap! (:rollback *db*) (fn [_] val)))) + +(defn transaction* + "Evaluates func as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If rollback is set within scope of the outermost transaction, + the entire transaction will be rolled back rather than committed when + complete." + [func] + (binding [*db* (update-in *db* [:level] inc)] + ;; This ugliness makes it easier to catch SQLException objects + ;; rather than something wrapped in a RuntimeException which + ;; can really obscure your code when working with JDBC from + ;; Clojure... :( + (letfn [(throw-non-rte [^Throwable ex] + (cond (instance? java.sql.SQLException ex) (throw ex) + (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) + :else (throw ex)))] + (if (= (:level *db*) 1) + (let [^java.sql.Connection con (connection) + auto-commit (.getAutoCommit con)] + (io! + (.setAutoCommit con false) + (try + (let [result (func)] + (if (rollback) + (.rollback con) + (.commit con)) + result) + (catch Exception e + (.rollback con) + (throw-non-rte e)) + (finally + (rollback false) + (.setAutoCommit con auto-commit))))) + (try + (func) + (catch Exception e + (throw-non-rte e))))))) + +(defmacro transaction + "Evaluates body as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If set-rollback-only is called within scope of the outermost + transaction, the entire transaction will be rolled back rather than + committed when complete." + [& body] + `(transaction* (fn [] ~@body))) + +(defn set-rollback-only + "Marks the outermost transaction such that it will rollback rather than + commit when complete" + [] + (rollback true)) + +(defn is-rollback-only + "Returns true if the outermost transaction will rollback rather than + commit when complete" + [] + (rollback)) + +(defn- execute-batch + "Executes a batch of SQL commands and returns a sequence of update counts. + (-2) indicates a single operation operating on an unknown number of rows. + Specifically, Oracle returns that and we must call getUpdateCount() to get + the actual number of rows affected. In general, operations return an array + of update counts, so this may not be a general solution for Oracle..." + [stmt] + (let [result (.executeBatch stmt)] + (if (and (= 1 (count result)) (= -2 (first result))) + (list (.getUpdateCount stmt)) + (seq result)))) + +(defn do-commands + "Executes SQL commands on the open database connection." + [& commands] + (with-open [^Statement stmt (let [^java.sql.Connection con (connection)] (.createStatement con))] + (doseq [^String cmd commands] + (.addBatch stmt cmd)) + (transaction + (execute-batch stmt)))) + +(def ^{:private true + :doc "Map friendly :concurrency values to ResultSet constants."} + result-set-concurrency + {:read-only ResultSet/CONCUR_READ_ONLY + :updatable ResultSet/CONCUR_UPDATABLE}) + +(def ^{:private true + :doc "Map friendly :cursors values to ResultSet constants."} + result-set-holdability + {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT + :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) + +(def ^{:private true + :doc "Map friendly :type values to ResultSet constants."} + result-set-type + {:forward-only ResultSet/TYPE_FORWARD_ONLY + :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE + :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) + +(defn prepare-statement + "Create a prepared statement from a connection, a SQL string and an + optional list of parameters: + :return-keys true | false - default false + :result-type :forward-only | :scroll-insensitive | :scroll-sensitive + :concurrency :read-only | :updatable + :fetch-size n + :max-rows n" + [^java.sql.Connection con ^String sql & {:keys [return-keys result-type concurrency cursors fetch-size max-rows]}] + (let [^PreparedStatement stmt (cond + return-keys (try + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS) + (catch Exception _ + ;; assume it is unsupported and try basic PreparedStatement: + (.prepareStatement con sql))) + (and result-type concurrency) (if cursors + (.prepareStatement con sql + (result-type result-set-type) + (concurrency result-set-concurrency) + (cursors result-set-holdability)) + (.prepareStatement con sql + (result-type result-set-type) + (concurrency result-set-concurrency))) + :else (.prepareStatement con sql))] + (when fetch-size (.setFetchSize stmt fetch-size)) + (when max-rows (.setMaxRows stmt max-rows)) + stmt)) + +(defn- set-parameters + "Add the parameters to the given statement." + [^PreparedStatement stmt params] + (dorun + (map-indexed + (fn [ix value] + (.setObject stmt (inc ix) value)) + params))) + +(defn do-prepared + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. Each param-group is a seq of values for all of + the parameters. + Return a seq of update counts (one count for each param-group)." + [sql & param-groups] + (with-open [^PreparedStatement stmt (prepare-statement (connection) sql)] + (if (empty? param-groups) + (transaction* (fn [] (vector (.executeUpdate stmt)))) + (do + (doseq [param-group param-groups] + (set-parameters stmt param-group) + (.addBatch stmt)) + (transaction* (fn [] (execute-batch stmt))))))) + +(defn create-table-ddl + "Given a table name and column specs with an optional table-spec + return the DDL string for creating a table based on that." + [name & specs] + (let [split-specs (partition-by #(= :table-spec %) specs) + col-specs (first split-specs) + table-spec (first (second (rest split-specs))) + table-spec-str (or (and table-spec (str " " table-spec)) "") + specs-to-string (fn [specs] + (apply str + (map as-identifier + (apply concat + (interpose [", "] + (map (partial interpose " ") specs))))))] + (format "CREATE TABLE %s (%s)%s" + (as-identifier name) + (specs-to-string col-specs) + table-spec-str))) + +(defn create-table + "Creates a table on the open database connection given a table name and + specs. Each spec is either a column spec: a vector containing a column + name and optionally a type and other constraints, or a table-level + constraint: a vector containing words that express the constraint. An + optional suffix to the CREATE TABLE DDL describing table attributes may + by provided as :table-spec {table-attributes-string}. All words used to + describe the table may be supplied as strings or keywords." + [name & specs] + (do-commands (apply create-table-ddl name specs))) + +(defn drop-table + "Drops a table on the open database connection given its name, a string + or keyword" + [name] + (do-commands + (format "DROP TABLE %s" (as-identifier name)))) + +(defn do-prepared-return-keys + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. The param-group is a seq of values for all of + the parameters. + Return the generated keys for the (single) update/insert." + [sql param-group] + (with-open [^PreparedStatement stmt (prepare-statement (connection) sql :return-keys true)] + (set-parameters stmt param-group) + (transaction* (fn [] (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (resultset-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))))) + +(defn insert-values + "Inserts rows into a table with values for specified columns only. + column-names is a vector of strings or keywords identifying columns. Each + value-group is a vector containing a values for each column in + order. When inserting complete rows (all columns), consider using + insert-rows instead. + If a single set of values is inserted, returns a map of the generated keys." + [table column-names & value-groups] + (let [column-strs (map as-identifier column-names) + n (count (first value-groups)) + return-keys (= 1 (count value-groups)) + prepared-statement (if return-keys do-prepared-return-keys do-prepared) + template (apply str (interpose "," (repeat n "?"))) + columns (if (seq column-names) + (format "(%s)" (apply str (interpose "," column-strs))) + "")] + (apply prepared-statement + (format "INSERT INTO %s %s VALUES (%s)" + (as-identifier table) columns template) + value-groups))) + +(defn insert-rows + "Inserts complete rows into a table. Each row is a vector of values for + each of the table's columns in order. + If a single row is inserted, returns a map of the generated keys." + [table & rows] + (apply insert-values table nil rows)) + +(defn insert-records + "Inserts records into a table. records are maps from strings or keywords + (identifying columns) to values. Inserts the records one at a time. + Returns a sequence of maps containing the generated keys for each record." + [table & records] + (let [ins-v (fn [record] (insert-values table (keys record) (vals record)))] + (doall (map ins-v records)))) + +(defn insert-record + "Inserts a single record into a table. A record is a map from strings or + keywords (identifying columns) to values. + Returns a map of the generated keys." + [table record] + (let [keys (insert-records table record)] + (first keys))) + +(defn delete-rows + "Deletes rows from a table. where-params is a vector containing a string + providing the (optionally parameterized) selection criteria followed by + values for any parameters." + [table where-params] + (let [[where & params] where-params] + (do-prepared + (format "DELETE FROM %s WHERE %s" + (as-identifier table) where) + params))) + +(defn update-values + "Updates values on selected rows in a table. where-params is a vector + containing a string providing the (optionally parameterized) selection + criteria followed by values for any parameters. record is a map from + strings or keywords (identifying columns) to updated values." + [table where-params record] + (let [[where & params] where-params + column-strs (map as-identifier (keys record)) + columns (apply str (concat (interpose "=?, " column-strs) "=?"))] + (do-prepared + (format "UPDATE %s SET %s WHERE %s" + (as-identifier table) columns where) + (concat (vals record) params)))) + +(defn update-or-insert-values + "Updates values on selected rows in a table, or inserts a new row when no + existing row matches the selection criteria. where-params is a vector + containing a string providing the (optionally parameterized) selection + criteria followed by values for any parameters. record is a map from + strings or keywords (identifying columns) to updated values." + [table where-params record] + (transaction + (let [result (update-values table where-params record)] + (if (zero? (first result)) + (insert-values table (keys record) (vals record)) + result)))) + +(defn with-query-results* + "Executes a query, then evaluates func passing in a seq of the results as + an argument. The first argument is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + [sql-params func] + (when-not (vector? sql-params) + (let [^Class sql-params-class (class sql-params) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-params-class) + (pr-str sql-params))] + (throw (IllegalArgumentException. msg)))) + (let [special (first sql-params) + sql-is-first (string? special) + options-are-first (map? special) + sql (cond sql-is-first special + options-are-first (second sql-params)) + params (vec (cond sql-is-first (rest sql-params) + options-are-first (rest (rest sql-params)) + :else (rest sql-params))) + prepare-args (when (map? special) (flatten (seq special)))] + (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (connection) sql prepare-args))] + (set-parameters stmt params) + (with-open [rset (.executeQuery stmt)] + (func (resultset-seq rset)))))) + +(defmacro with-query-results + "Executes a query, then evaluates body with results bound to a seq of the + results. sql-params is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + [options sql & params] - options and a SQL query for creating a + PreparedStatement, follwed by any parameters it needs + See prepare-statement for supported options." + [results sql-params & body] + `(with-query-results* ~sql-params (fn [~results] ~@body))) + +(defn print-sql-exception + "Prints the contents of an SQLException to *out*" + [^SQLException exception] + (let [^Class exception-class (class exception)] + (println + (format (str "%s:" \newline + " Message: %s" \newline + " SQLState: %s" \newline + " Error Code: %d") + (.getSimpleName exception-class) + (.getMessage exception) + (.getSQLState exception) + (.getErrorCode exception))))) + +(defn print-sql-exception-chain + "Prints a chain of SQLExceptions to *out*" + [^SQLException exception] + (loop [e exception] + (when e + (print-sql-exception e) + (recur (.getNextException e))))) + +(def ^{:private true} special-counts + {Statement/EXECUTE_FAILED "EXECUTE_FAILED" + Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) + +(defn print-update-counts + "Prints the update counts from a BatchUpdateException to *out*" + [^BatchUpdateException exception] + (println "Update counts:") + (dorun + (map-indexed + (fn [index count] + (println (format " Statement %d: %s" + index + (get special-counts count count)))) + (.getUpdateCounts exception)))) diff --git a/src/test/clojure/clojure/java/test_deprecated.clj b/src/test/clojure/clojure/java/test_deprecated.clj new file mode 100644 index 00000000..fcfe0bba --- /dev/null +++ b/src/test/clojure/clojure/java/test_deprecated.clj @@ -0,0 +1,357 @@ +;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; test_jdbc.clj +;; +;; This namespace contains tests that exercise the deprecated API for java.jdbc +;; so these tests expect databases to be available. Embedded databases can +;; be tested without external infrastructure (Apache Derby, HSQLDB). Other +;; databases will be available for testing in different environments. The +;; available databases for testing can be configured below. +;; +;; scgilardi (gmail) +;; Created 13 September 2008 +;; +;; seancorfield (gmail) +;; Migrated from clojure.contrib.test-sql 17 April 2011 + +(ns clojure.java.test-deprecated + (:use clojure.test) + (:require [clojure.java.jdbc.deprecated :as sql])) + +;; Set test-databases according to whether you have the local database available: +;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] +;; Apache Derby and HSQLDB can run without an external setup. +(def test-databases + (if-let [dbs (System/getenv "TEST_DBS")] + (map keyword (.split dbs ",")) + ;; enable more by default once the build server is equipped? + [:derby :hsqldb :sqlite])) + +;; MS SQL Server requires more specialized configuration: +(def mssql-host + (if-let [host (System/getenv "TEST_MSSQL_HOST")] host "127.0.0.1\\SQLEXPRESS")) +(def mssql-port + (if-let [port (System/getenv "TEST_MSSQL_PORT")] port "1433")) +(def mssql-user + (if-let [user (System/getenv "TEST_MSSQL_USER")] user "sa")) +(def mssql-pass + (if-let [pass (System/getenv "TEST_MSSQL_PASS")] pass "")) +(def mssql-dbname + (if-let [name (System/getenv "TEST_MSSQL_NAME")] name "clojure_test")) +(def jtds-host + (if-let [host (System/getenv "TEST_JTDS_HOST")] host mssql-host)) +(def jtds-port + (if-let [port (System/getenv "TEST_JTDS_PORT")] port mssql-port)) +(def jtds-user + (if-let [user (System/getenv "TEST_JTDS_USER")] user mssql-user)) +(def jtds-pass + (if-let [pass (System/getenv "TEST_JTDS_PASS")] pass mssql-pass)) +(def jtds-dbname + (if-let [name (System/getenv "TEST_JTDS_NAME")] name mssql-dbname)) + +;; database connections used for testing: + +(def mysql-db {:subprotocol "mysql" + :subname "//127.0.0.1:3306/clojure_test" + :user "clojure_test" + :password "clojure_test"}) + +(def derby-db {:subprotocol "derby" + :subname "clojure_test_derby" + :create true}) + +(def hsqldb-db {:subprotocol "hsqldb" + :subname "clojure_test_hsqldb"}) + +(def sqlite-db {:subprotocol "sqlite" + :subname "clojure_test_sqlite"}) + +(def postgres-db {:subprotocol "postgresql" + :subname "clojure_test" + :user "clojure_test" + :password "clojure_test"}) + +(def mssql-db {:subprotocol "sqlserver" + :subname (str "//" mssql-host ":" mssql-port ";DATABASENAME=" mssql-dbname) + :user mssql-user + :password mssql-pass}) + +(def jtds-db {:subprotocol "jtds:sqlserver" + :subname (str "//" jtds-host ":" jtds-port "/" jtds-dbname) + :user jtds-user + :password jtds-pass}) + +;; To test against the stringified DB connection settings: +(def mysql-str-db + "mysql://clojure_test:clojure_test@localhost:3306/clojure_test") + +(def mysql-jdbc-str-db + "jdbc:mysql://clojure_test:clojure_test@localhost:3306/clojure_test") + +(def postgres-str-db + "postgres://clojure_test:clojure_test@localhost/clojure_test") + +(defn- test-specs + "Return a sequence of db-spec maps that should be used for tests" + [] + (for [db test-databases] + @(ns-resolve 'clojure.java.test-jdbc (symbol (str (name db) "-db"))))) + +(defn- clean-up + "Attempt to drop any test tables before we start a test." + [t] + (doseq [db (test-specs)] + (sql/with-connection db + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/drop-table table) + (catch Exception _ + ;; ignore + ))))) + (t)) + +(use-fixtures + :each clean-up) + +;; We start with all tables dropped and each test has to create the tables +;; necessary for it to do its job, and populate it as needed... + +(defn- create-test-table + "Create a standard test table. Must be inside with-connection. + For MySQL, ensure table uses an engine that supports transactions!" + [table db] + (let [p (:subprotocol db)] + (sql/create-table + table + [:id :int (if (= "mysql" p) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] + [:name "VARCHAR(32)" (if (= "mysql" p) "" "PRIMARY KEY")] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))) + "ENGINE=InnoDB" "")))) + +(deftest test-create-table + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + +(deftest test-drop-table + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit2 db) + (sql/drop-table :fruit2) + (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + +(deftest test-do-commands + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit2 db) + (sql/do-commands "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + +(deftest test-do-prepared1 + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit2 db) + (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") + (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + +(deftest test-do-prepared2 + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit2 db) + (sql/do-prepared "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + +(deftest test-do-prepared3 + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit2 db) + (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) + (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + +(deftest test-do-prepared4 + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit2 db) + (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) + (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + +(deftest test-insert-rows + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (let [r (sql/insert-rows + :fruit + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])] + (is (= '(1 1 1 1) r))) + (is (= 4 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (is (= "Apple" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "red"] (:name (first res))))) + (is (= "juicy" (sql/with-query-results res ["SELECT * FROM fruit WHERE name = ?" "Orange"] (:appearance (first res)))))))) + +(deftest test-insert-values + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (let [r (sql/insert-values + :fruit + [:name :cost] + ["Mango" 722] + ["Feijoa" 441])] + (is (= '(1 1) r))) + (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (is (= "Mango" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 722] (:name (first res)))))))) + +(deftest test-insert-records + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (let [r (sql/insert-records + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + {:name "Kiwifruit" :grade 93})] + (condp = (:subprotocol db) + nil nil ; for the string connection args + "postgresql" (is (= 2 (count r))) + "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) + "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) + "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) + "hsqldb" (is (= '(1 1) r)) + "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} + {(keyword "last_insert_rowid()") 2}) r)) + "derby" (is (= '({:1 nil} {:1 nil}) r)))) + (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (is (= "Pomegranate" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 585] (:name (first res)))))))) + +(deftest test-update-values + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (let [r (sql/insert-rows + :fruit + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])] + (is (= '(1 1 1 1) r))) + (sql/update-values + :fruit + ["name=?" "Banana"] + {:appearance "bruised" :cost 14}) + (is (= 4 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (is (= "Apple" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "red"] (:name (first res))))) + (is (= "Banana" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] (:name (first res))))) + (is (= 14 (sql/with-query-results res ["SELECT * FROM fruit WHERE name = ?" "Banana"] (:cost (first res)))))))) + +(deftest test-update-or-insert-values + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (sql/update-or-insert-values + :fruit + ["name=?" "Pomegranate"] + {:name "Pomegranate" :appearance "fresh" :cost 585}) + (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (is (= 585 (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] (:cost (first res))))) + (sql/update-or-insert-values + :fruit + ["name=?" "Pomegranate"] + {:name "Pomegranate" :appearance "ripe" :cost 565}) + (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (is (= 565 (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] (:cost (first res))))) + (sql/update-or-insert-values + :fruit + ["name=?" "Apple"] + {:name "Apple" :appearance "green" :cost 74}) + (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + +(deftest test-partial-exception + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (try + (sql/transaction + (sql/insert-values + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) + (throw (Exception. "deliberate exception"))) + (catch Exception _ + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))))) + +(deftest test-sql-exception + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (try + (sql/transaction + (sql/insert-values + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + ;; sqlite does not throw exception for too many items + (throw (java.sql.SQLException.))) + (catch java.sql.SQLException _ + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + +(deftest test-rollback + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (try + (sql/transaction + (is (not (sql/is-rollback-only))) + (sql/set-rollback-only) + (is (sql/is-rollback-only)) + (sql/insert-values + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + (is (= 3 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))) + (catch java.sql.SQLException _ + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + +(deftest test-transactions-with-possible-generated-keys-result-set + (doseq [db (test-specs)] + (sql/with-connection db + (create-test-table :fruit db) + (try + (sql/transaction + (sql/set-rollback-only) + (sql/insert-values + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) + (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + +(deftest test-metadata + (doseq [db (test-specs)] + (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) + (let [metadata (sql/with-connection + db + (into [] + (sql/resultset-seq + (-> (sql/connection) + (.getMetaData) + (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] + (is (= [] metadata)))))) From d367b6c9f50a55d1b8ecf9cce3c821d6ddcbf3f7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 15:56:25 -0800 Subject: [PATCH 162/630] Ignore nrepl port --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4d4f0778..3a1aabdc 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ test-all.sh settings.xml /clojure_test_sqlite /.lein-failures +/.nrepl-port From 900ce9d1b8cd297a52f66eb874f3aa85f8f131ae Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 15:56:53 -0800 Subject: [PATCH 163/630] Remove all of the deprecated API to ensure what's left is still usable / complete. --- src/main/clojure/clojure/java/jdbc.clj | 436 ++----------------------- 1 file changed, 32 insertions(+), 404 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 24c293b6..5381d0cd 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -54,48 +54,43 @@ compatibility but it will be removed before a 1.0.0 release." } (:refer-clojure :exclude [resultset-seq]) (:require [clojure.string :as str])) -;; technically deprecated but still used as defaults in a couple of -;; places for backward compatibility... - -(def ^{:private true :dynamic true - :doc "The default entity naming strategy is to do nothing."} - *as-str* - identity) - -(def ^{:private true :dynamic true - :doc "The default keyword naming strategy is to lowercase the entity."} - *as-key* - str/lower-case) - -;; end of deprecated API artifacts... - -(defn as-str - "Given a naming strategy and a keyword, return the keyword as a - string per that naming strategy. Given (a naming strategy and) - a string, return it as-is. +(defn as-sql-name + "Given a naming strategy and a keyword or string, return the keyword + as a string per that naming strategy. A keyword of the form :x.y is treated as keywords :x and :y, both are turned into strings via the naming strategy and then joined back together so :x.y might become `x`.`y` if the naming strategy quotes identifiers with `." ([f] (fn [x] - (as-str f x))) + (as-sql-name f x))) ([f x] - (if (instance? clojure.lang.Named x) - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))) - (str x)))) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))))) + +(defn quoted + "Given a quoting pattern - either a single character or a vector pair of + characters - and a string, return the quoted string: + (quoted \\X \"foo\") will return \"XfooX\" + (quoted [\\A \\B] \"foo\") will return \"AfooB\"" + ([q] + (fn [x] + (as-quoted-str q x))) + ([q x] + (if (vector? q) + (str (first q) x (last q)) + (str q x q)))) (defn- ^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. - Uses as-str to convert both keys and values into strings." + Uses as-sql-name to convert both keys and values into strings." [m] (let [p (Properties.)] (doseq [[k v] m] - (.setProperty p (as-str identity k) (as-str identity v))) + (.setProperty p (as-sql-name identity k) (as-sql-name identity v))) p)) (defprotocol Connectable @@ -317,15 +312,6 @@ compatibility but it will be removed before a 1.0.0 release." } (cons (vec keys) (rows)) (records)))) -(defn - ^{:doc "A deprecated version of result-set-seq that uses the - dynamic *as-key* variable." - :deprecated "0.3.0"} - resultset-seq - [^ResultSet rs & {:keys [identifiers] - :or {identifiers *as-key*}}] - (result-set-seq rs :identifiers identifiers)) - (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. (-2) indicates a single operation operating on an unknown number of rows. @@ -697,8 +683,8 @@ compatibility but it will be removed before a 1.0.0 release." } [table entities] (if (map? table) (let [[k v] (first table)] - (str (as-str entities k) " " (as-str entities v))) - (as-str entities table))) + (str (as-sql-name entities k) " " (as-sql-name entities v))) + (as-sql-name entities table))) (defn- delete-sql "Given a table name, a where class and its parameters and an optional entities spec, @@ -759,8 +745,8 @@ compatibility but it will be removed before a 1.0.0 release." } [col entities] (if (map? col) (let [[k v] (first col)] - (str (as-str entities k) " AS " (as-str entities v))) - (as-str entities col))) + (str (as-sql-name entities k) " AS " (as-sql-name entities v))) + (as-sql-name entities col))) (defn- insert-multi-row-sql "Given a table and a list of columns, followed by a list of column value sequences, @@ -847,7 +833,7 @@ compatibility but it will be removed before a 1.0.0 release." } " SET " (str/join "," (map (fn [k v] - (str (as-str entities k) + (str (as-sql-name entities k) " = " (if (nil? v) "NULL" "?"))) ks vs)) @@ -870,116 +856,6 @@ compatibility but it will be removed before a 1.0.0 release." } (update-sql table set-map where-clause :entities entities) :transaction? transaction?)) -;; original API mostly rewritten in terms of new API primarily without dynamic binding - -(defn ^{:doc "Returns the current database connection (or nil if there is none)" - :deprecated "0.3.0"} - find-connection - ^java.sql.Connection [] - (db-find-connection *db*)) - -(defn ^{:doc "Returns the current database connection (or throws if there is none)" - :deprecated "0.3.0"} - connection - ^java.sql.Connection [] - (db-connection *db*)) - -(defn ^{:doc "Evaluates func in the context of a new connection to a database then - closes the connection." - :deprecated "0.3.0"} - with-connection* - [db-spec func] - (with-open [^java.sql.Connection con (get-connection db-spec)] - (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] - (func)))) - -(defmacro ^{:doc "Evaluates body in the context of a new connection to a database then - closes the connection." - :deprecated "0.3.0"} - with-connection - [db-spec & body] - `(with-connection* ~db-spec (^{:once true} fn* [] ~@body))) - -(defn - ^{:doc "Evaluates func as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If rollback is set within scope of the outermost transaction, - the entire transaction will be rolled back rather than committed when - complete." - :deprecated "0.3.0"} - transaction* - [func] - (binding [*db* (update-in *db* [:level] inc)] - (if (= (:level *db*) 1) - (let [^java.sql.Connection con (get-connection *db*) - auto-commit (.getAutoCommit con)] - (io! - (.setAutoCommit con false) - (try - (let [result (func)] - (if (db-is-rollback-only *db*) - (.rollback con) - (.commit con)) - result) - (catch Throwable t - (.rollback con) - (throw-non-rte t)) - (finally - (db-unset-rollback-only! *db*) - (.setAutoCommit con auto-commit))))) - (try - (func) - (catch Exception e - (throw-non-rte e)))))) - -(defmacro - ^{:doc "Evaluates body as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If set-rollback-only is called within scope of the outermost - transaction, the entire transaction will be rolled back rather than - committed when complete." - :deprecated "0.3.0"} - transaction - [& body] - `(transaction* (^{:once true} fn* [] ~@body))) - -(defn - ^{:doc "Marks the outermost transaction such that it will rollback rather than - commit when complete" - :deprecated "0.3.0"} - set-rollback-only - [] - (db-set-rollback-only! *db*)) - -(defn - ^{:doc "Returns true if the outermost transaction will rollback rather than - commit when complete" - :deprecated "0.3.0"} - is-rollback-only - [] - (db-is-rollback-only *db*)) - -(defn - ^{:doc "Executes SQL commands on the open database connection." - :deprecated "0.3.0"} - do-commands - [& commands] - (apply db-do-commands *db* commands)) - -(defn - ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. Each param-group is a seq of values for all of - the parameters. - Return a seq of update counts (one count for each param-group)." - :deprecated "0.3.0"} - do-prepared - [sql & param-groups] - (apply db-do-prepared *db* sql param-groups)) - (defn create-table-ddl "Given a table name and column specs with an optional table-spec return the DDL string for creating that table." @@ -992,264 +868,16 @@ compatibility but it will be removed before a 1.0.0 release." } table-spec-str (or (and table-spec (str " " table-spec)) "") specs-to-string (fn [specs] (apply str - (map (as-str entities) + (map (as-sql-name entities) (apply concat (interpose [", "] (map (partial interpose " ") specs))))))] (format "CREATE TABLE %s (%s)%s" - (as-str entities name) + (as-sql-name entities name) (specs-to-string col-specs) table-spec-str))) -(defn create-table - "Creates a table on the open database connection given a table name and - specs. Each spec is either a column spec: a vector containing a column - name and optionally a type and other constraints, or a table-level - constraint: a vector containing words that express the constraint. An - optional suffix to the CREATE TABLE DDL describing table attributes may - by provided as :table-spec {table-attributes-string}. All words used to - describe the table may be supplied as strings or keywords." - [name & specs] - (db-do-commands *db* (apply create-table-ddl name specs))) - (defn drop-table-ddl "Given a table name, return the DDL string for dropping that table." [name & {:keys [entities] :or {entities identity}}] - (format "DROP TABLE %s" (as-str entities name))) - -(defn drop-table - "Drops a table on the open database connection given its name, a string - or keyword" - [name] - (db-do-commands *db* (drop-table-ddl name))) - -(defn - ^{:doc "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. The param-group is a seq of values for all of - the parameters. - Return the generated keys for the (single) update/insert." - :deprecated "0.3.0"} - do-prepared-return-keys - [sql param-group] - (db-do-prepared-return-keys *db* sql param-group)) - -(defn - ^{:doc "Inserts rows into a table with values for specified columns only. - column-names is a vector of strings or keywords identifying columns. Each - value-group is a vector containing a values for each column in - order. When inserting complete rows (all columns), consider using - insert-rows instead. - If a single set of values is inserted, returns a map of the generated keys." - :deprecated "0.3.0"} - insert-values - [table column-names & value-groups] - (apply insert! *db* table column-names (concat value-groups [:entities *as-str*]))) - -(defn - ^{:doc "Inserts complete rows into a table. Each row is a vector of values for - each of the table's columns in order. - If a single row is inserted, returns a map of the generated keys." - :deprecated "0.3.0"} - insert-rows - [table & rows] - (apply insert! *db* table nil (concat rows [:entities *as-str*]))) - -(defn - ^{:doc "Inserts records into a table. records are maps from strings or keywords - (identifying columns) to values. Inserts the records one at a time. - Returns a sequence of maps containing the generated keys for each record." - :deprecated "0.3.0"} - insert-records - [table & records] - (apply insert! *db* table (concat records [:entities *as-str*]))) - -(defn - ^{:doc "Inserts a single record into a table. A record is a map from strings or - keywords (identifying columns) to values. - Returns a map of the generated keys." - :deprecated "0.3.0"} - insert-record - [table record] - (first (insert-records table record))) - -(defn - ^{:doc "Deletes rows from a table. where-params is a vector containing a string - providing the (optionally parameterized) selection criteria followed by - values for any parameters." - :deprecated "0.3.0"} - delete-rows - [table where-params] - (apply delete! *db* table where-params [:entities *as-str*])) - -(defn - ^{:doc "Updates values on selected rows in a table. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." - :deprecated "0.3.0"} - update-values - [table where-params record] - (apply update! *db* table record where-params [:entities *as-str*])) - -(defn update-or-insert-values - "Updates values on selected rows in a table, or inserts a new row when no - existing row matches the selection criteria. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." - [table where-params record] - (transaction - (let [result (update-values table where-params record)] - (if (zero? (first result)) - (insert-values table (keys record) (vals record)) - result)))) - -(defn - ^{:doc "Executes a query, then evaluates func passing in a seq of the results as - an argument. The first argument is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, followed by any parameters it needs - See prepare-statement for supported options." - :deprecated "0.3.0"} - with-query-results* - [sql-params func] - (when-not (vector? sql-params) - (let [^Class sql-params-class (class sql-params) - ^String msg (format "\"%s\" expected %s %s, found %s %s" - "sql-params" - "vector" - "[sql param*]" - (.getName sql-params-class) - (pr-str sql-params))] - (throw (IllegalArgumentException. msg)))) - (let [special (first sql-params) - sql-is-first (string? special) - options-are-first (map? special) - sql (cond sql-is-first special - options-are-first (second sql-params)) - params (vec (cond sql-is-first (rest sql-params) - options-are-first (rest (rest sql-params)) - :else (rest sql-params))) - prepare-args (when (map? special) (flatten (seq special)))] - (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (get-connection *db*) sql prepare-args))] - (set-parameters stmt params) ; cannot override this in legacy API! - (with-open [rset (.executeQuery stmt)] - (binding [*db* (assoc *db* :connection (.getConnection stmt))] - (func (resultset-seq rset))))))) - -(defmacro - ^{:doc "Executes a query, then evaluates body with results bound to a seq of the - results. sql-params is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, followed by any parameters it needs - See prepare-statement for supported options." - :deprecated "0.3.0"} - with-query-results - [results sql-params & body] - `(with-query-results* ~sql-params (^{:once true} fn* [~results] ~@body))) - -(defn - ^{:doc "Given a naming strategy and a string, return the string as a - keyword per that naming strategy. Given (a naming strategy and) - a keyword, return it as-is." - :deprecated "0.3.0"} - as-key - [f x] - (if (instance? clojure.lang.Named x) - x - (keyword (f (str x))))) - -(defn - ^{:doc "Given an entity name (string), convert it to a keyword using the - current naming strategy. - Given a keyword, return it as-is." - :deprecated "0.3.0"} - as-keyword - ([x] (as-keyword x *as-key*)) - ([x f-keyword] (as-key f-keyword x))) - -(defn - ^{:doc "Given a naming strategy and a string, return the string as a keyword using - the keyword naming strategy. - Given a naming strategy and a keyword, return the keyword as-is. - The naming strategy should either be a function (the entity naming strategy) - or a map containing :entity and/or :keyword keys which provide the entity - naming strategy and/or keyword naming strategy respectively. - Note that providing a single function will cause the default keyword naming - strategy to be used!" - :deprecated "0.3.0"} - as-named-keyword - [naming-strategy x] - (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) - -(defn - ^{:doc "Given a keyword, convert it to a string using the current naming - strategy. - Given a string, return it as-is." - :deprecated "0.3.0"} - as-identifier - ([x] (as-identifier x *as-str*)) - ([x f-entity] (as-str f-entity x))) - -(defn as-quoted-str - "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (as-quoted-str X foo) will return XfooX - (as-quoted-str [A B] foo) will return AfooB" - ([q] - (fn [x] - (as-quoted-str q x))) - ([q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q)))) - -(defn - ^{:doc "Given a naming strategy and a keyword, return the keyword as a string using - the entity naming strategy. - Given a naming strategy and a string, return the string as-is. - The naming strategy should either be a function (the entity naming strategy) - or a map containing :entity and/or :keyword keys which provide the entity - naming strategy and/or keyword naming strategy respectively." - :deprecated "0.3.0"} - as-named-identifier - [naming-strategy x] - (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) - -(defn - ^{:doc "Given a quote pattern - either a single character or a pair of characters in - a vector - and a keyword, return the keyword as a string using a simple - quoting naming strategy. - Given a quote pattern and a string, return the string as-is. - (as-quoted-identifier X :name) will return XnameX as a string. - (as-quoted-identifier [A B] :name) will return AnameB as a string." - :deprecated "0.3.0"} - as-quoted-identifier - [q x] - (as-identifier x (as-quoted-str q))) - -(defmacro - ^{:doc "Evaluates body in the context of a simple quoting naming strategy." - :deprecated "0.3.0"} - with-quoted-identifiers - [q & body ] - `(binding [*as-str* (as-quoted-str ~q)] ~@body)) - -(defmacro - ^{:doc "Evaluates body in the context of a naming strategy. - The naming strategy is either a function - the entity naming strategy - or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or the keyword naming strategy respectively. The default entity - naming strategy is identity; the default keyword naming strategy is - lower-case." - :deprecated "0.3.0"} - with-naming-strategy - [naming-strategy & body ] - `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) - *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) + (format "DROP TABLE %s" (as-sql-name entities name))) From 8afe80a7a0c077dd464f02d44d597a4f498d3bee Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 16:46:46 -0800 Subject: [PATCH 164/630] Move tests of now-deprecated as-xyz functions from utilities to deprecated tests. --- .../clojure/clojure/java/test_deprecated.clj | 51 +++++++++++++++++++ .../clojure/clojure/java/test_utilities.clj | 50 ------------------ 2 files changed, 51 insertions(+), 50 deletions(-) diff --git a/src/test/clojure/clojure/java/test_deprecated.clj b/src/test/clojure/clojure/java/test_deprecated.clj index fcfe0bba..3d0e5157 100644 --- a/src/test/clojure/clojure/java/test_deprecated.clj +++ b/src/test/clojure/clojure/java/test_deprecated.clj @@ -355,3 +355,54 @@ (.getMetaData) (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] (is (= [] metadata)))))) + +;; basic tests for keyword / entity conversion + +(deftest test-as-identifier + (is (= "kw" (sql/as-identifier "kw"))) + (is (= "kw" (sql/as-identifier :kw))) + (is (= "KW" (sql/as-identifier "KW"))) + (is (= "KW" (sql/as-identifier :KW))) + (is (= "k.w" (sql/as-identifier :k.w)))) + +(deftest test-as-keyword + (is (= :kw (sql/as-keyword "kw"))) + (is (= :kw (sql/as-keyword :kw))) + (is (= :kw (sql/as-keyword "KW"))) + (is (= :KW (sql/as-keyword :KW))) + (is (= :k.w (sql/as-keyword :k.w)))) + +(deftest test-quoted + (is (= "kw" (sql/as-quoted-identifier [ \[ \] ] "kw"))) + (is (= "[kw]" (sql/as-quoted-identifier [ \[ \] ] :kw))) + (is (= "KW" (sql/as-quoted-identifier \` "KW"))) + (is (= "`KW`" (sql/as-quoted-identifier \` :KW))) + (is (= "`k`.`w`" (sql/as-quoted-identifier \` :k.w)))) + +(def quote-dash { :entity (partial sql/as-quoted-str \`) :keyword #(.replace % "_" "-") }) + +(deftest test-named + (is (= "kw" (sql/as-named-identifier quote-dash "kw"))) + (is (= "`kw`" (sql/as-named-identifier quote-dash :kw))) + (is (= "`k`.`w`" (sql/as-named-identifier quote-dash :k.w))) + (is (= :K-W (sql/as-named-keyword quote-dash "K_W"))) + (is (= :K_W (sql/as-named-keyword quote-dash :K_W))) + (is (= :k.w (sql/as-named-keyword quote-dash :k.w)))) + +(deftest test-with-quote + (sql/with-quoted-identifiers [ \[ \] ] + (is (= "kw" (sql/as-identifier "kw"))) + (is (= "[kw]" (sql/as-identifier :kw))) + (is (= "KW" (sql/as-identifier "KW"))) + (is (= "[KW]" (sql/as-identifier :KW))) + (is (= "[k].[w]" (sql/as-identifier :k.w))))) + +(deftest test-with-naming + (sql/with-naming-strategy quote-dash + (is (= "kw" (sql/as-identifier "kw"))) + (is (= "`kw`" (sql/as-identifier :kw))) + (is (= "`k`.`w`" (sql/as-identifier :k.w))) + (is (= :K-W (sql/as-keyword "K_W"))) + (is (= :K_W) (sql/as-keyword :K_W)) + (is (= :k.w) (sql/as-keyword :k.w)))) + diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index 8024d334..c9fcebd2 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -21,56 +21,6 @@ (:use clojure.test) (:require [clojure.java.jdbc :as sql])) -;; basic tests for keyword / entity conversion - -(deftest test-as-identifier - (is (= "kw" (sql/as-identifier "kw"))) - (is (= "kw" (sql/as-identifier :kw))) - (is (= "KW" (sql/as-identifier "KW"))) - (is (= "KW" (sql/as-identifier :KW))) - (is (= "k.w" (sql/as-identifier :k.w)))) - -(deftest test-as-keyword - (is (= :kw (sql/as-keyword "kw"))) - (is (= :kw (sql/as-keyword :kw))) - (is (= :kw (sql/as-keyword "KW"))) - (is (= :KW (sql/as-keyword :KW))) - (is (= :k.w (sql/as-keyword :k.w)))) - -(deftest test-quoted - (is (= "kw" (sql/as-quoted-identifier [ \[ \] ] "kw"))) - (is (= "[kw]" (sql/as-quoted-identifier [ \[ \] ] :kw))) - (is (= "KW" (sql/as-quoted-identifier \` "KW"))) - (is (= "`KW`" (sql/as-quoted-identifier \` :KW))) - (is (= "`k`.`w`" (sql/as-quoted-identifier \` :k.w)))) - -(def quote-dash { :entity (partial sql/as-quoted-str \`) :keyword #(.replace % "_" "-") }) - -(deftest test-named - (is (= "kw" (sql/as-named-identifier quote-dash "kw"))) - (is (= "`kw`" (sql/as-named-identifier quote-dash :kw))) - (is (= "`k`.`w`" (sql/as-named-identifier quote-dash :k.w))) - (is (= :K-W (sql/as-named-keyword quote-dash "K_W"))) - (is (= :K_W (sql/as-named-keyword quote-dash :K_W))) - (is (= :k.w (sql/as-named-keyword quote-dash :k.w)))) - -(deftest test-with-quote - (sql/with-quoted-identifiers [ \[ \] ] - (is (= "kw" (sql/as-identifier "kw"))) - (is (= "[kw]" (sql/as-identifier :kw))) - (is (= "KW" (sql/as-identifier "KW"))) - (is (= "[KW]" (sql/as-identifier :KW))) - (is (= "[k].[w]" (sql/as-identifier :k.w))))) - -(deftest test-with-naming - (sql/with-naming-strategy quote-dash - (is (= "kw" (sql/as-identifier "kw"))) - (is (= "`kw`" (sql/as-identifier :kw))) - (is (= "`k`.`w`" (sql/as-identifier :k.w))) - (is (= :K-W (sql/as-keyword "K_W"))) - (is (= :K_W) (sql/as-keyword :K_W)) - (is (= :k.w) (sql/as-keyword :k.w)))) - (deftest test-print-update-counts (let [bu-ex (java.sql.BatchUpdateException. (int-array [1 2 3]))] (let [e (is (thrown? java.sql.BatchUpdateException (throw bu-ex))) From d7a75d633a67f4afaa0bf0bc7271c9f177104eae Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 16:47:17 -0800 Subject: [PATCH 165/630] Rename as-quoted-str to a more reasonable quoted. --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5381d0cd..a7021e6c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -78,7 +78,7 @@ compatibility but it will be removed before a 1.0.0 release." } (quoted [\\A \\B] \"foo\") will return \"AfooB\"" ([q] (fn [x] - (as-quoted-str q x))) + (quoted q x))) ([q x] (if (vector? q) (str (first q) x (last q)) From ff3a6a50bed7024e40dc230074e9af8e055fe7d6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 16:48:24 -0800 Subject: [PATCH 166/630] Update as-properties now as-sql-name unconditionally calls name on its argument --- src/main/clojure/clojure/java/jdbc.clj | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a7021e6c..abc2641e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -90,7 +90,10 @@ compatibility but it will be removed before a 1.0.0 release." } [m] (let [p (Properties.)] (doseq [[k v] m] - (.setProperty p (as-sql-name identity k) (as-sql-name identity v))) + (.setProperty p (as-sql-name identity k) + (if (instance? clojure.lang.Named v) + (as-sql-name identity v) + (str v)))) p)) (defprotocol Connectable From 27808c0a76e457654b10bcc180215f7d09ee6c59 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 16:48:41 -0800 Subject: [PATCH 167/630] Update all of the non-deprecated tests to use the new API exclusively --- src/test/clojure/clojure/java/test_jdbc.clj | 471 ++++++++++---------- 1 file changed, 230 insertions(+), 241 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 787817ca..09d10862 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -107,13 +107,14 @@ "Attempt to drop any test tables before we start a test." [t] (doseq [db (test-specs)] - (sql/with-connection db - (doseq [table [:fruit :fruit2 :veggies :veggies2]] - (try - (sql/drop-table table) - (catch Exception _ - ;; ignore - ))))) + (sql/db-transaction + [t-conn db] + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/db-do-commands t-conn (sql/drop-table-ddl table)) + (catch Exception _ + ;; ignore + ))))) (t)) (use-fixtures @@ -143,263 +144,266 @@ (defmethod create-test-table :mysql [table db] - (sql/create-table - table - [:id :int "PRIMARY KEY AUTO_INCREMENT"] - [:name "VARCHAR(32)"] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec "ENGINE=InnoDB")) + (sql/db-do-commands + db (sql/create-table-ddl + table + [:id :int "PRIMARY KEY AUTO_INCREMENT"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec "ENGINE=InnoDB"))) (defmethod create-test-table :postgres [table db] - (sql/create-table - table - [:id :serial "PRIMARY KEY"] - [:name "VARCHAR(32)"] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec "")) + (sql/db-do-commands + db (sql/create-table-ddl + table + [:id :serial "PRIMARY KEY"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec ""))) (defmethod create-test-table :default [table db] - (sql/create-table - table - [:id :int "DEFAULT 0"] - [:name "VARCHAR(32)" "PRIMARY KEY"] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec "")) + (sql/db-do-commands + db (sql/create-table-ddl + table + [:id :int "DEFAULT 0"] + [:name "VARCHAR(32)" "PRIMARY KEY"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec ""))) (deftest test-create-table (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (create-test-table :fruit db) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-drop-table (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/drop-table :fruit2) - (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + (create-test-table :fruit2 db) + (sql/db-do-commands db (sql/drop-table-ddl :fruit2)) + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) (deftest test-do-commands (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-commands "DROP TABLE fruit2") - (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + (create-test-table :fruit2 db) + (sql/db-do-commands db "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) (deftest test-do-prepared1 (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + (create-test-table :fruit2 db) + (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) (deftest test-do-prepared2 (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "DROP TABLE fruit2") - (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + (create-test-table :fruit2 db) + (sql/db-do-prepared db "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) (deftest test-do-prepared3 (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + (create-test-table :fruit2 db) + (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) (deftest test-do-prepared4 (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) + (create-test-table :fruit2 db) + (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) + (is (= 2 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) (deftest test-insert-rows (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-rows - :fruit - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])] - (is (= '(1 1 1 1) r))) - (is (= 4 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Apple" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "red"] (:name (first res))))) - (is (= "juicy" (sql/with-query-results res ["SELECT * FROM fruit WHERE name = ?" "Orange"] (:appearance (first res)))))))) + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + nil + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])] + (is (= '(1 1 1 1) r))) + (is (= 4 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] :result-set-fn (comp :name first)))) + (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] :result-set-fn (comp :appearance first)))))) (deftest test-insert-values (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-values - :fruit - [:name :cost] - ["Mango" 722] - ["Feijoa" 441])] - (is (= '(1 1) r))) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Mango" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 722] (:name (first res)))))))) + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + [:name :cost] + ["Mango" 722] + ["Feijoa" 441])] + (is (= '(1 1) r))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Mango" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 722] :result-set-fn (comp :name first)))))) (deftest test-insert-records (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-records - :fruit - {:name "Pomegranate" :appearance "fresh" :cost 585} - {:name "Kiwifruit" :grade 93})] - (condp = (:subprotocol db) - nil (when (mysql? db) - (is (= '({:generated_key 1} {:generated_key 2}) r))) - "postgresql" (is (= 2 (count r))) - "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) - "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) - "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) - "hsqldb" (is (= '(1 1) r)) - "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} - {(keyword "last_insert_rowid()") 2}) r)) - "derby" (is (= (list {(keyword "1") nil} {(keyword "1") nil}) r)))) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Pomegranate" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 585] (:name (first res)))))))) + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + {:name "Kiwifruit" :grade 93})] + (condp = (:subprotocol db) + nil (when (mysql? db) + (is (= '({:generated_key 1} {:generated_key 2}) r))) + "postgresql" (is (= 2 (count r))) + "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) + "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) + "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) + "hsqldb" (is (= '(1 1) r)) + "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} + {(keyword "last_insert_rowid()") 2}) r)) + "derby" (is (= (list {(keyword "1") nil} {(keyword "1") nil}) r)))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] :result-set-fn (comp :name first)))))) (deftest test-update-values (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-rows - :fruit - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])] - (is (= '(1 1 1 1) r))) - (sql/update-values - :fruit - ["name=?" "Banana"] - {:appearance "bruised" :cost 14}) - (is (= 4 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Apple" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "red"] (:name (first res))))) - (is (= "Banana" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] (:name (first res))))) - (is (= 14 (sql/with-query-results res ["SELECT * FROM fruit WHERE name = ?" "Banana"] (:cost (first res)))))))) + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + nil + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])] + (is (= '(1 1 1 1) r))) + (sql/update! db + :fruit + {:appearance "bruised" :cost 14} + ["name=?" "Banana"]) + (is (= 4 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] :result-set-fn (comp :name first)))) + (is (= "Banana" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] :result-set-fn (comp :name first)))) + (is (= 14 (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Banana"] :result-set-fn (comp :cost first)))))) + +(defn update-or-insert-values + [db table row where] + (sql/db-transaction + [t-conn db] + (let [result (sql/update! t-conn table row where)] + (if (zero? (first result)) + (sql/insert! t-conn table row) + result)))) (deftest test-update-or-insert-values (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (sql/update-or-insert-values - :fruit - ["name=?" "Pomegranate"] - {:name "Pomegranate" :appearance "fresh" :cost 585}) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= 585 (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] (:cost (first res))))) - (sql/update-or-insert-values - :fruit - ["name=?" "Pomegranate"] - {:name "Pomegranate" :appearance "ripe" :cost 565}) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= 565 (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] (:cost (first res))))) - (sql/update-or-insert-values - :fruit - ["name=?" "Apple"] - {:name "Apple" :appearance "green" :cost 74}) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (create-test-table :fruit db) + (update-or-insert-values db + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Pomegranate" :appearance "ripe" :cost 565} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Apple" :appearance "green" :cost 74} + ["name=?" "Apple"]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-partial-exception (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (throw (Exception. "deliberate exception"))) - (catch Exception _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))))) + (create-test-table :fruit db) + (try + (sql/db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (throw (Exception. "deliberate exception"))) + (catch Exception _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) (deftest test-sql-exception (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Apple" "strange" "whoops"])) - (catch IllegalArgumentException _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (create-test-table :fruit db) + (try + (sql/db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Apple" "strange" "whoops"])) + (catch IllegalArgumentException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-insert-values-exception (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (is (thrown? IllegalArgumentException - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"])))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (create-test-table :fruit db) + (is (thrown? IllegalArgumentException + (sql/db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"])))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-rollback (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (is (not (sql/is-rollback-only))) - (sql/set-rollback-only) - (is (sql/is-rollback-only)) - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange"]) - (is (= 3 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))) - (catch java.sql.SQLException _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (create-test-table :fruit db) + (try + (sql/db-transaction [t-conn db] + (is (not (sql/db-is-rollback-only t-conn))) + (sql/db-set-rollback-only! t-conn) + (is (sql/db-is-rollback-only t-conn)) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (catch java.sql.SQLException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-transactions-with-possible-generated-keys-result-set (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (sql/set-rollback-only) - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) + (create-test-table :fruit db) + (try + (sql/db-transaction [t-conn db] + (sql/db-set-rollback-only! t-conn) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-metadata (doseq [db (test-specs)] (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) - (let [metadata (sql/with-connection - db + (let [metadata (with-open [conn (sql/get-connection db)] (into [] (sql/result-set-seq - (-> (sql/connection) + (-> conn (.getMetaData) (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] (is (= [] metadata)))))) @@ -436,22 +440,19 @@ (deftest empty-query (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (is (= [] (sql/query db ["SELECT * FROM fruit"]))))) (deftest insert-one-row (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys)] (is (= [(returned-key db 1)] new-keys))))) (deftest insert-query (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys)] (is (= [(returned-key db 1)] new-keys)) @@ -459,8 +460,7 @@ (deftest insert-two-by-map-and-query (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] @@ -470,8 +470,7 @@ (deftest insert-two-by-map-and-query-as-arrays (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] @@ -483,8 +482,7 @@ (deftest insert-two-by-cols-and-query (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [1 1] update-counts)) @@ -493,8 +491,7 @@ (deftest insert-update-and-query (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} @@ -509,8 +506,7 @@ (deftest insert-delete-and-query (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) delete-result (sql/delete! db :fruit @@ -531,8 +527,7 @@ (deftest test-partial-exception-with-db (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (try (sql/db-transaction [t-db db] (sql/insert! t-db @@ -547,8 +542,7 @@ (deftest test-sql-exception-with-db (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (try (sql/db-transaction [t-db db] (sql/insert! t-db @@ -565,8 +559,7 @@ (deftest test-rollback-with-db (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (try (sql/db-transaction [t-db db] (is (not (sql/db-is-rollback-only t-db))) @@ -585,8 +578,7 @@ (deftest test-transactions-with-possible-generated-keys-result-set-with-db (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) (sql/db-transaction [t-db db] (sql/db-set-rollback-only! t-db) (sql/insert! t-db @@ -598,8 +590,7 @@ (deftest test-execute!-fails-with-multi-param-groups (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) ;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException (is (thrown? Exception (sql/execute! @@ -611,8 +602,7 @@ (deftest test-execute!-with-multi?-true-param-groups (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db)) + (create-test-table :fruit db) ;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException (let [counts (sql/execute! db @@ -633,18 +623,17 @@ (result-set-read-column [s _ _] ::FOO)) (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (sql/insert! db - :fruit - [:name :cost] - ["Crepes" 12] - ["Vegetables" -88] - ["Teenage Mutant Ninja Turtles" 0]) - (is (= {:name ::FOO, :cost -88} - (sql/with-query-results res ["SELECT name, cost FROM fruit WHERE name = ?" - "Vegetables"] - (first res)))))) + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost] + ["Crepes" 12] + ["Vegetables" -88] + ["Teenage Mutant Ninja Turtles" 0]) + (is (= {:name ::FOO, :cost -88} + (sql/query db ["SELECT name, cost FROM fruit WHERE name = ?" + "Vegetables"] + :result-set-fn first)))) ;; somewhat "undo" the first extension (extend-protocol sql/IResultSetReadColumn From 03ba5c6c514ec1fb3cc1a2998457d7daa294cc00 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 17:01:13 -0800 Subject: [PATCH 168/630] Update README/CHANGES to explain namespace changes coming in beta2 --- CHANGES.md | 1 + README.md | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1f8a78cb..3bf9a1b9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.0-beta2 * The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). +* The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. Changes in 0.3.0-beta1 diff --git a/README.md b/README.md index 37b5334c..cbafd207 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,22 @@ clojure.java.jdbc ======================================== -A low-level Clojure wrapper for JDBC-based access to databases. A minimal DSL is provided to generate basic SQL (in clojure.java.jdbc.sql) and basic DDL (in clojure.java.jdbc.ddl). For a more sophisticated DSL that is compatible with this library, consider: +A low-level Clojure wrapper for JDBC-based access to databases. + +For DSLs that are compatible with this library, consider: * [HoneySQL](https://github.com/jkk/honeysql) +* [SQLingvo](https://github.com/r0man/sqlingvo) * [Korma](http://sqlkorma.com) -Formerly known as clojure.contrib.sql. +Formerly known as `clojure.contrib.sql`. Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). +If you depend on the `clojure.java.jdbc.sql` or `clojure.java.jdbc.ddl` namespaces, which were introduced in 0.3.0-alpha1, you will need to switch to [java-jdbc/dsl](https://github.com/seancorfield/jsql) as those DSLs have been removed from this contrib library as of 0.3.0-beta2, to improve the focus. + +Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `clojure.java.jdbc.deprecated` as the old API was deprecated as part of the 0.3.0 release (alpha1 thru beta1). In order to clean up the documentation and improve the focus of `clojure.java.jdbc`, the old API has been moved in 0.3.0-beta1. + Releases and Dependency Information ======================================== From ac0cf2fb78ab8fd394745b65acf6b55b238cd8d1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 17:57:26 -0800 Subject: [PATCH 169/630] Some typos in README --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cbafd207..d16458ec 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,12 @@ Formerly known as `clojure.contrib.sql`. Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). +Important Changes from Earlier Versions +======================================== + If you depend on the `clojure.java.jdbc.sql` or `clojure.java.jdbc.ddl` namespaces, which were introduced in 0.3.0-alpha1, you will need to switch to [java-jdbc/dsl](https://github.com/seancorfield/jsql) as those DSLs have been removed from this contrib library as of 0.3.0-beta2, to improve the focus. -Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `clojure.java.jdbc.deprecated` as the old API was deprecated as part of the 0.3.0 release (alpha1 thru beta1). In order to clean up the documentation and improve the focus of `clojure.java.jdbc`, the old API has been moved in 0.3.0-beta1. +Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `clojure.java.jdbc.deprecated` as the old API was deprecated as part of the 0.3.0 release (alpha1 thru beta1). In order to clean up the documentation and improve the focus of `clojure.java.jdbc`, the old API has been moved in 0.3.0-beta2. Releases and Dependency Information ======================================== From 585fe830a63c99130794986e0d47ec7b1be78027 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 18:27:50 -0800 Subject: [PATCH 170/630] Prepare for 0.3.0-beta2 --- CHANGES.md | 2 +- README.md | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3bf9a1b9..2544da93 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.0-beta2 +Changes in 0.3.0-beta2 * The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). * The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. diff --git a/README.md b/README.md index d16458ec..56be3c71 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-beta1 +Latest stable release: 0.3.0-beta2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.0-beta1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-beta1"] +[org.clojure/java.jdbc "0.3.0-beta2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-beta1 + 0.3.0-beta2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -119,6 +119,11 @@ Developer Information Change Log ==================== +* Release 0.3.0-beta1 on 2013-11-24 + * BREAKING CHANGES! + * The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). + * The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. + * Release 0.3.0-beta1 on 2013-11-03 * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver From 1b23d64787335ffe46db407cf0279239a0f2d819 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 24 Nov 2013 20:29:13 -0600 Subject: [PATCH 171/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-beta2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 734e6734..56787481 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-beta2 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.0-beta2 From 6558b2e447bb502442d7d1ad3cbe6f58efe2c825 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 24 Nov 2013 20:29:13 -0600 Subject: [PATCH 172/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 56787481..734e6734 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-beta2 + 0.3.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.0-beta2 + HEAD From 2ba05b00f8691114a24014f7738298d00651e438 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Nov 2013 23:13:51 -0800 Subject: [PATCH 173/630] No longer need to exclude resultset-seq --- src/main/clojure/clojure/java/jdbc.clj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index abc2641e..76b9dd70 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -51,7 +51,6 @@ compatibility but it will be removed before a 1.0.0 release." } PreparedStatement ResultSet SQLException Statement Types] [java.util Hashtable Map Properties] [javax.sql DataSource]) - (:refer-clojure :exclude [resultset-seq]) (:require [clojure.string :as str])) (defn as-sql-name From be0ee6372de9f6851b70848cf7f615e184a882af Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 1 Dec 2013 22:59:42 -0800 Subject: [PATCH 174/630] Fix JDBC-77 by adding ISQLValue protocol for parameters in SQL statements. --- CHANGES.md | 4 ++++ src/main/clojure/clojure/java/jdbc.clj | 16 +++++++++++++++- src/test/clojure/clojure/java/test_jdbc.clj | 20 ++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 2544da93..c0a1b19f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.0-beta3 (or rc1) + +* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). + Changes in 0.3.0-beta2 * The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 76b9dd70..1c84c91f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -269,6 +269,20 @@ compatibility but it will be removed before a 1.0.0 release." } (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) +(defprotocol ISQLValue + "Protocol for creating SQL values from Clojure values. Default + implementations (for Object and nil) just return the argument, + but it can be extended to provide custom behavior to support + exotic types supported by different databases." + (sql-value [val] "Convert a Clojure value into a SQL value.")) + +(extend-protocol ISQLValue + Object + (sql-value [v] v) + + nil + (sql-value [_] nil)) + (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default implementations (for Object and nil) return the argument, but it can @@ -384,7 +398,7 @@ compatibility but it will be removed before a 1.0.0 release." } "Add the parameters to the given statement." [^PreparedStatement stmt params] (dorun (map-indexed (fn [ix value] - (.setObject stmt (inc ix) value)) + (.setObject stmt (inc ix) (sql-value value))) params))) (defn print-sql-exception diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 09d10862..b2dba6b2 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -639,3 +639,23 @@ (extend-protocol sql/IResultSetReadColumn String (result-set-read-column [s _ _] s))) + +(deftest test-sql-value + (extend-protocol sql/ISQLValue + clojure.lang.Keyword + (sql-value [_] "KW")) + + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost] + [:test 12]) + (is (= {:name "KW", :cost 12} + (sql/query db ["SELECT name, cost FROM fruit"] + :result-set-fn first)))) + + ;; somewhat "undo" the first extension + (extend-protocol sql/ISQLValue + clojure.lang.Keyword + (sql-value [k] k))) From d8f700a311ae37c2eca2bde17bb68ea022d3ab45 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 1 Dec 2013 23:22:43 -0800 Subject: [PATCH 175/630] Fix JDBC-74 by adding :user as an alias for :username on DataSource connections. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c0a1b19f..43e189a1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.0-beta3 (or rc1) * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). +* Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). Changes in 0.3.0-beta2 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1c84c91f..5dd5d522 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -185,6 +185,8 @@ compatibility but it will be removed before a 1.0.0 release." } DataSource: :datasource (required) a javax.sql.DataSource :username (optional) a String + :user (optional) a String - an alternate alias for :username + (added after 0.3.0-beta2 for consistency JDBC-74) :password (optional) a String, required if :username is supplied JNDI: @@ -206,7 +208,7 @@ compatibility but it will be removed before a 1.0.0 release." } factory connection-uri classname subprotocol subname - datasource username password + datasource username password user name environment] :as db-spec}] (cond @@ -232,8 +234,9 @@ compatibility but it will be removed before a 1.0.0 release." } (clojure.lang.RT/loadClassForName classname) (DriverManager/getConnection url (as-properties etc))) - (and datasource username password) - (.getConnection ^DataSource datasource ^String username ^String password) + (or (and datasource username password) + (and datasource user password)) + (.getConnection ^DataSource datasource ^String (or username user) ^String password) datasource (.getConnection ^DataSource datasource) From 395a22481dabbfb63516f235e5bb6792273c0083 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 2 Dec 2013 14:37:30 -0800 Subject: [PATCH 176/630] Ignore lein repl history --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 3a1aabdc..5a1aaeb2 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ settings.xml /clojure_test_sqlite /.lein-failures /.nrepl-port +/.lein-repl-history From 5c0a7fc6b9c76658159b7bf7615d732eb03a6b9b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 2 Dec 2013 14:37:52 -0800 Subject: [PATCH 177/630] Remove reference to clojure.java.jdbc.sql from README for JDBC-78 --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 56be3c71..7dc3eb8c 100644 --- a/README.md +++ b/README.md @@ -67,8 +67,7 @@ has to be downloaded manually and placed in a Maven repository accessible to you Example Usage ======================================== ```clojure -(require '[clojure.java.jdbc :as j] - '[clojure.java.jdbc.sql :as s]) +(require '[clojure.java.jdbc :as j]) (def mysql-db {:subprotocol "mysql" :subname "//127.0.0.1:3306/clojure_test" @@ -81,7 +80,7 @@ Example Usage ;; ({:generated_key 1} {:generated_key 2}) (j/query mysql-db - (s/select * :fruit (s/where {:appearance "rosy"})) + ["select * from fruit where appearance = ?" "rosy"] :row-fn :cost) ;; (24) ``` From 1b86d85827a938e41a6d436912962e67aea56550 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 2 Dec 2013 18:36:09 -0800 Subject: [PATCH 178/630] Fix a reflection warning in execute-batch --- src/main/clojure/clojure/java/jdbc/deprecated.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/deprecated.clj b/src/main/clojure/clojure/java/jdbc/deprecated.clj index c576dbe7..cbf0077d 100644 --- a/src/main/clojure/clojure/java/jdbc/deprecated.clj +++ b/src/main/clojure/clojure/java/jdbc/deprecated.clj @@ -419,7 +419,7 @@ generated keys are returned (as a map)." } Specifically, Oracle returns that and we must call getUpdateCount() to get the actual number of rows affected. In general, operations return an array of update counts, so this may not be a general solution for Oracle..." - [stmt] + [^Statement stmt] (let [result (.executeBatch stmt)] (if (and (= 1 (count result)) (= -2 (first result))) (list (.getUpdateCount stmt)) From 70021b13df8e5d81154cb3a90cf671101f1e2cbc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 3 Dec 2013 09:35:40 -0800 Subject: [PATCH 179/630] Fix docstring in insert-sql --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5dd5d522..8a2241ad 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -800,7 +800,7 @@ compatibility but it will be removed before a 1.0.0 release." } (vals row)))) (defn insert-sql - "Given a table name and either column names and values or maps representing rows, retun + "Given a table name and either column names and values or maps representing rows, return a vector of the SQL for that insert operation followed by its parameters. An optional entities spec (default 'as-is') specifies how to transform column names." [table & clauses] From 9ea7d012c5df2d31e2fd8823aa0eb023ca17078a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 3 Dec 2013 09:36:04 -0800 Subject: [PATCH 180/630] Fix docstring in create-test-table --- src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index b2dba6b2..6adb3920 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -134,7 +134,7 @@ (= "postgresql" (:subprotocol db)))) (defmulti create-test-table - "Create a standard test table. Must be inside with-connection. + "Create a standard test table. Uses db-do-commands. For MySQL, ensure table uses an engine that supports transactions!" (fn [table db] (cond From e91aed39c8c6ba550b27e400f521602ad96356f2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 16:56:53 -0800 Subject: [PATCH 181/630] Fix JDBC-79 by adding with-db-connection --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 8 ++++++++ src/test/clojure/clojure/java/test_jdbc.clj | 13 +++++++++++++ 3 files changed, 22 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 43e189a1..c34875f8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-beta3 (or rc1) +* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). * Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8a2241ad..79cafb28 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -526,6 +526,14 @@ compatibility but it will be removed before a 1.0.0 release." } `(db-transaction* ~(second binding) (^{:once true} fn* [~(first binding)] ~@body))) +(defmacro with-db-connection + "Evaluates body in the context of an active connection to the database." + [binding & body] + `(let [db-spec# ~(second binding)] + (with-open [con# (get-connection db-spec#)] + (let [~(first binding) (add-connection db-spec# con#)] + ~@body)))) + (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 6adb3920..a8823189 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -516,6 +516,19 @@ (is (= [1] delete-result)) (is (= [] rows))))) +(deftest insert-delete-and-query-in-connection + (doseq [db (test-specs)] + (sql/with-db-connection [con-db db] + (create-test-table :fruit con-db) + (let [new-keys (sql/insert! con-db :fruit {:name "Apple"}) + new-keys (if (postgres? con-db) (map :id new-keys) new-keys) + delete-result (sql/delete! con-db :fruit + ["id = ?" (generated-key con-db 1)]) + rows (sql/query con-db ["SELECT * FROM fruit"])] + (is (= [(returned-key con-db 1)] new-keys)) + (is (= [1] delete-result)) + (is (= [] rows)))))) + (deftest illegal-insert-arguments (doseq [db (test-specs)] (is (thrown? IllegalArgumentException (sql/insert! db))) From f580aed16dc7bda9bac0aaa003a7ed4627daa72b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 17:00:39 -0800 Subject: [PATCH 182/630] Remove unused *db* variable from main namespace. --- src/main/clojure/clojure/java/jdbc.clj | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 79cafb28..3137f97a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -121,8 +121,6 @@ compatibility but it will be removed before a 1.0.0 release." } (add-connection [_ connection] {:connection connection :level 0 :legacy true}) (get-level [_] 0)) -(def ^{:private true :dynamic true} *db* (add-connection nil nil)) - (def ^{:private true :doc "Map of classnames to subprotocols"} classnames {"postgresql" "org.postgresql.Driver" "mysql" "com.mysql.jdbc.Driver" From eadef75b0e38e4513cf5cc623e80221aad6c5ad4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 17:55:52 -0800 Subject: [PATCH 183/630] Fix JDBC-80 by adding with-db-metadata and metadata-result and improving tests to exercise them. --- CHANGES.md | 3 ++- src/main/clojure/clojure/java/jdbc.clj | 23 ++++++++++++++-- src/test/clojure/clojure/java/test_jdbc.clj | 30 ++++++++++++++++----- 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c34875f8..c75f7e7b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ -Changes coming in 0.3.0-beta3 (or rc1) +Changes coming in 0.3.0-rc1 +* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). * Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 3137f97a..7bc11b3f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -525,13 +525,32 @@ compatibility but it will be removed before a 1.0.0 release." } (^{:once true} fn* [~(first binding)] ~@body))) (defmacro with-db-connection - "Evaluates body in the context of an active connection to the database." + "Evaluates body in the context of an active connection to the database. + (with-db-connection [con-db db-spec] ... con-db ...)" [binding & body] `(let [db-spec# ~(second binding)] - (with-open [con# (get-connection db-spec#)] + (with-open [^java.sql.Connection con# (get-connection db-spec#)] (let [~(first binding) (add-connection db-spec# con#)] ~@body)))) +(defmacro with-db-metadata + "Evaluates body in the context of an active connection with metadata bound + to the specified name. See also metadata-result below. + (with-db-metadata [md db-spec] ... md ..." + [binding & body] + `(with-open [^java.sql.Connection con# (get-connection ~(second binding))] + (let [~(first binding) (.getMetaData con#)] + ~@body))) + +(defn metadata-result + "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, + else return it as-is. This makes working with metadata easier." + [rs-or-value & {:keys [identifiers as-arrays?] + :or {identifiers str/lower-case}}] + (if (instance? java.sql.ResultSet rs-or-value) + (result-set-seq rs-or-value :identifiers identifiers :as-arrays? as-arrays?) + rs-or-value)) + (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index a8823189..60116409 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -397,16 +397,34 @@ (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) -(deftest test-metadata - (doseq [db (test-specs)] - (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) - (let [metadata (with-open [conn (sql/get-connection db)] +(deftest test-raw-metadata + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [table-info (with-open [conn (sql/get-connection db)] (into [] (sql/result-set-seq (-> conn (.getMetaData) - (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] - (is (= [] metadata)))))) + (.getTables nil nil nil + (into-array ["TABLE" "VIEW"]))))))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case)))))) + +(deftest test-metadata + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-metadata [metadata db] + (let [table-info (sql/metadata-result (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case))))))) (defn- returned-key [db k] (condp = (:subprotocol db) From a62e12ad742e57aed410d09289caec94e5fbdbc7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 18:10:57 -0800 Subject: [PATCH 184/630] Fix JDBC-81 by adding with-db-transaction and deprecating db-transaction (which prints a message to console if you use it). --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 30 ++-- src/test/clojure/clojure/java/test_jdbc.clj | 174 ++++++++++---------- 3 files changed, 108 insertions(+), 97 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c75f7e7b..6f6f60a4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-rc1 +* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7bc11b3f..0bd87aa1 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -515,7 +515,7 @@ compatibility but it will be removed before a 1.0.0 release." } (catch Exception e (throw-non-rte e))))) -(defmacro db-transaction +(defmacro with-db-transaction "Evaluates body in the context of a transaction on the specified database connection. The binding provides the database connection for the transaction and the name to which that is bound for evaluation of the body. @@ -563,8 +563,8 @@ compatibility but it will be removed before a 1.0.0 release." } (doseq [^String cmd commands] (.addBatch stmt cmd)) (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) (try (execute-batch stmt) (catch Exception e @@ -597,8 +597,8 @@ compatibility but it will be removed before a 1.0.0 release." } ;; assume generated keys is unsupported and return counts instead: counts))))] (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (exec-and-return-keys)) + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (exec-and-return-keys)) (try (exec-and-return-keys) (catch Exception e @@ -618,8 +618,8 @@ compatibility but it will be removed before a 1.0.0 release." } (with-open [^PreparedStatement stmt (prepare-statement con sql)] (if (empty? param-groups) (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (vector (.executeUpdate stmt))) (try (vector (.executeUpdate stmt)) (catch Exception e @@ -629,8 +629,8 @@ compatibility but it will be removed before a 1.0.0 release." } ((or (:set-parameters db) set-parameters) stmt param-group) (.addBatch stmt)) (if transaction? - (db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) (try (execute-batch stmt) (catch Exception e @@ -770,7 +770,7 @@ compatibility but it will be removed before a 1.0.0 release." } (if (string? (first stmts)) (apply db-do-prepared db transaction? (first stmts) (rest stmts)) (if transaction? - (db-transaction [t-db db] (multi-insert-helper t-db stmts)) + (with-db-transaction [t-db db] (multi-insert-helper t-db stmts)) (multi-insert-helper db stmts)))) (defn- extract-transaction? @@ -925,3 +925,13 @@ compatibility but it will be removed before a 1.0.0 release." } "Given a table name, return the DDL string for dropping that table." [name & {:keys [entities] :or {entities identity}}] (format "DROP TABLE %s" (as-sql-name entities name))) + +(defmacro + ^{:doc "Original name for with-db-transaction. Use that instead." + :deprecated "0.3.0"} + db-transaction + [binding & body] + (println "DEPRECATED: Use with-db-transaction instead of db-transaction.") + `(db-transaction* ~(second binding) + (^{:once true} fn* [~(first binding)] ~@body))) + diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 60116409..fcc55ed6 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -107,14 +107,14 @@ "Attempt to drop any test tables before we start a test." [t] (doseq [db (test-specs)] - (sql/db-transaction - [t-conn db] - (doseq [table [:fruit :fruit2 :veggies :veggies2]] - (try - (sql/db-do-commands t-conn (sql/drop-table-ddl table)) - (catch Exception _ - ;; ignore - ))))) + (sql/with-db-transaction + [t-conn db] + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/db-do-commands t-conn (sql/drop-table-ddl table)) + (catch Exception _ + ;; ignore + ))))) (t)) (use-fixtures @@ -296,12 +296,12 @@ (defn update-or-insert-values [db table row where] - (sql/db-transaction - [t-conn db] - (let [result (sql/update! t-conn table row where)] - (if (zero? (first result)) - (sql/insert! t-conn table row) - result)))) + (sql/with-db-transaction + [t-conn db] + (let [result (sql/update! t-conn table row where)] + (if (zero? (first result)) + (sql/insert! t-conn table row) + result)))) (deftest test-update-or-insert-values (doseq [db (test-specs)] @@ -328,14 +328,14 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-conn db] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) - (throw (Exception. "deliberate exception"))) + (sql/with-db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (throw (Exception. "deliberate exception"))) (catch Exception _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) @@ -343,11 +343,11 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-conn db] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Apple" "strange" "whoops"])) + (sql/with-db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Apple" "strange" "whoops"])) (catch IllegalArgumentException _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) @@ -356,30 +356,30 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (is (thrown? IllegalArgumentException - (sql/db-transaction [t-conn db] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"])))) + (sql/with-db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"])))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-rollback (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-conn db] - (is (not (sql/db-is-rollback-only t-conn))) - (sql/db-set-rollback-only! t-conn) - (is (sql/db-is-rollback-only t-conn)) - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange"]) - (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (sql/with-db-transaction [t-conn db] + (is (not (sql/db-is-rollback-only t-conn))) + (sql/db-set-rollback-only! t-conn) + (is (sql/db-is-rollback-only t-conn)) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) (catch java.sql.SQLException _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) @@ -388,13 +388,13 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-conn db] - (sql/db-set-rollback-only! t-conn) - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))))) + (sql/with-db-transaction [t-conn db] + (sql/db-set-rollback-only! t-conn) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-raw-metadata @@ -560,14 +560,14 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-db db] - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - (is (= 2 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count))) - (throw (Exception. "deliberate exception"))) + (sql/with-db-transaction [t-db db] + (sql/insert! t-db + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count))) + (throw (Exception. "deliberate exception"))) (catch Exception _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) @@ -575,15 +575,15 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-db db] - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - ;; sqlite does not throw exception for too many items - (throw (java.sql.SQLException.))) + (sql/with-db-transaction [t-db db] + (sql/insert! t-db + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + ;; sqlite does not throw exception for too many items + (throw (java.sql.SQLException.))) (catch Exception _ ;; insert! throws the exception, not JDBC (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) @@ -592,17 +592,17 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/db-transaction [t-db db] - (is (not (sql/db-is-rollback-only t-db))) - (sql/db-set-rollback-only! t-db) - (is (sql/db-is-rollback-only t-db)) - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - (is (= 3 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) + (sql/with-db-transaction [t-db db] + (is (not (sql/db-is-rollback-only t-db))) + (sql/db-set-rollback-only! t-db) + (is (sql/db-is-rollback-only t-db)) + (sql/insert! t-db + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]) + (is (= 3 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) (catch Exception _ ;; insert! throws the exception, not JDBC (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) @@ -610,13 +610,13 @@ (deftest test-transactions-with-possible-generated-keys-result-set-with-db (doseq [db (test-specs)] (create-test-table :fruit db) - (sql/db-transaction [t-db db] - (sql/db-set-rollback-only! t-db) - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) + (sql/with-db-transaction [t-db db] + (sql/db-set-rollback-only! t-db) + (sql/insert! t-db + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-execute!-fails-with-multi-param-groups From e2f77ee78babb6e1a9bec1ad377f890bda0a9460 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 18:34:48 -0800 Subject: [PATCH 185/630] Minor formatting cleanup --- src/main/clojure/clojure/java/jdbc.clj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 0bd87aa1..13980ff9 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -18,8 +18,7 @@ ;; Migrated from clojure.contrib.sql 17 April 2011 (ns - ^{ - :author "Stephen C. Gilardi, Sean Corfield", + ^{:author "Stephen C. Gilardi, Sean Corfield", :doc "A Clojure interface to SQL databases via JDBC clojure.java.jdbc provides a simple abstraction for CRUD (create, read, From b3ca504266f6f9c02680bf7f7916bf9211841c7e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 18:35:52 -0800 Subject: [PATCH 186/630] Test cleanup. Remove a few redundant tests now the deprecated stuff is elsewhere. --- src/test/clojure/clojure/java/test_jdbc.clj | 78 ++------------------- 1 file changed, 7 insertions(+), 71 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index fcc55ed6..83c8d146 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -387,14 +387,13 @@ (deftest test-transactions-with-possible-generated-keys-result-set (doseq [db (test-specs)] (create-test-table :fruit db) - (try - (sql/with-db-transaction [t-conn db] - (sql/db-set-rollback-only! t-conn) - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))))) + (sql/with-db-transaction [t-conn db] + (sql/db-set-rollback-only! t-conn) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-raw-metadata @@ -556,69 +555,6 @@ (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) (is (thrown? IllegalArgumentException (sql/insert! db [:name] :entities identity))))) -(deftest test-partial-exception-with-db - (doseq [db (test-specs)] - (create-test-table :fruit db) - (try - (sql/with-db-transaction [t-db db] - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - (is (= 2 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count))) - (throw (Exception. "deliberate exception"))) - (catch Exception _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) - -(deftest test-sql-exception-with-db - (doseq [db (test-specs)] - (create-test-table :fruit db) - (try - (sql/with-db-transaction [t-db db] - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - ;; sqlite does not throw exception for too many items - (throw (java.sql.SQLException.))) - (catch Exception _ ;; insert! throws the exception, not JDBC - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - -(deftest test-rollback-with-db - (doseq [db (test-specs)] - (create-test-table :fruit db) - (try - (sql/with-db-transaction [t-db db] - (is (not (sql/db-is-rollback-only t-db))) - (sql/db-set-rollback-only! t-db) - (is (sql/db-is-rollback-only t-db)) - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - (is (= 3 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) - (catch Exception _ ;; insert! throws the exception, not JDBC - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - -(deftest test-transactions-with-possible-generated-keys-result-set-with-db - (doseq [db (test-specs)] - (create-test-table :fruit db) - (sql/with-db-transaction [t-db db] - (sql/db-set-rollback-only! t-db) - (sql/insert! t-db - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/query t-db ["SELECT * FROM fruit"] :result-set-fn count)))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (deftest test-execute!-fails-with-multi-param-groups (doseq [db (test-specs)] (create-test-table :fruit db) From eb4f6dfb9de2d18564dbfd09cdf275c50c44ead1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 18:48:03 -0800 Subject: [PATCH 187/630] Fix JDBC-75 by adding support for :isolation on with-db-transaction --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 24 ++++- src/test/clojure/clojure/java/test_jdbc.clj | 107 +++++++++++++++++++- 3 files changed, 123 insertions(+), 9 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 6f6f60a4..a6a40267 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,7 @@ Changes coming in 0.3.0-rc1 * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). +* Add support for :isolation in with-db-transaction [JDBC-75](http://dev.clojure.org/jira/browse/JDBC-75). * Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). Changes in 0.3.0-beta2 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 13980ff9..f3c6edcf 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -480,6 +480,14 @@ compatibility but it will be removed before a 1.0.0 release." } [db] (deref (:rollback db))) +(def ^{:private true :doc "Transaction isolation levels."} + isolation-levels + {:none java.sql.Connection/TRANSACTION_NONE + :read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED + :read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED + :repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ + :serializable java.sql.Connection/TRANSACTION_SERIALIZABLE}) + (defn db-transaction* "Evaluates func as a transaction on the open database connection. Any nested transactions are absorbed into the outermost transaction. By @@ -488,12 +496,15 @@ compatibility but it will be removed before a 1.0.0 release." } exception. If rollback is set within scope of the outermost transaction, the entire transaction will be rolled back rather than committed when complete." - [db func] + [db func & {:keys [isolation]}] (if (zero? (get-level db)) (if-let [^java.sql.Connection con (db-find-connection db)] (let [nested-db (inc-level db) - auto-commit (.getAutoCommit con)] + auto-commit (.getAutoCommit con) + old-isolation (.getTransactionIsolation con)] (io! + (when isolation + (.setTransactionIsolation con (isolation isolation-levels))) (.setAutoCommit con false) (try (let [result (func nested-db)] @@ -506,9 +517,11 @@ compatibility but it will be removed before a 1.0.0 release." } (throw-non-rte t)) (finally (db-unset-rollback-only! nested-db) - (.setAutoCommit con auto-commit))))) + (.setAutoCommit con auto-commit) + (when isolation + (.setTransactionIsolation con old-isolation)))))) (with-open [^java.sql.Connection con (get-connection db)] - (db-transaction* (add-connection db con) func))) + (db-transaction* (add-connection db con) func :isolation isolation))) (try (func (inc-level db)) (catch Exception e @@ -521,7 +534,8 @@ compatibility but it will be removed before a 1.0.0 release." } See db-transaction* for more details." [binding & body] `(db-transaction* ~(second binding) - (^{:once true} fn* [~(first binding)] ~@body))) + (^{:once true} fn* [~(first binding)] ~@body) + ~@(rest (rest binding)))) (defmacro with-db-connection "Evaluates body in the context of an active connection to the database. diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 83c8d146..abd874a4 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -107,8 +107,7 @@ "Attempt to drop any test tables before we start a test." [t] (doseq [db (test-specs)] - (sql/with-db-transaction - [t-conn db] + (sql/with-db-transaction [t-conn db] (doseq [table [:fruit :fruit2 :veggies :veggies2]] (try (sql/db-do-commands t-conn (sql/drop-table-ddl table)) @@ -296,8 +295,15 @@ (defn update-or-insert-values [db table row where] - (sql/with-db-transaction - [t-conn db] + (sql/with-db-transaction [t-conn db] + (let [result (sql/update! t-conn table row where)] + (if (zero? (first result)) + (sql/insert! t-conn table row) + result)))) + +(defn update-or-insert-values-with-isolation + [db table row where] + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] (let [result (sql/update! t-conn table row where)] (if (zero? (first result)) (sql/insert! t-conn table row) @@ -324,6 +330,27 @@ ["name=?" "Apple"]) (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-update-or-insert-values + (doseq [db (test-specs)] + (create-test-table :fruit db) + (update-or-insert-values-with-isolation db + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Pomegranate" :appearance "ripe" :cost 565} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Apple" :appearance "green" :cost 74} + ["name=?" "Apple"]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (deftest test-partial-exception (doseq [db (test-specs)] (create-test-table :fruit db) @@ -339,6 +366,21 @@ (catch Exception _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) +(deftest test-partial-exception-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db :isolation :serializable] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (throw (Exception. "deliberate exception"))) + (catch Exception _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) + (deftest test-sql-exception (doseq [db (test-specs)] (create-test-table :fruit db) @@ -352,6 +394,19 @@ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-sql-exception-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Apple" "strange" "whoops"])) + (catch IllegalArgumentException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (deftest test-insert-values-exception (doseq [db (test-specs)] (create-test-table :fruit db) @@ -365,6 +420,19 @@ ["Apple" "strange" "whoops"])))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-insert-values-exception-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (thrown? IllegalArgumentException + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"])))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (deftest test-rollback (doseq [db (test-specs)] (create-test-table :fruit db) @@ -384,6 +452,25 @@ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-rollback-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (is (not (sql/db-is-rollback-only t-conn))) + (sql/db-set-rollback-only! t-conn) + (is (sql/db-is-rollback-only t-conn)) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (catch java.sql.SQLException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (deftest test-transactions-with-possible-generated-keys-result-set (doseq [db (test-specs)] (create-test-table :fruit db) @@ -396,6 +483,18 @@ (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-transactions-with-possible-generated-keys-result-set-and-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/db-set-rollback-only! t-conn) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (deftest test-raw-metadata (doseq [db (test-specs)] (create-test-table :fruit db) From c5d25c7aa0f093935db2044a1b7580551bfa51c9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 19:06:09 -0800 Subject: [PATCH 188/630] Prep for 0.3.0-rc1 --- CHANGES.md | 2 +- README.md | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index a6a40267..8feb1dab 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.0-rc1 +Changes in 0.3.0-rc1 * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). diff --git a/README.md b/README.md index 7dc3eb8c..ccb4ae11 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,15 @@ Developer Information Change Log ==================== -* Release 0.3.0-beta1 on 2013-11-24 +* Release 0.3.0-rc1 on 2013-12-12 + * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). + * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). + * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). + * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). + * Add support for :isolation in with-db-transaction [JDBC-75](http://dev.clojure.org/jira/browse/JDBC-75). + * Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). + +* Release 0.3.0-beta2 on 2013-11-24 * BREAKING CHANGES! * The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). * The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. From 594cffe4afe9b839e8c8b699cc71dbd8fae28ab9 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 12 Dec 2013 21:07:16 -0600 Subject: [PATCH 189/630] [maven-release-plugin] prepare release java.jdbc-0.3.0-rc1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 734e6734..f0aa9513 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0-rc1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.0-rc1 From e081a67dee7765c470f211c019193e5c62ecf201 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 12 Dec 2013 21:07:16 -0600 Subject: [PATCH 190/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index f0aa9513..734e6734 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-rc1 + 0.3.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.0-rc1 + HEAD From 419d4cdbd8b739e8240ff576d73af2042e6150ad Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 19:12:03 -0800 Subject: [PATCH 191/630] Update README with latest stable version now it has been released to Maven --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ccb4ae11..83e8305e 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-beta2 +Latest stable release: 0.3.0-rc1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.0-beta2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-beta2"] +[org.clojure/java.jdbc "0.3.0-rc1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-beta2 + 0.3.0-rc1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, From b915c358a52b26494f8beb28d1ba81fcdb1f0122 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 Dec 2013 23:06:55 -0800 Subject: [PATCH 192/630] Fix JDBC-82 by renaming unused arguments in protocol to allow Android compilation --- CHANGES.md | 4 ++++ src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 8feb1dab..3cde2f91 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.0-rc2 (or gold) + +* Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). + Changes in 0.3.0-rc1 * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f3c6edcf..e8c4e28d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -292,10 +292,10 @@ compatibility but it will be removed before a 1.0.0 release." } (extend-protocol IResultSetReadColumn Object - (result-set-read-column [x _ _] x) + (result-set-read-column [x _2 _3] x) nil - (result-set-read-column [_ _ _] nil)) + (result-set-read-column [_1 _2 _3] nil)) (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the From aef15667db7efd3a1b9654004b5b356b62a0dcbc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 16 Dec 2013 13:12:27 -0800 Subject: [PATCH 193/630] Fix JDBC-84 by ensuring canonical Boolean true/false when reading from the DB --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3cde2f91..9a740635 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.0-rc2 (or gold) +* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). Changes in 0.3.0-rc1 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e8c4e28d..64d18261 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -285,8 +285,9 @@ compatibility but it will be removed before a 1.0.0 release." } (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default - implementations (for Object and nil) return the argument, but it can - be extended to provide custom behavior for special types." + implementations (for Object and nil) return the argument, and the + Boolean implementation ensures a canonicalized true/false value, + but it can be extended to provide custom behavior for special types." (result-set-read-column [val rsmeta idx] "Function for transforming values after reading them from the database")) @@ -294,6 +295,9 @@ compatibility but it will be removed before a 1.0.0 release." } Object (result-set-read-column [x _2 _3] x) + Boolean + (result-set-read-column [x _2 _3] (if (= true x) true false)) + nil (result-set-read-column [_1 _2 _3] nil)) From 85bf3bdf69fbd27a95b954f1c85615a9b672a00a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 16 Dec 2013 13:16:55 -0800 Subject: [PATCH 194/630] Fix JDBC-83 by ensuring unique test names --- CHANGES.md | 1 + src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 9a740635..1aa24a92 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.0-rc2 (or gold) * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). +* Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83). * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). Changes in 0.3.0-rc1 diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index abd874a4..9ed83957 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -330,7 +330,7 @@ ["name=?" "Apple"]) (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) -(deftest test-update-or-insert-values +(deftest test-update-or-insert-values-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) (update-or-insert-values-with-isolation db From 6b1a9b24417e7279b380d30a4c530cdb296c8244 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 16 Dec 2013 17:03:38 -0800 Subject: [PATCH 195/630] Add test to expose bug in JDBC-65 --- src/test/clojure/clojure/java/test_jdbc.clj | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9ed83957..5a68ed30 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -272,6 +272,18 @@ (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] :result-set-fn (comp :name first)))))) +(deftest test-insert-via-execute + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )") + "Apple" "Green" 75]) + (sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( 'Pear', 'Yellow', 99 )")]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + :result-set-fn (comp :name first)))))) + (deftest test-update-values (doseq [db (test-specs)] (create-test-table :fruit db) From 79ae77870f96705fc766668b08e135f997abe184 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 16 Dec 2013 18:18:16 -0800 Subject: [PATCH 196/630] Fix JDBC-65 by correctly handling empty param group sequence in execute! --- src/main/clojure/clojure/java/jdbc.clj | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 64d18261..46bf4b0a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -728,11 +728,14 @@ compatibility but it will be removed before a 1.0.0 release." } whether to run the operation in a transaction or not (default true)." [db sql-params & {:keys [transaction? multi?] :or {transaction? true multi? false}}] - (let [execute-helper + (let [param-groups (rest sql-params) + execute-helper (^{:once true} fn* [db] (if multi? - (apply db-do-prepared db transaction? (first sql-params) (rest sql-params)) - (db-do-prepared db transaction? (first sql-params) (rest sql-params))))] + (apply db-do-prepared db transaction? (first sql-params) param-groups) + (if (seq param-groups) + (db-do-prepared db transaction? (first sql-params) param-groups) + (db-do-prepared db transaction? (first sql-params)))))] (if-let [con (db-find-connection db)] (execute-helper db) (with-open [^java.sql.Connection con (get-connection db)] From 80b0101ce7559b00717f0b80383672205c8a2598 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 16 Dec 2013 18:23:34 -0800 Subject: [PATCH 197/630] Prepare for gold 0.3.0 release. --- CHANGES.md | 3 ++- README.md | 14 ++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1aa24a92..2dc73f89 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,8 +1,9 @@ -Changes coming in 0.3.0-rc2 (or gold) +Changes in 0.3.0 * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). * Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83). * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). +* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://dev.clojure.org/jira/browse/JDBC-65). Changes in 0.3.0-rc1 diff --git a/README.md b/README.md index 83e8305e..d2ed5b0e 100644 --- a/README.md +++ b/README.md @@ -18,12 +18,12 @@ Important Changes from Earlier Versions If you depend on the `clojure.java.jdbc.sql` or `clojure.java.jdbc.ddl` namespaces, which were introduced in 0.3.0-alpha1, you will need to switch to [java-jdbc/dsl](https://github.com/seancorfield/jsql) as those DSLs have been removed from this contrib library as of 0.3.0-beta2, to improve the focus. -Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `clojure.java.jdbc.deprecated` as the old API was deprecated as part of the 0.3.0 release (alpha1 thru beta1). In order to clean up the documentation and improve the focus of `clojure.java.jdbc`, the old API has been moved in 0.3.0-beta2. +Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `clojure.java.jdbc.deprecated` as the old API was deprecated as part of the 0.3.0 release (alpha1 thru beta1). In order to clean up the documentation and improve the focus of `clojure.java.jdbc`, the old API was moved in 0.3.0-beta2. Releases and Dependency Information ======================================== -Latest stable release: 0.3.0-rc1 +Latest stable release: 0.3.0 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.0-rc1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0-rc1"] +[org.clojure/java.jdbc "0.3.0"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0-rc1 + 0.3.0 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,6 +118,12 @@ Developer Information Change Log ==================== +* Release 0.3.0 on 2013-12-16 + * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). + * Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83). + * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). + * Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://dev.clojure.org/jira/browse/JDBC-65). + * Release 0.3.0-rc1 on 2013-12-12 * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). From cbbc7d214b13bc7ef1c14458aef9eecd14285dbe Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 16 Dec 2013 20:31:36 -0600 Subject: [PATCH 198/630] [maven-release-plugin] prepare release java.jdbc-0.3.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 734e6734..b1e46a8a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0-SNAPSHOT + 0.3.0 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.0 From b9723e4ba88ef213c2705fffd16b590f7afe2c1e Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 16 Dec 2013 20:31:37 -0600 Subject: [PATCH 199/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b1e46a8a..d4100a79 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.0 + 0.3.1-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.0 + HEAD From cd0d5f581422872941f02bff403f83817c17de4d Mon Sep 17 00:00:00 2001 From: Andy Fingerhut Date: Mon, 23 Dec 2013 16:17:17 -0800 Subject: [PATCH 200/630] JDBC-85: Correct two unit tests so that they test something Signed-off-by: Sean Corfield --- src/test/clojure/clojure/java/test_deprecated.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/clojure/clojure/java/test_deprecated.clj b/src/test/clojure/clojure/java/test_deprecated.clj index 3d0e5157..f980921c 100644 --- a/src/test/clojure/clojure/java/test_deprecated.clj +++ b/src/test/clojure/clojure/java/test_deprecated.clj @@ -403,6 +403,6 @@ (is (= "`kw`" (sql/as-identifier :kw))) (is (= "`k`.`w`" (sql/as-identifier :k.w))) (is (= :K-W (sql/as-keyword "K_W"))) - (is (= :K_W) (sql/as-keyword :K_W)) - (is (= :k.w) (sql/as-keyword :k.w)))) + (is (= :K_W (sql/as-keyword :K_W))) + (is (= :k.w (sql/as-keyword :k.w))))) From 6ec9f29a335313e60269950242424b8938abadc3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 23 Dec 2013 16:39:05 -0800 Subject: [PATCH 201/630] Log changes from JDBC-85 fix --- CHANGES.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 2dc73f89..90bf9bc4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,6 @@ +Changes coming in 0.3.1 + +* Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). Changes in 0.3.0 * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). From ece48924bc56b6d248dbca943ef1ce1f1f5df0d7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 29 Dec 2013 14:28:49 -0800 Subject: [PATCH 202/630] Made create-table-ddl less aggressive about converting column spec items --- CHANGES.md | 2 ++ src/main/clojure/clojure/java/jdbc.clj | 15 ++++++--------- src/test/clojure/clojure/java/test_utilities.clj | 11 +++++++---- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 90bf9bc4..45e67ce6 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ Changes coming in 0.3.1 * Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). +* Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. + Changes in 0.3.0 * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 46bf4b0a..9138ce24 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -923,22 +923,19 @@ compatibility but it will be removed before a 1.0.0 release." } (defn create-table-ddl "Given a table name and column specs with an optional table-spec return the DDL string for creating that table." - [name & specs] + [table & specs] (let [col-specs (take-while (fn [s] (not (or (= :table-spec s) (= :entities s)))) specs) other-specs (drop (count col-specs) specs) {:keys [table-spec entities] :or {entities identity}} other-specs table-spec-str (or (and table-spec (str " " table-spec)) "") - specs-to-string (fn [specs] - (apply str - (map (as-sql-name entities) - (apply concat - (interpose [", "] - (map (partial interpose " ") specs))))))] + spec-to-string (fn [spec] + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))))] (format "CREATE TABLE %s (%s)%s" - (as-sql-name entities name) - (specs-to-string col-specs) + (as-sql-name entities table) + (str/join ", " (map spec-to-string col-specs)) table-spec-str))) (defn drop-table-ddl diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index c9fcebd2..5d28ea8a 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -57,7 +57,10 @@ ;; DDL tests (deftest test-create-table-ddl - (is (= "CREATE TABLE table (col1 int, col2 int)" - (sql/create-table-ddl :table ["col1 int"] [:col2 :int]))) - (is (= "CREATE TABLE table (col1 int, col2 int) ENGINE=MyISAM" - (sql/create-table-ddl :table [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM")))) \ No newline at end of file + (is (= "CREATE TABLE THING (COL1 INT, COL2 int)" + (sql/create-table-ddl :thing ["col1 int"] [:col2 :int] + :entities clojure.string/upper-case))) + (is (= "CREATE TABLE THING (COL1 int, COL2 int) ENGINE=MyISAM" + (sql/create-table-ddl :thing [:col1 "int"] ["col2" :int] + :table-spec "ENGINE=MyISAM" + :entities clojure.string/upper-case)))) \ No newline at end of file From 0125d8d7a031f3b0a8ea3969f08a212bc27a13a5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 29 Dec 2013 16:23:28 -0800 Subject: [PATCH 203/630] Fix JDBC-86 by adding another protocol extension point for setting parameters --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 22 +++++++++++++++---- src/test/clojure/clojure/java/test_jdbc.clj | 24 +++++++++++++++++++++ 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 45e67ce6..aa43d9f6 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.1 +* Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86). * Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9138ce24..1b648ba6 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -283,13 +283,27 @@ compatibility but it will be removed before a 1.0.0 release." } nil (sql-value [_] nil)) +(defprotocol ISQLParameter + "Protocol for setting SQL parameters in statement objects, which + can convert from Clojure values. The default implementation just + delegates the conversion to ISQLValue's sql-value conversion and + uses .setObject on the parameter." + (set-parameter [val stmt ix] + "Convert a Clojure value into a SQL value and store it as the ix'th + parameter in the given SQL statement object.")) + +(extend-protocol ISQLParameter + Object + (set-parameter [v ^PreparedStatement s ^long i] + (.setObject s i (sql-value v)))) + (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default implementations (for Object and nil) return the argument, and the Boolean implementation ensures a canonicalized true/false value, but it can be extended to provide custom behavior for special types." - (result-set-read-column [val rsmeta idx] "Function for transforming values after reading them - from the database")) + (result-set-read-column [val rsmeta idx] + "Function for transforming values after reading them from the database")) (extend-protocol IResultSetReadColumn Object @@ -400,9 +414,9 @@ compatibility but it will be removed before a 1.0.0 release." } (defn- set-parameters "Add the parameters to the given statement." - [^PreparedStatement stmt params] + [stmt params] (dorun (map-indexed (fn [ix value] - (.setObject stmt (inc ix) (sql-value value))) + (set-parameter value stmt (inc ix))) params))) (defn print-sql-exception diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 5a68ed30..bc844dff 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -737,3 +737,27 @@ (extend-protocol sql/ISQLValue clojure.lang.Keyword (sql-value [k] k))) + +(deftest test-sql-parameter + (extend-protocol sql/ISQLParameter + clojure.lang.Keyword + (set-parameter [v ^java.sql.PreparedStatement s ^long i] + (if (= :twelve v) + (.setLong s i 12) + (.setString s i (str (name v) i))))) + + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost] + [:test :twelve]) + (is (= {:name "test1", :cost 12} + (sql/query db ["SELECT name, cost FROM fruit"] + :result-set-fn first)))) + + ;; somewhat "undo" the first extension + (extend-protocol sql/ISQLParameter + clojure.lang.Keyword + (set-parameter [v ^java.sql.PreparedStatement s ^long i] + (.setObject s i (sql/sql-value v))))) From c287e8dfecc6b02a53b329bb5ae02dac76d5ea99 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 29 Dec 2013 20:05:23 -0800 Subject: [PATCH 204/630] Update copyright --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1b648ba6..ac354467 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,4 +1,4 @@ -;; Copyright (c) Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2008-2014 Sean Corfield, Stephen C. Gilardi. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be From bc024ef2c3720328685d45066bfcb8c24fbde6af Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 29 Dec 2013 20:09:53 -0800 Subject: [PATCH 205/630] Improve docstrings and add :arglists --- src/main/clojure/clojure/java/jdbc.clj | 85 +++++++++++++++++++------- 1 file changed, 63 insertions(+), 22 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ac354467..61a708e2 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -53,11 +53,11 @@ compatibility but it will be removed before a 1.0.0 release." } (:require [clojure.string :as str])) (defn as-sql-name - "Given a naming strategy and a keyword or string, return the keyword - as a string per that naming strategy. - A keyword of the form :x.y is treated as keywords :x and :y, - both are turned into strings via the naming strategy and then - joined back together so :x.y might become `x`.`y` if the naming + "Given a naming strategy function and a keyword or string, return + a string per that naming strategy. + A name of the form x.y is treated as multiple names, x, y, etc, + and each are turned into strings via the naming strategy and then + joined back together so x.y might become `x`.`y` if the naming strategy quotes identifiers with `." ([f] (fn [x] @@ -70,10 +70,13 @@ compatibility but it will be removed before a 1.0.0 release." } (str/join "." (map f (.split n "\\."))))))) (defn quoted - "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (quoted \\X \"foo\") will return \"XfooX\" - (quoted [\\A \\B] \"foo\") will return \"AfooB\"" + "With a single argument, returns a naming strategy function that quotes + names. The single argument can either be a single character or a vector + pair of characters. + Can also be called with two arguments - a quoting argument and a name - + and returns the fully quoted string: + (quoted \\` \"foo\") will return \"`foo`\" + (quoted [\\[ \\]] \"foo\") will return \"[foo]\"" ([q] (fn [x] (quoted q x))) @@ -94,6 +97,7 @@ compatibility but it will be removed before a 1.0.0 release." } (str v)))) p)) +;; convenience for working with different forms of connections (defprotocol Connectable (add-connection [db connection]) (get-level [db])) @@ -161,9 +165,9 @@ compatibility but it will be removed before a 1.0.0 release." } (catch ClassNotFoundException _#))) (defn get-connection - "Creates a connection to a database. db-spec is a map containing connection - parameters. db-spec is a map containing values for one of the following - parameter sets: + "Creates a connection to a database. db-spec is usually a map containing connection + parameters but can also be a URI or a String. The various possibilities are described + below: Existing Connection: :connection (required) an existing open connection that can be used @@ -287,7 +291,8 @@ compatibility but it will be removed before a 1.0.0 release." } "Protocol for setting SQL parameters in statement objects, which can convert from Clojure values. The default implementation just delegates the conversion to ISQLValue's sql-value conversion and - uses .setObject on the parameter." + uses .setObject on the parameter. It can be extended to use other + methods of PreparedStatement to convert and set parameter values." (set-parameter [val stmt ix] "Convert a Clojure value into a SQL value and store it as the ix'th parameter in the given SQL statement object.")) @@ -513,7 +518,11 @@ compatibility but it will be removed before a 1.0.0 release." } evaluating the outermost body, or rolled back on any uncaught exception. If rollback is set within scope of the outermost transaction, the entire transaction will be rolled back rather than committed when - complete." + complete. + The isolation option may be :none, :read-committed, :read-uncommitted, + :repeatable-read, or :serializable. Note that not all databases support + all of those isolation levels, and may either throw an exception or + substitute another isolation level." [db func & {:keys [isolation]}] (if (zero? (get-level db)) (if-let [^java.sql.Connection con (db-find-connection db)] @@ -548,7 +557,10 @@ compatibility but it will be removed before a 1.0.0 release." } (defmacro with-db-transaction "Evaluates body in the context of a transaction on the specified database connection. The binding provides the database connection for the transaction and the name to which - that is bound for evaluation of the body. + that is bound for evaluation of the body. The binding may also specify the isolation + level for the transaction, via the :isolation option. + (with-db-transaction [t-con db-spec :isolation level] + ... t-con ...) See db-transaction* for more details." [binding & body] `(db-transaction* ~(second binding) @@ -557,7 +569,8 @@ compatibility but it will be removed before a 1.0.0 release." } (defmacro with-db-connection "Evaluates body in the context of an active connection to the database. - (with-db-connection [con-db db-spec] ... con-db ...)" + (with-db-connection [con-db db-spec] + ... con-db ...)" [binding & body] `(let [db-spec# ~(second binding)] (with-open [^java.sql.Connection con# (get-connection db-spec#)] @@ -566,8 +579,10 @@ compatibility but it will be removed before a 1.0.0 release." } (defmacro with-db-metadata "Evaluates body in the context of an active connection with metadata bound - to the specified name. See also metadata-result below. - (with-db-metadata [md db-spec] ... md ..." + to the specified name. See also metadata-result for dealing with the results + of operations that retrieve information from the metadata. + (with-db-metadata [md db-spec] + ... md ...)" [binding & body] `(with-open [^java.sql.Connection con# (get-connection ~(second binding))] (let [~(first binding) (.getMetaData con#)] @@ -575,7 +590,9 @@ compatibility but it will be removed before a 1.0.0 release." } (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, - else return it as-is. This makes working with metadata easier." + else return it as-is. This makes working with metadata easier. + Also accepts :identifiers and :as-arrays? to control how the ResultSet + is transformed and returned. See query for more details." [rs-or-value & {:keys [identifiers as-arrays?] :or {identifiers str/lower-case}}] (if (instance? java.sql.ResultSet rs-or-value) @@ -586,6 +603,8 @@ compatibility but it will be removed before a 1.0.0 release." } "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it defaults to true." + {:arglists '([db-spec sql-command & sql-commands] + [db-spec transaction? sql-command & sql-commands])} [db transaction? & commands] (if (string? transaction?) (apply db-do-commands db true transaction? commands) @@ -642,6 +661,8 @@ compatibility but it will be removed before a 1.0.0 release." } open database connection. Each param-group is a seq of values for all of the parameters. transaction? can be omitted and defaults to true. Return a seq of update counts (one count for each param-group)." + {:arglists '([db-spec sql & param-groups] + [db-spec transaction? sql & param-groups])} [db transaction? & [sql & param-groups :as opts]] (if (string? transaction?) (apply db-do-prepared db true transaction? opts) @@ -671,13 +692,16 @@ compatibility but it will be removed before a 1.0.0 release." } (defn db-query-with-resultset "Executes a query, then evaluates func passing in the raw ResultSet as an - argument. The first argument is a vector containing either: + argument. The second argument is a vector containing either: [sql & params] - a SQL query, followed by any parameters it needs [stmt & params] - a PreparedStatement, followed by any parameters it needs (the PreparedStatement already contains the SQL query) [options sql & params] - options and a SQL query for creating a PreparedStatement, followed by any parameters it needs See prepare-statement for supported options." + {:arglists '([db-spec [sql-string & params] func] + [db-spec [stmt & params] func] + [db-spec [options-map sql-string & params] func])} [db sql-params func] (when-not (vector? sql-params) (let [^Class sql-params-class (class sql-params) @@ -722,7 +746,18 @@ compatibility but it will be removed before a 1.0.0 release." } if :as-arrays? false, :result-set-fn will default to doall :row-fn - applied to each row as the result set is constructed, default identity :identifiers - applied to each column name in the result set, default lower-case - :as-arrays? - return the results as a set of arrays, default false." + :as-arrays? - return the results as a set of arrays, default false. + The second argument is a vector containing a SQL string or PreparedStatement, followed + by any parameters it needs. See db-query-with-resultset for details." + {:arglists '([db-spec sql-and-params + :as-arrays? false :identifiers clojure.string/lower-case + :result-set-fn doall :row-fn identity] + [db-spec sql-and-params + :as-arrays? true :identifiers clojure.string/lower-case + :result-set-fn vec :row-fn identity] + [db-spec [sql-string & params]] + [db-spec [stmt & params]] + [db-spec [option-map sql-string & params]])} [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] :or {row-fn identity identifiers str/lower-case}}] @@ -740,6 +775,8 @@ compatibility but it will be removed before a 1.0.0 release." } "Given a database connection and a vector containing SQL and optional parameters, perform a general (non-select) SQL operation. The optional keyword argument specifies whether to run the operation in a transaction or not (default true)." + {:arglists '([db-spec [sql & params] :multi? false :transaction? true] + [db-spec [sql & param-groups] :multi? true :transaction? true])} [db sql-params & {:keys [transaction? multi?] :or {transaction? true multi? false}}] (let [param-groups (rest sql-params) @@ -885,7 +922,11 @@ compatibility but it will be removed before a 1.0.0 release." } "Given a database connection, a table name and either maps representing rows or a list of column names followed by lists of column values, perform an insert. Use :transaction? argument to specify whether to run in a transaction or not. - The default is true (use a transaction)." + The default is true (use a transaction). Use :entities to specify how to convert + the table name and column names to SQL entities." + {:arglists '([db-spec table row-map :transaction? true :entities identity] + [db-spec table row-map & row-maps :transaction? true :entities identity] + [db-spec table col-name-vec col-val-vec & col-val-vecs :transaction? true :entities identity])} [db table & options] (let [[transaction? maps-or-cols-and-values-etc] (extract-transaction? options) stmts (apply insert-sql table maps-or-cols-and-values-etc)] From d1b44d495f4514ac3b3cf676d32fa03dd5176d04 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 29 Dec 2013 20:12:03 -0800 Subject: [PATCH 206/630] Make insert-sql private "again" (it was not supposed to be public in 0.3.0). --- CHANGES.md | 2 ++ src/main/clojure/clojure/java/jdbc.clj | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index aa43d9f6..fa0eb7e4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,7 @@ Changes coming in 0.3.1 +* Improve docstrings and add :arglists for better auto-generated documentation. +* Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! * Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86). * Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 61a708e2..4b89467f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -895,7 +895,7 @@ compatibility but it will be removed before a 1.0.0 release." } " )")] (vals row)))) -(defn insert-sql +(defn- insert-sql "Given a table name and either column names and values or maps representing rows, return a vector of the SQL for that insert operation followed by its parameters. An optional entities spec (default 'as-is') specifies how to transform column names." From b246d7ce1a398753a03768ce0f77df5cc95c4074 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 29 Dec 2013 20:17:20 -0800 Subject: [PATCH 207/630] Prep for 0.3.1 release --- CHANGES.md | 2 +- README.md | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index fa0eb7e4..864b2437 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.1 +Changes in 0.3.1 * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! diff --git a/README.md b/README.md index d2ed5b0e..bba0483f 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.0 +Latest stable release: 0.3.1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.0 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.0"] +[org.clojure/java.jdbc "0.3.1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.0 + 0.3.1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,6 +118,13 @@ Developer Information Change Log ==================== +* Release 0.3.1 on 2013-12-29 + * Improve docstrings and add :arglists for better auto-generated documentation. + * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! + * Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86). + * Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). + * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. + * Release 0.3.0 on 2013-12-16 * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). * Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83). From 2cfdc427486c998100082a35320b374df957a954 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 29 Dec 2013 22:26:06 -0600 Subject: [PATCH 208/630] [maven-release-plugin] prepare release java.jdbc-0.3.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d4100a79..bde40b0f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.1-SNAPSHOT + 0.3.1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.1 From 534244703ac6f4dd321eadb2b634f65d9531896f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 29 Dec 2013 22:26:07 -0600 Subject: [PATCH 209/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index bde40b0f..1ee8e186 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.1 + 0.3.2-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.1 + HEAD From 580a763cb8a1138249678378756e61b028cc05e2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Dec 2013 09:03:18 -0800 Subject: [PATCH 210/630] Add nil implementation to ISQLParameter; add nil cases to protocol tests. --- src/main/clojure/clojure/java/jdbc.clj | 6 ++++- src/test/clojure/clojure/java/test_jdbc.clj | 28 ++++++++++----------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 4b89467f..7f100f80 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -300,7 +300,11 @@ compatibility but it will be removed before a 1.0.0 release." } (extend-protocol ISQLParameter Object (set-parameter [v ^PreparedStatement s ^long i] - (.setObject s i (sql-value v)))) + (.setObject s i (sql-value v))) + + nil + (set-parameter [_ ^PreparedStatement s ^long i] + (.setObject s i (sql-value nil)))) (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index bc844dff..843c1083 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -704,12 +704,12 @@ (create-test-table :fruit db) (sql/insert! db :fruit - [:name :cost] - ["Crepes" 12] - ["Vegetables" -88] - ["Teenage Mutant Ninja Turtles" 0]) - (is (= {:name ::FOO, :cost -88} - (sql/query db ["SELECT name, cost FROM fruit WHERE name = ?" + [:name :cost :grade] + ["Crepes" 12 87.7] + ["Vegetables" -88 nil] + ["Teenage Mutant Ninja Turtles" 0 100.0]) + (is (= {:name ::FOO, :cost -88, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?" "Vegetables"] :result-set-fn first)))) @@ -727,10 +727,10 @@ (create-test-table :fruit db) (sql/insert! db :fruit - [:name :cost] - [:test 12]) - (is (= {:name "KW", :cost 12} - (sql/query db ["SELECT name, cost FROM fruit"] + [:name :cost :grade] + [:test 12 nil]) + (is (= {:name "KW", :cost 12, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit"] :result-set-fn first)))) ;; somewhat "undo" the first extension @@ -750,10 +750,10 @@ (create-test-table :fruit db) (sql/insert! db :fruit - [:name :cost] - [:test :twelve]) - (is (= {:name "test1", :cost 12} - (sql/query db ["SELECT name, cost FROM fruit"] + [:name :cost :grade] + [:test :twelve nil]) + (is (= {:name "test1", :cost 12, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit"] :result-set-fn first)))) ;; somewhat "undo" the first extension From b14fbfdcfae9bd06e6cbf5e4ca6a94bcedc8dc16 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Dec 2013 09:08:32 -0800 Subject: [PATCH 211/630] Prep for 0.3.2 --- CHANGES.md | 6 +++++- README.md | 11 +++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 864b2437..144da20e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,8 @@ -Changes in 0.3.1 +Changes in 0.3.2 + +* Add nil protocol implementation to ISQLParameter. + +Changes in 0.3.1 (broken) * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! diff --git a/README.md b/README.md index bba0483f..75f26e59 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.1 +Latest stable release: 0.3.2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.1"] +[org.clojure/java.jdbc "0.3.2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.1 + 0.3.2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,7 +118,10 @@ Developer Information Change Log ==================== -* Release 0.3.1 on 2013-12-29 +* Release 0.3.2 on 2013-12-30 + * Add nil protocol implementation to ISQLParameter + +* Release 0.3.1 on 2013-12-29 (broken; use 0.3.2 instead) * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! * Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86). From 99ddfb6197a97a24bef96a05225b4d81766b1156 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 30 Dec 2013 11:09:52 -0600 Subject: [PATCH 212/630] [maven-release-plugin] prepare release java.jdbc-0.3.2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1ee8e186..32b8852a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.2-SNAPSHOT + 0.3.2 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.2 From 0e727f128438c758cdb502b26143353cbe3d73ea Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 30 Dec 2013 11:09:52 -0600 Subject: [PATCH 213/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 32b8852a..49caf041 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.2 + 0.3.3-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.2 + HEAD From 7e328db50d0918559f244fc99ef11f4a11bcba0f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Dec 2013 09:13:05 -0800 Subject: [PATCH 214/630] Bump project.clj to match pom.xml --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index be3fc44e..f71386b0 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,4 @@ -(defproject org.clojure/java.jdbc "0.3.0-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.3.3-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From f16a054ea3e13fd5d0724330390eec6e852153f3 Mon Sep 17 00:00:00 2001 From: Phil Hagelberg Date: Tue, 21 Jan 2014 10:20:11 -0800 Subject: [PATCH 215/630] Support arbitrary db-spec k/vs from query params in URIs. This makes it a lot easier to support SSL connections from URI-style DB connection parameters. --- src/main/clojure/clojure/java/jdbc.clj | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7f100f80..46959587 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -50,7 +50,8 @@ compatibility but it will be removed before a 1.0.0 release." } PreparedStatement ResultSet SQLException Statement Types] [java.util Hashtable Map Properties] [javax.sql DataSource]) - (:require [clojure.string :as str])) + (:require [clojure.string :as str] + [clojure.walk :as walk])) (defn as-sql-name "Given a naming strategy function and a keyword or string, return @@ -141,7 +142,10 @@ compatibility but it will be removed before a 1.0.0 release." } (let [host (.getHost uri) port (if (pos? (.getPort uri)) (.getPort uri)) path (.getPath uri) - scheme (.getScheme uri)] + scheme (.getScheme uri) + query (.getQuery uri) + query-parts (and query (for [kvs (.split query "&")] + (vec (.split kvs "="))))] (merge {:subname (if port (str "//" host ":" port path) @@ -149,7 +153,8 @@ compatibility but it will be removed before a 1.0.0 release." } :subprotocol (subprotocols scheme scheme)} (if-let [user-info (.getUserInfo uri)] {:user (first (str/split user-info #":")) - :password (second (str/split user-info #":"))})))) + :password (second (str/split user-info #":"))}) + (walk/keywordize-keys (into {} query-parts))))) (defn- strip-jdbc [^String spec] (if (.startsWith spec "jdbc:") From fba097f0aca0f643b128a89930e612bf326ad6d8 Mon Sep 17 00:00:00 2001 From: Phil Hagelberg Date: Tue, 21 Jan 2014 13:59:41 -0800 Subject: [PATCH 216/630] Add explict tests for URI-style DB specs. Note that there is some redundancy here since URI specs may be tested by `postgres-str-db` and friends, but it wasn't clear how those are invoked in the test suite as it is, so I've left them alone even though they appear unnecessary. --- src/test/clojure/clojure/java/test_jdbc.clj | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 843c1083..5ca36fbb 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -177,6 +177,20 @@ [:grade :real] :table-spec ""))) +(deftest test-uri-spec-parsing + (is (= {:advanced "false" :ssl "required" :password "clojure_test" + :user "clojure_test" :subname "//localhost/clojure_test" + :subprotocol "postgresql"} + (@#'sql/parse-properties-uri + (java.net.URI. + (str "postgres://clojure_test:clojure_test@localhost/clojure_test?" + "ssl=required&advanced=false"))))) + (is (= {:password "clojure_test" :user "clojure_test" + :subname "//localhost:3306/clojure_test", :subprotocol "mysql"} + (@#'sql/parse-properties-uri + (java.net.URI. + "mysql://clojure_test:clojure_test@localhost:3306/clojure_test"))))) + (deftest test-create-table (doseq [db (test-specs)] (create-test-table :fruit db) From 5a71e99a2a5a740648d588ee1f0e0888d7103a2b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 29 Jan 2014 22:13:37 -0800 Subject: [PATCH 217/630] Fix JDBC-89 by allowing query to accept a bare query string --- src/main/clojure/clojure/java/jdbc.clj | 7 +++++-- src/test/clojure/clojure/java/test_jdbc.clj | 5 +++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 46959587..fa50ba92 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -770,8 +770,11 @@ compatibility but it will be removed before a 1.0.0 release." } [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] :or {row-fn identity identifiers str/lower-case}}] - (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] - (db-query-with-resultset db (vec sql-params) + (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) + sql-params-vector (if (string? sql-params) + (vector sql-params) + (vec sql-params))] + (db-query-with-resultset db sql-params-vector (^{:once true} fn* [rset] ((^{:once true} fn* [rs] (result-set-fn (if as-arrays? diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 5ca36fbb..61408a6a 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -585,6 +585,11 @@ (create-test-table :fruit db) (is (= [] (sql/query db ["SELECT * FROM fruit"]))))) +(deftest query-with-string + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= [] (sql/query db "SELECT * FROM fruit"))))) + (deftest insert-one-row (doseq [db (test-specs)] (create-test-table :fruit db) From 651a8904a4f2cfa59ea48faf35e68fba43170ff9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 29 Jan 2014 23:33:25 -0800 Subject: [PATCH 218/630] Fix JDBC-87 by adding :row-fn and :result-set-fn to metadata-result to match how query works --- src/main/clojure/clojure/java/jdbc.clj | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index fa50ba92..6055c424 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -600,13 +600,20 @@ compatibility but it will be removed before a 1.0.0 release." } (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, else return it as-is. This makes working with metadata easier. - Also accepts :identifiers and :as-arrays? to control how the ResultSet - is transformed and returned. See query for more details." - [rs-or-value & {:keys [identifiers as-arrays?] - :or {identifiers str/lower-case}}] - (if (instance? java.sql.ResultSet rs-or-value) - (result-set-seq rs-or-value :identifiers identifiers :as-arrays? as-arrays?) - rs-or-value)) + Also accepts :identifiers, :as-arrays?, :row-fn, and :result-set-fn + to control how the ResultSet is transformed and returned. + See query for more details." + [rs-or-value & {:keys [identifiers as-arrays? row-fn result-set-fn] + :or {identifiers str/lower-case row-fn identity}}] + (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (if (instance? java.sql.ResultSet rs-or-value) + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rs-or-value :identifiers identifiers :as-arrays? as-arrays?)) + rs-or-value))) (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands From 40736d52b2b92f4d8cdf3235bb016fccbe36b428 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 30 Jan 2014 23:18:09 -0800 Subject: [PATCH 219/630] Prep for 0.3.3 release --- CHANGES.md | 6 ++++++ README.md | 11 ++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 144da20e..c074c488 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,9 @@ +Changes in 0.3.3 + +* Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89). +* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87). +* Support key/value configuration from URI (Phil Hagelberg). + Changes in 0.3.2 * Add nil protocol implementation to ISQLParameter. diff --git a/README.md b/README.md index 75f26e59..40ce19c2 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.2 +Latest stable release: 0.3.3 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.2"] +[org.clojure/java.jdbc "0.3.3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.2 + 0.3.3 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,6 +118,11 @@ Developer Information Change Log ==================== +* Release 0.3.3 on 2014-01-30 + * Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89). + * Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87). + * Support key/value configuration from URI (Phil Hagelberg). + * Release 0.3.2 on 2013-12-30 * Add nil protocol implementation to ISQLParameter From f1c6fc1258e3475c1ccfbee0d60e2b61273fbdbe Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 31 Jan 2014 01:21:28 -0600 Subject: [PATCH 220/630] [maven-release-plugin] prepare release java.jdbc-0.3.3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 49caf041..a6e99fc5 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.3-SNAPSHOT + 0.3.3 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.3 From 191067e6c5f877c5ebdcfead1906ed134a66940a Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 31 Jan 2014 01:21:28 -0600 Subject: [PATCH 221/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a6e99fc5..b82c6813 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.3 + 0.3.4-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.3 + HEAD From e0a61c5baab1eeb56f83dae1bc4754f4ca97cbd2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 27 Feb 2014 23:35:05 -0800 Subject: [PATCH 222/630] Correct the version in project.clj --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index f71386b0..f01de92d 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,4 @@ -(defproject org.clojure/java.jdbc "0.3.3-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.3.4-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 500efca18a9bc4fbe1dad8899b11ec82a9398898 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 27 Feb 2014 23:36:17 -0800 Subject: [PATCH 223/630] Fix JDBC-90 by adding aliases for Oracle drivers. --- src/main/clojure/clojure/java/jdbc.clj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6055c424..e3524225 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -130,6 +130,8 @@ compatibility but it will be removed before a 1.0.0 release." } "mysql" "com.mysql.jdbc.Driver" "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver" "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" + "oracle:oci" "oracle.jdbc.OracleDriver" + "oracle:thin" "oracle.jdbc.OracleDriver" "derby" "org.apache.derby.jdbc.EmbeddedDriver" "hsqldb" "org.hsqldb.jdbcDriver" "h2" "org.h2.Driver" From 289cd353fd43a151f158a176650e09cff673026b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 27 Feb 2014 23:38:40 -0800 Subject: [PATCH 224/630] Add JDBC-90 to changes. --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index c074c488..6bd77a1f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.4 + +* Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). + Changes in 0.3.3 * Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89). From 4667bdd86e73870cbb1e369c65fe8262fa964637 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 7 Mar 2014 14:53:27 -0800 Subject: [PATCH 225/630] Fix JDBC-92 by providing simpler connection spec --- src/main/clojure/clojure/java/jdbc.clj | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7f100f80..635e3f0b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -183,6 +183,15 @@ compatibility but it will be removed before a 1.0.0 release." } :classname (optional) a String, the jdbc driver class name (others) (optional) passed to the driver as properties. + DriverManager (alternative): + :dbtype (required) a String, the type of the database (the jdbc subprotocol) + :dbname (required) a String, the name of the database + :host (optional) a String, the host name/IP of the database + (defaults to 127.0.0.1) + :port (optional) a Long, the port of the database + (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) + (others) (optional) passed to the driver as properties. + DataSource: :datasource (required) a javax.sql.DataSource :username (optional) a String @@ -209,6 +218,7 @@ compatibility but it will be removed before a 1.0.0 release." } factory connection-uri classname subprotocol subname + dbtype dbname host port datasource username password user name environment] :as db-spec}] @@ -234,6 +244,22 @@ compatibility but it will be removed before a 1.0.0 release." } classname (or classname (classnames subprotocol))] (clojure.lang.RT/loadClassForName classname) (DriverManager/getConnection url (as-properties etc))) + + (and dbtype dbname) + (let [subprotocol dbtype + host (or host "127.0.0.1") + port (or port (condp = subprotocol + "mysql" 3306 + "mssql" 1433 + "jtds" 1433 + nil)) + db-sep (if (= "mssql" subprotocol) ";DATABASENAME=" "/") + url (str "jdbc:" subprotocol "://" host + (when port (str ":" port)) + db-sep dbname) + etc (dissoc db-spec :dbtype :dbname)] + (clojure.lang.RT/loadClassForName (classnames subprotocol)) + (DriverManager/getConnection url (as-properties etc))) (or (and datasource username password) (and datasource user password)) From 98950bae0bbcfdf7003300def658264373abb9a9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 7 Mar 2014 15:10:56 -0800 Subject: [PATCH 226/630] Update CHANGE with JDBC-92 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 6bd77a1f..e824f662 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.4 +* Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). Changes in 0.3.3 From 0487a2817eace6d1b17f11ed5e3ab6a9a2cfe29e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 31 Mar 2014 09:49:01 -0700 Subject: [PATCH 227/630] Add CONTRIBUTING page, per Stuart Sierra. --- CONTRIBUTING.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..7800bfb8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,14 @@ +This is a [Clojure contrib] project. + +Under the Clojure contrib [guidelines], this project cannot accept +pull requests. All patches must be submitted via [JIRA]. + +See [Contributing] and the [FAQ] on the Clojure development [wiki] for +more information on how to contribute. + +[Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib +[Contributing]: http://dev.clojure.org/display/community/Contributing +[FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ +[JIRA]: http://dev.clojure.org/jira/browse/JDBC +[guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers +[wiki]: http://dev.clojure.org/ From 20bc517e037e82a951090eb1b6cbb42df258f92e Mon Sep 17 00:00:00 2001 From: Tejas Dinkar Date: Tue, 13 May 2014 17:53:57 +0530 Subject: [PATCH 228/630] execute! can now accept prepared statements as well Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 45 ++++++++++++--------- src/test/clojure/clojure/java/test_jdbc.clj | 18 ++++++++- 2 files changed, 41 insertions(+), 22 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 01c4f21c..e0a16e50 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -700,6 +700,27 @@ compatibility but it will be removed before a 1.0.0 release." } (with-open [^java.sql.Connection con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) +(defn- db-do-execute-prepared-statement [db stmt param-groups transaction?] + (if (empty? param-groups) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (vector (.executeUpdate stmt))) + (try + (vector (.executeUpdate stmt)) + (catch Exception e + (throw-non-rte e)))) + (do + (doseq [param-group param-groups] + ((or (:set-parameters db) set-parameters) stmt param-group) + (.addBatch stmt)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (try + (execute-batch stmt) + (catch Exception e + (throw-non-rte e))))))) + (defn db-do-prepared "Executes an (optionally parameterized) SQL prepared statement on the open database connection. Each param-group is a seq of values for all of @@ -711,26 +732,10 @@ compatibility but it will be removed before a 1.0.0 release." } (if (string? transaction?) (apply db-do-prepared db true transaction? opts) (if-let [^java.sql.Connection con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql)] - (if (empty? param-groups) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) - (try - (vector (.executeUpdate stmt)) - (catch Exception e - (throw-non-rte e)))) - (do - (doseq [param-group param-groups] - ((or (:set-parameters db) set-parameters) stmt param-group) - (.addBatch stmt)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (try - (execute-batch stmt) - (catch Exception e - (throw-non-rte e))))))) + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-statement db sql param-groups transaction?) + (with-open [^PreparedStatement stmt (prepare-statement con sql)] + (db-do-execute-prepared-statement db stmt param-groups transaction?))) (with-open [^java.sql.Connection con (get-connection db)] (apply db-do-prepared (add-connection db con) transaction? sql param-groups))))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 61408a6a..a707d45d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -298,6 +298,20 @@ (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] :result-set-fn (comp :name first)))))) +(deftest execute-with-prepared-statement + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-connection [conn db] + (let [connection (:connection conn) + prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )"))] + + (sql/execute! db [prepared-statement "Apple" "Green" 75]) + (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + :result-set-fn (comp :name first)))))) + (deftest test-update-values (doseq [db (test-specs)] (create-test-table :fruit db) @@ -522,7 +536,7 @@ (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) (deftest test-raw-metadata - (doseq [db (test-specs)] + (doseq [db (test-specs)] (create-test-table :fruit db) (let [table-info (with-open [conn (sql/get-connection db)] (into [] @@ -538,7 +552,7 @@ clojure.string/lower-case)))))) (deftest test-metadata - (doseq [db (test-specs)] + (doseq [db (test-specs)] (create-test-table :fruit db) (sql/with-db-metadata [metadata db] (let [table-info (sql/metadata-result (.getTables metadata From 8d809f8828c073178321b00651e3656d496e5656 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 18 May 2014 17:03:58 -0700 Subject: [PATCH 229/630] Update CHANGES for JDBC-96 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index e824f662..4008f811 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.4 +* execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). From 501bd8eda7b0ef99b9e2860225cbf86f32dece87 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Jun 2014 11:03:16 -0700 Subject: [PATCH 230/630] Update docs for 0.3.4 release --- CHANGES.md | 2 +- README.md | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 4008f811..236dffd6 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.4 +Changes in 0.3.4 * execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). diff --git a/README.md b/README.md index 40ce19c2..bd81a8d6 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.3 +Latest stable release: 0.3.4 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.3 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.3"] +[org.clojure/java.jdbc "0.3.4"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.3 + 0.3.4 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,6 +118,11 @@ Developer Information Change Log ==================== +* Release 0.3.4 on 2014-06-30 + * execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). + * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). + * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). + * Release 0.3.3 on 2014-01-30 * Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89). * Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87). From 8eca5b0d5c58ce36a437f59fc74963194bc96c21 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 30 Jun 2014 13:16:17 -0500 Subject: [PATCH 231/630] [maven-release-plugin] prepare release java.jdbc-0.3.4 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b82c6813..931f0a74 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.4-SNAPSHOT + 0.3.4 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.4 From a1a0a0d783a7e242a01167b44b9405124076c5f3 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 30 Jun 2014 13:16:17 -0500 Subject: [PATCH 232/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 931f0a74..3690b78a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.4 + 0.3.5-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.4 + HEAD From fb78e3ba7b9357289a05b1553c3601bf17339cb1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Jun 2014 11:28:21 -0700 Subject: [PATCH 233/630] Bump project.clj to match pom.xml version --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index f01de92d..290c598a 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,4 @@ -(defproject org.clojure/java.jdbc "0.3.4-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.3.5-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From f70a69f1119dc348e196df9c1f82568df345718e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Jun 2014 19:32:05 -0700 Subject: [PATCH 234/630] Fixes JDBC-94 by using schemeSpecificPart if host is not present in URI. --- CHANGES.md | 4 ++++ src/main/clojure/clojure/java/jdbc.clj | 8 +++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 236dffd6..bf00e28d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.5 + +* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). + Changes in 0.3.4 * execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e0a16e50..2957bb08 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -149,9 +149,11 @@ compatibility but it will be removed before a 1.0.0 release." } query-parts (and query (for [kvs (.split query "&")] (vec (.split kvs "="))))] (merge - {:subname (if port - (str "//" host ":" port path) - (str "//" host path)) + {:subname (if host + (if port + (str "//" host ":" port path) + (str "//" host path)) + (.getSchemeSpecificPart uri)) :subprotocol (subprotocols scheme scheme)} (if-let [user-info (.getUserInfo uri)] {:user (first (str/split user-info #":")) From a9bcd81cb78b06858cbd882b6b65864ef37a6edc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Jun 2014 19:43:29 -0700 Subject: [PATCH 235/630] Fixes JDBC-93 by adding :read-only? to transactions --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 22 +++++++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index bf00e28d..d3ad6fda 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.5 * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). +* Add support for readonly transactions via :read-only? [JDBC-93](https://dev.clojure.org/jira/browse/JDBC-93). Changes in 0.3.4 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 2957bb08..d720400e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -561,16 +561,20 @@ compatibility but it will be removed before a 1.0.0 release." } The isolation option may be :none, :read-committed, :read-uncommitted, :repeatable-read, or :serializable. Note that not all databases support all of those isolation levels, and may either throw an exception or - substitute another isolation level." - [db func & {:keys [isolation]}] + substitute another isolation level. + The read-only? option puts the transaction in readonly mode (if supported)." + [db func & {:keys [isolation read-only?]}] (if (zero? (get-level db)) (if-let [^java.sql.Connection con (db-find-connection db)] (let [nested-db (inc-level db) auto-commit (.getAutoCommit con) - old-isolation (.getTransactionIsolation con)] + old-isolation (.getTransactionIsolation con) + old-readonly (.isReadOnly con)] (io! (when isolation (.setTransactionIsolation con (isolation isolation-levels))) + (when read-only? + (.setReadOnly con true)) (.setAutoCommit con false) (try (let [result (func nested-db)] @@ -585,9 +589,12 @@ compatibility but it will be removed before a 1.0.0 release." } (db-unset-rollback-only! nested-db) (.setAutoCommit con auto-commit) (when isolation - (.setTransactionIsolation con old-isolation)))))) + (.setTransactionIsolation con old-isolation)) + (when read-only? + (.setReadOnly con old-readonly)))))) (with-open [^java.sql.Connection con (get-connection db)] - (db-transaction* (add-connection db con) func :isolation isolation))) + (db-transaction* (add-connection db con) func + :isolation isolation :read-only? read-only?))) (try (func (inc-level db)) (catch Exception e @@ -597,8 +604,9 @@ compatibility but it will be removed before a 1.0.0 release." } "Evaluates body in the context of a transaction on the specified database connection. The binding provides the database connection for the transaction and the name to which that is bound for evaluation of the body. The binding may also specify the isolation - level for the transaction, via the :isolation option. - (with-db-transaction [t-con db-spec :isolation level] + level for the transaction, via the :isolation option and/or set the transaction to + readonly via the :read-only? option. + (with-db-transaction [t-con db-spec :isolation level :read-only? true] ... t-con ...) See db-transaction* for more details." [binding & body] From 97be163884d402c4506e2397a528b15a23867a8f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 Jun 2014 19:45:24 -0700 Subject: [PATCH 236/630] Update project.clj to test Clojure 1.7 on master and 1.6 final --- project.clj | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/project.clj b/project.clj index 290c598a..1b154b7c 100644 --- a/project.clj +++ b/project.clj @@ -21,7 +21,9 @@ :1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} - :1.6 {:dependencies [[org.clojure/clojure "1.6.0-master-SNAPSHOT"]]}} - :aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6" "test"] - "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6" "check"]} + :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} + :1.7 {:dependencies [[org.clojure/clojure "1.7.0-master-SNAPSHOT"]]} + } + :aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6:test,1.7" "test"] + "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6:1.7" "check"]} :min-lein-version "2.0.0") From 0fea524f92425c6009d403fb2ed3dedb0565ab78 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 1 Aug 2014 15:29:05 -0700 Subject: [PATCH 237/630] Fix some reflection warnings reported by Brian Craft. --- src/main/clojure/clojure/java/jdbc.clj | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d720400e..d771abc0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -145,8 +145,8 @@ compatibility but it will be removed before a 1.0.0 release." } port (if (pos? (.getPort uri)) (.getPort uri)) path (.getPath uri) scheme (.getScheme uri) - query (.getQuery uri) - query-parts (and query (for [kvs (.split query "&")] + ^String query (.getQuery uri) + query-parts (and query (for [^String kvs (.split query "&")] (vec (.split kvs "="))))] (merge {:subname (if host @@ -710,7 +710,8 @@ compatibility but it will be removed before a 1.0.0 release." } (with-open [^java.sql.Connection con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) -(defn- db-do-execute-prepared-statement [db stmt param-groups transaction?] +(defn- db-do-execute-prepared-statement + [db ^PreparedStatement stmt param-groups transaction?] (if (empty? param-groups) (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] From 72c5b449cdc7ed781b2d240547f8fd0045740553 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 1 Aug 2014 15:31:17 -0700 Subject: [PATCH 238/630] Update README/CHANGES for 0.3.5 release --- CHANGES.md | 3 ++- README.md | 11 ++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d3ad6fda..8a68fede 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ -Changes coming in 0.3.5 +Changes in 0.3.5 +* Reflection warnings on executeUpdate addressed. * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). * Add support for readonly transactions via :read-only? [JDBC-93](https://dev.clojure.org/jira/browse/JDBC-93). diff --git a/README.md b/README.md index bd81a8d6..67e2766e 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.4 +Latest stable release: 0.3.5 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.4 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.4"] +[org.clojure/java.jdbc "0.3.5"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.4 + 0.3.5 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,6 +118,11 @@ Developer Information Change Log ==================== +* Release 0.3.5 on 2014-08-01 + * Reflection warnings on executeUpdate addressed. + * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). + * Add support for readonly transactions via :read-only? [JDBC-93](https://dev.clojure.org/jira/browse/JDBC-93). + * Release 0.3.4 on 2014-06-30 * execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). From 5fbb108016862314810a251af4831a5a6ab6365b Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 1 Aug 2014 17:33:40 -0500 Subject: [PATCH 239/630] [maven-release-plugin] prepare release java.jdbc-0.3.5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3690b78a..5128f0c9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.5-SNAPSHOT + 0.3.5 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.5 From aa1b08bc61b5da6b733c0b5da6a42424f0231aef Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 1 Aug 2014 17:33:40 -0500 Subject: [PATCH 240/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5128f0c9..9d8976e4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.5 + 0.3.6-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.5 + HEAD From 77623d71d331b26eef509405b7ca10b97280ab86 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 1 Aug 2014 15:40:21 -0700 Subject: [PATCH 241/630] Update project.clj to next snapshot for easier dev/testing --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index 1b154b7c..468a86c5 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,4 @@ -(defproject org.clojure/java.jdbc "0.3.5-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.3.6-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 954f33c70ac64ed139377973141ff86867e60e8e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 27 Aug 2014 12:09:52 -0700 Subject: [PATCH 242/630] Fix typo in insert-values docstring --- src/main/clojure/clojure/java/jdbc/deprecated.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/deprecated.clj b/src/main/clojure/clojure/java/jdbc/deprecated.clj index cbf0077d..e2b6ec93 100644 --- a/src/main/clojure/clojure/java/jdbc/deprecated.clj +++ b/src/main/clojure/clojure/java/jdbc/deprecated.clj @@ -565,7 +565,7 @@ generated keys are returned (as a map)." } (defn insert-values "Inserts rows into a table with values for specified columns only. column-names is a vector of strings or keywords identifying columns. Each - value-group is a vector containing a values for each column in + value-group is a vector containing a value for each column in order. When inserting complete rows (all columns), consider using insert-rows instead. If a single set of values is inserted, returns a map of the generated keys." From 275cc9d7219901c7a1a72720d475b37157e8b939 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:28:08 -0700 Subject: [PATCH 243/630] Fix JDBC-102 by defaulting to passed value if unknown for various result-set-* lookups --- src/main/clojure/clojure/java/jdbc.clj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d771abc0..c6a3d1fa 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -443,12 +443,12 @@ compatibility but it will be removed before a 1.0.0 release." } (and result-type concurrency) (if cursors (.prepareStatement con sql - (result-type result-set-type) - (concurrency result-set-concurrency) - (cursors result-set-holdability)) + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency) + (get result-set-holdability cursors cursors)) (.prepareStatement con sql - (result-type result-set-type) - (concurrency result-set-concurrency))) + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency))) :else (.prepareStatement con sql))] From 49f5b0001cdfb08b2053cc0757d8d91e78bbf54b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:31:31 -0700 Subject: [PATCH 244/630] Start list of changes for 0.3.6 --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 8a68fede..f73accb0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.6 + +* Arbitrary values allowed for cursors, concurrency, result-type [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). + Changes in 0.3.5 * Reflection warnings on executeUpdate addressed. From 3a580d78098b4efddfeecf435ddbdf70758f397e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:32:22 -0700 Subject: [PATCH 245/630] Note that I'm now testing locally with version 4.0 of Microsoft's MS SQL JDBC driver (was 3.0) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 67e2766e..6db4bfdc 100644 --- a/README.md +++ b/README.md @@ -57,11 +57,11 @@ shown as Leiningen dependencies: ;; SQLite [org.xerial/sqlite-jdbc "3.7.2"] ``` -For the latest versions, consult the vendor or project websites. clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 3.0 but that +For the latest versions, consult the vendor or project websites. clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 4.0 but that has to be downloaded manually and placed in a Maven repository accessible to your system. For testing, it was installed locally as: ```clojure -;; Microsoft SQL Server JDBC4 Driver 3.0 -[sqljdbc4/sqljdbc4 "3.0"] +;; Microsoft SQL Server JDBC4 Driver 4.0 +[sqljdbc4/sqljdbc4 "4.0"] ``` Example Usage From a1ba529ab0e4859046026a821c2df2bf76ec1075 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:34:07 -0700 Subject: [PATCH 246/630] Changes for 4.0 MS SQL JDBC driver --- pom.xml | 4 ++-- project.clj | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 9d8976e4..c26e4715 100644 --- a/pom.xml +++ b/pom.xml @@ -62,12 +62,12 @@ 1.2.4 test - + diff --git a/project.clj b/project.clj index 468a86c5..073bdf76 100644 --- a/project.clj +++ b/project.clj @@ -15,7 +15,7 @@ [org.xerial/sqlite-jdbc "3.7.2"] [net.sourceforge.jtds/jtds "1.2.4"] ;; if you have the MS driver in your local repo - ;; [sqljdbc4 "3.0"] + ;; [sqljdbc4 "4.0"] ] :profiles {:1.2 {:dependencies [[org.clojure/clojure "1.2.1"]]} :1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} From f9c003df075e2d23263568aca881288bab64cb43 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:34:50 -0700 Subject: [PATCH 247/630] Bump default test version from 1.6.0 master snapshot to 1.7.0 alpha 3 --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index 073bdf76..162c35ca 100644 --- a/project.clj +++ b/project.clj @@ -7,7 +7,7 @@ :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :dependencies [[org.clojure/clojure "1.6.0-master-SNAPSHOT"] + :dependencies [[org.clojure/clojure "1.7.0-alpha3"] [mysql/mysql-connector-java "5.1.25"] [org.apache.derby/derby "10.8.1.2"] [hsqldb "1.8.0.10"] From 9ee817e0423b89d501a5f3bec2280f3d075966c3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:58:18 -0700 Subject: [PATCH 248/630] Fix JDBC-99 by adding optional :timeout argument to prepare-statement --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f73accb0..7a448c4c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.6 * Arbitrary values allowed for cursors, concurrency, result-type [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). +* Add timeout argument to prepare-statement [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). Changes in 0.3.5 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c6a3d1fa..12917006 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -429,9 +429,11 @@ compatibility but it will be removed before a 1.0.0 release." } :concurrency :read-only | :updatable :cursors :fetch-size n - :max-rows n" + :max-rows n + :timeout n" [^java.sql.Connection con ^String sql & - {:keys [return-keys result-type concurrency cursors fetch-size max-rows]}] + {:keys [return-keys result-type concurrency cursors + fetch-size max-rows timeout]}] (let [^PreparedStatement stmt (cond return-keys (try @@ -454,6 +456,7 @@ compatibility but it will be removed before a 1.0.0 release." } (.prepareStatement con sql))] (when fetch-size (.setFetchSize stmt fetch-size)) (when max-rows (.setMaxRows stmt max-rows)) + (when timeout (.setQueryTimeout stmt timeout)) stmt)) (defn- set-parameters From 11c2fd94f447606e516c99ff86af1cdcf6c9c725 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 15:59:23 -0700 Subject: [PATCH 249/630] Correct changes to show JDBC-100 not JDBC-99 --- CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 7a448c4c..68a568e1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,7 @@ Changes coming in 0.3.6 * Arbitrary values allowed for cursors, concurrency, result-type [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). -* Add timeout argument to prepare-statement [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). +* Add timeout argument to prepare-statement [JDBC-100](https://dev.clojure.org/jira/browse/JDBC-100). Changes in 0.3.5 From 9fb6b0f6c75f7d04ef3a23655f0aedf944cddff8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 16:15:19 -0700 Subject: [PATCH 250/630] Fix JDBC-101 by supporting :as-arrays? :cols-as-is --- CHANGES.md | 5 +++-- src/main/clojure/clojure/java/jdbc.clj | 3 ++- src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 68a568e1..cf428d2c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,8 @@ Changes coming in 0.3.6 -* Arbitrary values allowed for cursors, concurrency, result-type [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). -* Add timeout argument to prepare-statement [JDBC-100](https://dev.clojure.org/jira/browse/JDBC-100). +* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). +* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://dev.clojure.org/jira/browse/JDBC-101). +* Add `:timeout` argument to `prepare-statement` [JDBC-100](https://dev.clojure.org/jira/browse/JDBC-100). Changes in 0.3.5 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 12917006..c46d9600 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -368,9 +368,10 @@ compatibility but it will be removed before a 1.0.0 release." } :or {identifiers str/lower-case}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) + col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) - make-cols-unique + col-name-fn (map (comp keyword identifiers))) row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index a707d45d..efffc77d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -635,7 +635,7 @@ (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] - :as-arrays? true)] + :as-arrays? :cols-as-is)] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [[:id :name :appearance :cost :grade] [(generated-key db 1) "Apple" nil nil nil] From d7c25fea86ab19965a8d65a38c84d80e6892c680 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 16:23:24 -0700 Subject: [PATCH 251/630] Prepare for 0.3.6 release --- CHANGES.md | 2 +- README.md | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index cf428d2c..21073ee5 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.6 +Changes in 0.3.6 * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://dev.clojure.org/jira/browse/JDBC-101). diff --git a/README.md b/README.md index 6db4bfdc..59765b71 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `cloju Releases and Dependency Information ======================================== -Latest stable release: 0.3.5 +Latest stable release: 0.3.6 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -31,14 +31,14 @@ Latest stable release: 0.3.5 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.5"] +[org.clojure/java.jdbc "0.3.6"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.5 + 0.3.6 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, @@ -118,6 +118,11 @@ Developer Information Change Log ==================== +* Release 0.3.6 on 2014-10-28 + * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). + * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://dev.clojure.org/jira/browse/JDBC-101). + * Add `:timeout` argument to `prepare-statement` [JDBC-100](https://dev.clojure.org/jira/browse/JDBC-100). + * Release 0.3.5 on 2014-08-01 * Reflection warnings on executeUpdate addressed. * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). @@ -282,7 +287,7 @@ Change Log Copyright and License ======================================== -Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2013. All rights reserved. The use and +Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2014. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. From 729616de96c3569df46e680103d3c4ad8545cb50 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 28 Oct 2014 18:36:12 -0500 Subject: [PATCH 252/630] [maven-release-plugin] prepare release java.jdbc-0.3.6 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c26e4715..9a3f2862 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.6-SNAPSHOT + 0.3.6 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.6 From 48995a09ca3a26473eb90b7846435ee86dd7c212 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 28 Oct 2014 18:36:12 -0500 Subject: [PATCH 253/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9a3f2862..7304f7f3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.6 + 0.3.7-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.6 + HEAD From f1a5e7d48841e10a8e3d5755fafb612527e27745 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Oct 2014 16:41:08 -0700 Subject: [PATCH 254/630] Update project.clj to match pom.xml after 0.3.6 release --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index 162c35ca..f42578a7 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,4 @@ -(defproject org.clojure/java.jdbc "0.3.6-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.3.7-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From cc8365fc46d36b09ea9508064f8f7de10e1256d9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 29 Oct 2014 14:23:19 -0700 Subject: [PATCH 255/630] Fix JDBC-103 by correcting links in CHANGES and README --- CHANGES.md | 16 ++++++++++------ README.md | 12 ++++++------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 21073ee5..dd1f7450 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,18 +1,22 @@ +Changes coming in 0.3.7 + +* Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. + Changes in 0.3.6 -* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). -* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://dev.clojure.org/jira/browse/JDBC-101). -* Add `:timeout` argument to `prepare-statement` [JDBC-100](https://dev.clojure.org/jira/browse/JDBC-100). +* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102). +* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101). +* Add `:timeout` argument to `prepare-statement` [JDBC-100](http://dev.clojure.org/jira/browse/JDBC-100). Changes in 0.3.5 * Reflection warnings on executeUpdate addressed. -* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). -* Add support for readonly transactions via :read-only? [JDBC-93](https://dev.clojure.org/jira/browse/JDBC-93). +* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://dev.clojure.org/jira/browse/JDBC-94). +* Add support for readonly transactions via :read-only? [JDBC-93](http://dev.clojure.org/jira/browse/JDBC-93). Changes in 0.3.4 -* execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). +* execute! can now accept a PreparedStatement [JDBC-96](http://dev.clojure.org/jira/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). diff --git a/README.md b/README.md index 59765b71..df180b4e 100644 --- a/README.md +++ b/README.md @@ -119,17 +119,17 @@ Change Log ==================== * Release 0.3.6 on 2014-10-28 - * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://dev.clojure.org/jira/browse/JDBC-102). - * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://dev.clojure.org/jira/browse/JDBC-101). - * Add `:timeout` argument to `prepare-statement` [JDBC-100](https://dev.clojure.org/jira/browse/JDBC-100). + * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102). + * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101). + * Add `:timeout` argument to `prepare-statement` [JDBC-100](http://dev.clojure.org/jira/browse/JDBC-100). * Release 0.3.5 on 2014-08-01 * Reflection warnings on executeUpdate addressed. - * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://dev.clojure.org/jira/browse/JDBC-94). - * Add support for readonly transactions via :read-only? [JDBC-93](https://dev.clojure.org/jira/browse/JDBC-93). + * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://dev.clojure.org/jira/browse/JDBC-94). + * Add support for readonly transactions via :read-only? [JDBC-93](http://dev.clojure.org/jira/browse/JDBC-93). * Release 0.3.4 on 2014-06-30 - * execute! can now accept a PreparedStatement [JDBC-96](https://dev.clojure.org/jira/browse/JDBC-96). + * execute! can now accept a PreparedStatement [JDBC-96](http://dev.clojure.org/jira/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). From 0603d20dcbef384779e913ca5fa0821181d7d634 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Nov 2014 16:07:25 -0800 Subject: [PATCH 256/630] Update SQLite driver version to 3.8.7 and re-test. --- CHANGES.md | 1 + README.md | 2 +- pom.xml | 2 +- project.clj | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index dd1f7450..64ad1d77 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.3.7 +* Update SQLite driver version to 3.8.7 and re-test. * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. Changes in 0.3.6 diff --git a/README.md b/README.md index df180b4e..5b27494f 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ shown as Leiningen dependencies: ;; PostgreSQL [postgresql/postgresql "8.4-702.jdbc4"] ;; SQLite -[org.xerial/sqlite-jdbc "3.7.2"] +[org.xerial/sqlite-jdbc "3.8.7"] ``` For the latest versions, consult the vendor or project websites. clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 4.0 but that has to be downloaded manually and placed in a Maven repository accessible to your system. For testing, it was installed locally as: diff --git a/pom.xml b/pom.xml index 7304f7f3..cf6edc0a 100644 --- a/pom.xml +++ b/pom.xml @@ -53,7 +53,7 @@ org.xerial sqlite-jdbc - 3.7.2 + 3.8.7 test diff --git a/project.clj b/project.clj index f42578a7..6b611779 100644 --- a/project.clj +++ b/project.clj @@ -12,7 +12,7 @@ [org.apache.derby/derby "10.8.1.2"] [hsqldb "1.8.0.10"] [postgresql "8.4-702.jdbc4"] - [org.xerial/sqlite-jdbc "3.7.2"] + [org.xerial/sqlite-jdbc "3.8.7"] [net.sourceforge.jtds/jtds "1.2.4"] ;; if you have the MS driver in your local repo ;; [sqljdbc4 "4.0"] From 179e8703d6a2b54cfb6c9fd8214d6c0ea695d411 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 May 2015 08:54:58 -0700 Subject: [PATCH 257/630] Add link to mailing list. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5b27494f..80fcf4a2 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,8 @@ Developer Information * [Compatibility Test Matrix](http://build.clojure.org/job/java.jdbc-test-matrix/) +* [Mailing List](https://groups.google.com/forum/#!forum/clojure-java-jdbc) + * Testing: * Currently by default tests run only against Derby and HSQLDB, the in-process databases. From a89b7d8cd0365afe2cfaea05ae2d3e46a237ad14 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 May 2015 08:56:07 -0700 Subject: [PATCH 258/630] Move mailing list reference to top of README --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 80fcf4a2..b68d08a8 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ For DSLs that are compatible with this library, consider: Formerly known as `clojure.contrib.sql`. -Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). +Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) and there is a dedicated [java.jdbc mailing list](https://groups.google.com/forum/#!forum/clojure-java-jdbc) Important Changes from Earlier Versions ======================================== @@ -97,8 +97,6 @@ Developer Information * [Compatibility Test Matrix](http://build.clojure.org/job/java.jdbc-test-matrix/) -* [Mailing List](https://groups.google.com/forum/#!forum/clojure-java-jdbc) - * Testing: * Currently by default tests run only against Derby and HSQLDB, the in-process databases. From cfe96b1ae61c580d3690cc8f52b115249e457e4d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:18:37 -0700 Subject: [PATCH 259/630] Fix JDBC-108 by reusing local bindings Instead of calling `count` on `rows` and `cols-and-vals` again, use the already calculated `n-*` local bindings. --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c46d9600..288c9712 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -973,7 +973,7 @@ compatibility but it will be removed before a 1.0.0 release." } cols-and-vals (take-while (comp not keyword?) cols-and-vals-etc) n-cols-and-vals (count cols-and-vals) no-cols-and-vals (zero? n-cols-and-vals) - options (drop (+ (count rows) (count cols-and-vals)) clauses) + options (drop (+ n-rows n-cols-and-vals) clauses) {:keys [entities] :or {entities identity}} (apply hash-map options)] (if (zero? n-rows) (if no-cols-and-vals From ffea0332a87ec4100d459ec9533e9619d46fb2c8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:19:41 -0700 Subject: [PATCH 260/630] Whitespace cleanup - remove trailing --- src/main/clojure/clojure/java/jdbc.clj | 53 +++++++++++++------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 288c9712..a01f0d4e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2014 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2008-2015 Sean Corfield, Stephen C. Gilardi. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be @@ -218,7 +218,7 @@ compatibility but it will be removed before a 1.0.0 release." } URI: Parsed JDBC connection string - see below - + String: subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." @@ -234,19 +234,19 @@ compatibility but it will be removed before a 1.0.0 release." } (cond connection connection - + (instance? URI db-spec) (get-connection (parse-properties-uri db-spec)) - + (string? db-spec) (get-connection (URI. (strip-jdbc db-spec))) - + factory (factory (dissoc db-spec :factory)) - + connection-uri (DriverManager/getConnection connection-uri) - + (and subprotocol subname) (let [url (format "jdbc:%s:%s" subprotocol subname) etc (dissoc db-spec :classname :subprotocol :subname) @@ -269,14 +269,14 @@ compatibility but it will be removed before a 1.0.0 release." } etc (dissoc db-spec :dbtype :dbname)] (clojure.lang.RT/loadClassForName (classnames subprotocol)) (DriverManager/getConnection url (as-properties etc))) - + (or (and datasource username password) (and datasource user password)) (.getConnection ^DataSource datasource ^String (or username user) ^String password) - + datasource (.getConnection ^DataSource datasource) - + name (when-available javax.naming.InitialContext @@ -284,7 +284,7 @@ compatibility but it will be removed before a 1.0.0 release." } context (javax.naming.InitialContext. env) ^DataSource datasource (.lookup context ^String name)] (.getConnection datasource))) - + :else (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] (throw (IllegalArgumentException. msg))))) @@ -355,7 +355,7 @@ compatibility but it will be removed before a 1.0.0 release." } Boolean (result-set-read-column [x _2 _3] (if (= true x) true false)) - + nil (result-set-read-column [_1 _2 _3] nil)) @@ -404,19 +404,19 @@ compatibility but it will be removed before a 1.0.0 release." } (seq result)))) (def ^{:private true - :doc "Map friendly :concurrency values to ResultSet constants."} + :doc "Map friendly :concurrency values to ResultSet constants."} result-set-concurrency {:read-only ResultSet/CONCUR_READ_ONLY :updatable ResultSet/CONCUR_UPDATABLE}) (def ^{:private true - :doc "Map friendly :cursors values to ResultSet constants."} + :doc "Map friendly :cursors values to ResultSet constants."} result-set-holdability {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) (def ^{:private true - :doc "Map friendly :type values to ResultSet constants."} + :doc "Map friendly :type values to ResultSet constants."} result-set-type {:forward-only ResultSet/TYPE_FORWARD_ONLY :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE @@ -442,17 +442,17 @@ compatibility but it will be removed before a 1.0.0 release." } (catch Exception _ ;; assume it is unsupported and try basic PreparedStatement: (.prepareStatement con sql))) - + (and result-type concurrency) (if cursors - (.prepareStatement con sql + (.prepareStatement con sql (get result-set-type result-type result-type) (get result-set-concurrency concurrency concurrency) (get result-set-holdability cursors cursors)) - (.prepareStatement con sql + (.prepareStatement con sql (get result-set-type result-type result-type) (get result-set-concurrency concurrency concurrency))) - + :else (.prepareStatement con sql))] (when fetch-size (.setFetchSize stmt fetch-size)) @@ -497,12 +497,12 @@ compatibility but it will be removed before a 1.0.0 release." } "Prints the update counts from a BatchUpdateException to *out*" [^BatchUpdateException exception] (println "Update counts:") - (dorun - (map-indexed - (fn [index count] + (dorun + (map-indexed + (fn [index count] (println (format " Statement %d: %s" index - (get special-counts count count)))) + (get special-counts count count)))) (.getUpdateCounts exception)))) ;; java.jdbc pieces rewritten to not use dynamic bindings @@ -702,7 +702,7 @@ compatibility but it will be removed before a 1.0.0 release." } (.close rs) result) (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: + ;; assume generated keys is unsupported and return counts instead: counts))))] (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] @@ -774,12 +774,12 @@ compatibility but it will be removed before a 1.0.0 release." } "vector" "[sql param*]" (.getName sql-params-class) - (pr-str sql-params))] + (pr-str sql-params))] (throw (IllegalArgumentException. msg)))) (let [special (first sql-params) sql-is-first (string? special) options-are-first (map? special) - sql (cond sql-is-first special + sql (cond sql-is-first special options-are-first (second sql-params)) params (vec (cond sql-is-first (rest sql-params) options-are-first (rest (rest sql-params)) @@ -1073,4 +1073,3 @@ compatibility but it will be removed before a 1.0.0 release." } (println "DEPRECATED: Use with-db-transaction instead of db-transaction.") `(db-transaction* ~(second binding) (^{:once true} fn* [~(first binding)] ~@body))) - From f2f608c501fb2981d87e537a8ea6f6ad0ef8f165 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:22:07 -0700 Subject: [PATCH 261/630] Update CHANGES to include JDBC-108. --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 64ad1d77..a34c0a81 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.3.7 * Update SQLite driver version to 3.8.7 and re-test. +* Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. Changes in 0.3.6 From b326e834f3a9a46000e082d2bf8a67db990a3a2d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:32:15 -0700 Subject: [PATCH 262/630] Change `metadat-result` test to close the `ResultSet`. See JDBC-107 for details. --- src/test/clojure/clojure/java/test_jdbc.clj | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index efffc77d..ccb2306b 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -555,14 +555,16 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (sql/with-db-metadata [metadata db] - (let [table-info (sql/metadata-result (.getTables metadata - nil nil nil - (into-array ["TABLE" "VIEW"])))] - (is (not= [] table-info)) - (is (= "fruit" (-> table-info - first - :table_name - clojure.string/lower-case))))))) + ;; make sure to close the ResultSet + (with-open [table-info-result (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"]))] + (let [table-info (sql/metadata-result table-info-result)] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case)))))))) (defn- returned-key [db k] (condp = (:subprotocol db) From 3eb799d4393b87d78738d6fd418a823726b03eb3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:44:31 -0700 Subject: [PATCH 263/630] Tidy up README Remove "Important Changes from Earlier Versions" section since that is a couple of years old now and the breaking changes are highlighted clearly in the change log section of the README. --- README.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/README.md b/README.md index b68d08a8..befb90f9 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,6 @@ Formerly known as `clojure.contrib.sql`. Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) and there is a dedicated [java.jdbc mailing list](https://groups.google.com/forum/#!forum/clojure-java-jdbc) -Important Changes from Earlier Versions -======================================== - -If you depend on the `clojure.java.jdbc.sql` or `clojure.java.jdbc.ddl` namespaces, which were introduced in 0.3.0-alpha1, you will need to switch to [java-jdbc/dsl](https://github.com/seancorfield/jsql) as those DSLs have been removed from this contrib library as of 0.3.0-beta2, to improve the focus. - -Similarly, if you depend on the older 0.2.3 API, you'll need to switch to `clojure.java.jdbc.deprecated` as the old API was deprecated as part of the 0.3.0 release (alpha1 thru beta1). In order to clean up the documentation and improve the focus of `clojure.java.jdbc`, the old API was moved in 0.3.0-beta2. - Releases and Dependency Information ======================================== @@ -163,7 +156,7 @@ Change Log * Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). * Release 0.3.0-beta2 on 2013-11-24 - * BREAKING CHANGES! + * **BREAKING CHANGES!** * The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL). * The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. From ac74838377aa3936a98fccdeb6d21dd7f31c600b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:54:05 -0700 Subject: [PATCH 264/630] Fix JDBC-106 by removing driver versions from README Provide links to Maven Central instead (and download link for Microsoft SQL Server JDBC driver). --- README.md | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index befb90f9..56da7d0a 100644 --- a/README.md +++ b/README.md @@ -34,24 +34,17 @@ Latest stable release: 0.3.6 0.3.6 ``` -You will also need to add dependencies for the JDBC driver you intend to use. Here are examples of the drivers currently used for testing, -shown as Leiningen dependencies: -```clojure -;; Apache Derby -[org.apache.derby/derby "10.8.1.2"] -;; HSQLDB -[hsqldb/hsqldb "1.8.0.10"] -;; Microsoft SQL Server using the jTDS driver -[net.sourceforge.jtds/jtds "1.2.4"] -;; MySQL -[mysql/mysql-connector-java "5.1.25"] -;; PostgreSQL -[postgresql/postgresql "8.4-702.jdbc4"] -;; SQLite -[org.xerial/sqlite-jdbc "3.8.7"] -``` -For the latest versions, consult the vendor or project websites. clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 4.0 but that -has to be downloaded manually and placed in a Maven repository accessible to your system. For testing, it was installed locally as: +You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: + +* [Apache Derby](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.derby%22%20AND%20a%3A%22derby%22) +* [HSQLDB](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22hsqldb%22%20AND%20a%3A%22hsqldb%22) +* [Microsoft SQL Server jTDS](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.jtds%22%20AND%20a%3A%22jtds%22) +* [MySQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22mysql%22%20AND%20a%3A%22mysql-connector-java%22) +* [PostgreSQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.postgresql%22%20AND%20a%3A%22postgresql%22) +* [SQLite](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.xerial%22%20AND%20a%3A%22sqlite-jdbc%22) + +clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 4.0 but that +has to be [downloaded manually](https://www.microsoft.com/en-us/download/details.aspx?id=11774) and placed in a Maven repository accessible to your system. For testing, it was installed locally as: ```clojure ;; Microsoft SQL Server JDBC4 Driver 4.0 [sqljdbc4/sqljdbc4 "4.0"] From b92d215b66e209fcaa4f9ae64840485e09768928 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 09:56:53 -0700 Subject: [PATCH 265/630] Document JDBC-108 in change log --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index a34c0a81..c70bd18e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,7 @@ Changes coming in 0.3.7 * Update SQLite driver version to 3.8.7 and re-test. * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. +* Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106). * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. Changes in 0.3.6 From 3810907edf1acbd9d99c274032ef75809086a974 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 10:01:46 -0700 Subject: [PATCH 266/630] Prep for 0.3.7 release --- CHANGES.md | 2 +- README.md | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c70bd18e..296b9c6f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.3.7 +Changes in 0.3.7 * Update SQLite driver version to 3.8.7 and re-test. * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. diff --git a/README.md b/README.md index 56da7d0a..318b0518 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.3.6 +Latest stable release: 0.3.7 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.3.6 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.6"] +[org.clojure/java.jdbc "0.3.7"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.6 + 0.3.7 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,12 @@ Developer Information Change Log ==================== +* Release 0.3.7 on 2015-05-18 + * Update SQLite driver version to 3.8.7 and re-test. + * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. + * Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106). + * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. + * Release 0.3.6 on 2014-10-28 * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102). * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101). From 95b1121eb8aa4b239f26e0170d9e2addfdb5c58b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 May 2015 10:07:11 -0700 Subject: [PATCH 267/630] Bump all driver versions for testing. --- CHANGES.md | 2 +- README.md | 2 +- project.clj | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 296b9c6f..aa7da9e5 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,6 @@ Changes in 0.3.7 -* Update SQLite driver version to 3.8.7 and re-test. +* Bump all driver versions in `project.clj` and re-test. * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. * Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106). * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. diff --git a/README.md b/README.md index 318b0518..aa456ca7 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ Change Log ==================== * Release 0.3.7 on 2015-05-18 - * Update SQLite driver version to 3.8.7 and re-test. + * Bump all driver versions in `project.clj` and re-test. * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. * Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106). * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. diff --git a/project.clj b/project.clj index 6b611779..c7365867 100644 --- a/project.clj +++ b/project.clj @@ -7,13 +7,13 @@ :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :dependencies [[org.clojure/clojure "1.7.0-alpha3"] - [mysql/mysql-connector-java "5.1.25"] - [org.apache.derby/derby "10.8.1.2"] + :dependencies [[org.clojure/clojure "1.7.0-beta3"] + [org.apache.derby/derby "10.11.1.1"] [hsqldb "1.8.0.10"] - [postgresql "8.4-702.jdbc4"] - [org.xerial/sqlite-jdbc "3.8.7"] - [net.sourceforge.jtds/jtds "1.2.4"] + [net.sourceforge.jtds/jtds "1.3.1"] + [mysql/mysql-connector-java "5.1.35"] + [org.postgresql/postgresql "9.4-1201-jdbc41"] + [org.xerial/sqlite-jdbc "3.8.10.1"] ;; if you have the MS driver in your local repo ;; [sqljdbc4 "4.0"] ] From e36e6c193cc4ed8be281efc5c16027636b883c3e Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 18 May 2015 12:29:47 -0500 Subject: [PATCH 268/630] [maven-release-plugin] prepare release java.jdbc-0.3.7 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index cf6edc0a..e3fdb476 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.7-SNAPSHOT + 0.3.7 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.3.7 From 3868f8ade4a8ef13ff97b706729ac95664b89de0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 18 May 2015 12:29:47 -0500 Subject: [PATCH 269/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index e3fdb476..dbbfe33d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.7 + 0.3.8-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.3.7 + HEAD From 6282f32b21a6727a31553345326a0aa3c87168ac Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 10 Jul 2015 09:13:51 -0700 Subject: [PATCH 270/630] Clarified pom.xml/project.clj roles Added comments to project.clj clarifying that pom.xml is the "system of record". Also took the opportunity to add 1.8 snapshot and bump 1.7 to stable version for multi-version testing. --- project.clj | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/project.clj b/project.clj index c7365867..d4a18eb5 100644 --- a/project.clj +++ b/project.clj @@ -1,4 +1,8 @@ -(defproject org.clojure/java.jdbc "0.3.7-SNAPSHOT" +;; NOTE: This project.clj file exists purely to make it easier to +;; develop and test java.jdbc locally. The pom.xml file is the +;; "system of record" as far as the project version is concerned. + +(defproject org.clojure/java.jdbc "0.3.8-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" @@ -7,7 +11,12 @@ :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :dependencies [[org.clojure/clojure "1.7.0-beta3"] + :dependencies [[org.clojure/clojure "1.7.0"] + ;; These are just the versions most recently test against + ;; for your own projects, use whatever version is most + ;; appropriate for you. Again, note that this project.clj + ;; file exists for convenience -- the pom.xml file is the + ;; "system of record" as far as dependencies go! [org.apache.derby/derby "10.11.1.1"] [hsqldb "1.8.0.10"] [net.sourceforge.jtds/jtds "1.3.1"] @@ -15,15 +24,16 @@ [org.postgresql/postgresql "9.4-1201-jdbc41"] [org.xerial/sqlite-jdbc "3.8.10.1"] ;; if you have the MS driver in your local repo - ;; [sqljdbc4 "4.0"] + [sqljdbc4 "4.0"] ] :profiles {:1.2 {:dependencies [[org.clojure/clojure "1.2.1"]]} :1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} - :1.7 {:dependencies [[org.clojure/clojure "1.7.0-master-SNAPSHOT"]]} + :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} + :1.8 {:dependencies [[org.clojure/clojure "1.8.0-master-SNAPSHOT"]]} } - :aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6:test,1.7" "test"] - "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6:1.7" "check"]} + :aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6:test,1.7:test,1.8" "test"] + "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6:1.7:1.8" "check"]} :min-lein-version "2.0.0") From 8234f917f8a9d584a3bc4297151e511cdb4acfff Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 22:26:37 -0700 Subject: [PATCH 271/630] Fix JDBC-111 by allowing transaction? to be omitted when PreparedStatement passed --- src/main/clojure/clojure/java/jdbc.clj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a01f0d4e..67ccf62f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -744,7 +744,8 @@ compatibility but it will be removed before a 1.0.0 release." } {:arglists '([db-spec sql & param-groups] [db-spec transaction? sql & param-groups])} [db transaction? & [sql & param-groups :as opts]] - (if (string? transaction?) + (if (or (string? transaction?) + (instance? PreparedStatement transaction?)) (apply db-do-prepared db true transaction? opts) (if-let [^java.sql.Connection con (db-find-connection db)] (if (instance? PreparedStatement sql) From 57b69ff4e0fc94cd1c5af901d467a4f2886e4153 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 22:29:39 -0700 Subject: [PATCH 272/630] Update docs for JDBC-111 --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index aa7da9e5..f4154c94 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.3.8 + +* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. + Changes in 0.3.7 * Bump all driver versions in `project.clj` and re-test. From f3d720e49ab2def1f690da83595204f7a879dd02 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 22:31:18 -0700 Subject: [PATCH 273/630] Update docstring for JDBC-111 --- src/main/clojure/clojure/java/jdbc.clj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 67ccf62f..bdfaf097 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -740,6 +740,7 @@ compatibility but it will be removed before a 1.0.0 release." } "Executes an (optionally parameterized) SQL prepared statement on the open database connection. Each param-group is a seq of values for all of the parameters. transaction? can be omitted and defaults to true. + The sql parameter can either be a SQL string or a PreparedStatement. Return a seq of update counts (one count for each param-group)." {:arglists '([db-spec sql & param-groups] [db-spec transaction? sql & param-groups])} From aac2df50611e8232449fc976e18d08804ba0b2e6 Mon Sep 17 00:00:00 2001 From: Donald Ball Date: Tue, 4 Nov 2014 15:42:54 -0500 Subject: [PATCH 274/630] Ensure that nested transactions don't specify invalid isolation levels Specifically, anything other than what the outermost transaction is in. Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 6 ++++++ src/test/clojure/clojure/java/test_jdbc.clj | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index bdfaf097..57b45c9d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -600,6 +600,12 @@ compatibility but it will be removed before a 1.0.0 release." } (db-transaction* (add-connection db con) func :isolation isolation :read-only? read-only?))) (try + (when (and isolation + (let [^java.sql.Connection con (db-find-connection db)] + (not= (isolation isolation-levels) + (.getTransactionIsolation con)))) + (let [msg "Nested transactions may not have different isolation levels"] + (throw (IllegalStateException. msg)))) (func (inc-level db)) (catch Exception e (throw-non-rte e))))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index ccb2306b..798ad14c 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -535,6 +535,18 @@ (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(deftest test-nested-transactions-check-transaction-isolation-level + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (is (thrown? IllegalStateException + (sql/with-db-transaction [t-conn' t-conn :isolation :serializable] + (sql/insert! t-conn' + :fruit + [:name :appearance] + ["Grape" "yummy"]))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (deftest test-raw-metadata (doseq [db (test-specs)] (create-test-table :fruit db) From 148499b200b220215401ebdbd641460084e0f690 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 22:39:40 -0700 Subject: [PATCH 275/630] Fix JDBC-110 by applying patch and dropping Clojure 1.2 support --- CHANGES.md | 2 ++ project.clj | 5 ++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f4154c94..ea7f9d89 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ Changes coming in 0.3.8 * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. +* Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. +* Drop Clojure 1.2 compatibility. Changes in 0.3.7 diff --git a/project.clj b/project.clj index d4a18eb5..0c6fee87 100644 --- a/project.clj +++ b/project.clj @@ -26,14 +26,13 @@ ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"] ] - :profiles {:1.2 {:dependencies [[org.clojure/clojure "1.2.1"]]} - :1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} + :profiles {:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0-master-SNAPSHOT"]]} } - :aliases {"test-all" ["with-profile" "test,1.2:test,1.3:test,1.4:test,1.5:test,1.6:test,1.7:test,1.8" "test"] + :aliases {"test-all" ["with-profile" "test,1.3:test,1.4:test,1.5:test,1.6:test,1.7:test,1.8" "test"] "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6:1.7:1.8" "check"]} :min-lein-version "2.0.0") From 8f5e8f269a6b336117c2fddac3c4c6e1d0716e09 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 23:02:52 -0700 Subject: [PATCH 276/630] Most of JDBC-109 Defaults PostgreSQL port. Supports more dbtype/dbname. Doesn't test it. Doesn't update CHANGES.md --- src/main/clojure/clojure/java/jdbc.clj | 9 ++++++--- src/test/clojure/clojure/java/test_deprecated.clj | 3 +-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 57b45c9d..1e40be49 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -261,11 +261,14 @@ compatibility but it will be removed before a 1.0.0 release." } "mysql" 3306 "mssql" 1433 "jtds" 1433 + "postgresql" 5432 nil)) db-sep (if (= "mssql" subprotocol) ";DATABASENAME=" "/") - url (str "jdbc:" subprotocol "://" host - (when port (str ":" port)) - db-sep dbname) + url (if (#{"derby" "hsqldb" "sqlite"} subprotocol) + (str "jdbc:" subprotocol ":" dbname) + (str "jdbc:" subprotocol "://" host + (when port (str ":" port)) + db-sep dbname)) etc (dissoc db-spec :dbtype :dbname)] (clojure.lang.RT/loadClassForName (classnames subprotocol)) (DriverManager/getConnection url (as-properties etc))) diff --git a/src/test/clojure/clojure/java/test_deprecated.clj b/src/test/clojure/clojure/java/test_deprecated.clj index f980921c..5763042c 100644 --- a/src/test/clojure/clojure/java/test_deprecated.clj +++ b/src/test/clojure/clojure/java/test_deprecated.clj @@ -101,7 +101,7 @@ "Return a sequence of db-spec maps that should be used for tests" [] (for [db test-databases] - @(ns-resolve 'clojure.java.test-jdbc (symbol (str (name db) "-db"))))) + @(ns-resolve 'clojure.java.test-deprecated (symbol (str (name db) "-db"))))) (defn- clean-up "Attempt to drop any test tables before we start a test." @@ -405,4 +405,3 @@ (is (= :K-W (sql/as-keyword "K_W"))) (is (= :K_W (sql/as-keyword :K_W))) (is (= :k.w (sql/as-keyword :k.w))))) - From 7348a5d7de4575bcc6fd89350c12592bfdd2ad9a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 23:18:09 -0700 Subject: [PATCH 277/630] Update tests to exercise JDBC-109 --- src/test/clojure/clojure/java/test_jdbc.clj | 24 ++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 798ad14c..b514a12c 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -62,15 +62,15 @@ :user "clojure_test" :password "clojure_test"}) -(def derby-db {:subprotocol "derby" - :subname "clojure_test_derby" +(def derby-db {:dbtype "derby" + :dbname "clojure_test_derby" :create true}) -(def hsqldb-db {:subprotocol "hsqldb" - :subname "clojure_test_hsqldb"}) +(def hsqldb-db {:dbtype "hsqldb" + :dbname "clojure_test_hsqldb"}) -(def sqlite-db {:subprotocol "sqlite" - :subname "clojure_test_sqlite"}) +(def sqlite-db {:dbtype "sqlite" + :dbname "clojure_test_sqlite"}) (def postgres-db {:subprotocol "postgresql" :subname "clojure_test" @@ -125,12 +125,12 @@ (defn- mysql? [db] (if (string? db) (re-find #"mysql:" db) - (= "mysql" (:subprotocol db)))) + (= "mysql" (or (:subprotocol db) (:dbtype db))))) (defn- postgres? [db] (if (string? db) (re-find #"postgres" db) - (= "postgresql" (:subprotocol db)))) + (= "postgresql" (or (:subprotocol db) (:dbtype db))))) (defmulti create-test-table "Create a standard test table. Uses db-do-commands. @@ -272,7 +272,7 @@ :fruit {:name "Pomegranate" :appearance "fresh" :cost 585} {:name "Kiwifruit" :grade 93})] - (condp = (:subprotocol db) + (condp = (or (:subprotocol db) (:dbtype db)) nil (when (mysql? db) (is (= '({:generated_key 1} {:generated_key 2}) r))) "postgresql" (is (= 2 (count r))) @@ -579,7 +579,7 @@ clojure.string/lower-case)))))))) (defn- returned-key [db k] - (condp = (:subprotocol db) + (condp = (or (:subprotocol db) (:dbtype db)) "derby" {(keyword "1") nil} "hsqldb" 1 "mysql" {:generated_key k} @@ -592,7 +592,7 @@ k)) (defn- generated-key [db k] - (condp = (:subprotocol db) + (condp = (or (:subprotocol db) (:dbtype db)) "derby" 0 "hsqldb" 0 "jtds:sqlserver" 0 @@ -601,7 +601,7 @@ k)) (defn- float-or-double [db v] - (condp = (:subprotocol db) + (condp = (or (:subprotocol db) (:dbtype db)) "derby" (Float. v) "jtds:sqlserver" (Float. v) "sqlserver" (Float. v) From b26b73d96f47a4f4a0ec39cf72adca36162296e3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 23:22:07 -0700 Subject: [PATCH 278/630] Prep for 0.4.0 release --- CHANGES.md | 3 ++- README.md | 12 +++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index ea7f9d89..7ae24095 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,8 @@ -Changes coming in 0.3.8 +Changes in 0.4.0 * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. * Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. +* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109). * Drop Clojure 1.2 compatibility. Changes in 0.3.7 diff --git a/README.md b/README.md index aa456ca7..921fb285 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.3.7 +Latest stable release: 0.4.0 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.3.7 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.3.7"] +[org.clojure/java.jdbc "0.4.0"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.3.7 + 0.4.0 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,12 @@ Developer Information Change Log ==================== +* Release 0.4.0 on 2015-07-26 + * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. + * Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. + * Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109). + * Drop Clojure 1.2 compatibility. + * Release 0.3.7 on 2015-05-18 * Bump all driver versions in `project.clj` and re-test. * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. From dea08da009758b4d18dba965c6f464afa5f00c70 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 27 Jul 2015 01:23:02 -0500 Subject: [PATCH 279/630] [maven-release-plugin] prepare release java.jdbc-0.4.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index dbbfe33d..cd44643f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.8-SNAPSHOT + 0.4.0 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.4.0 From 919a22959e5a0384e2064e41ed185ae5c891f845 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 27 Jul 2015 01:23:03 -0500 Subject: [PATCH 280/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index cd44643f..2b6c9273 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.4.0 + 0.3.9-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.4.0 + HEAD From c1d55ad68341ba7690d5b8f4b877b0421fc116cb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 23:25:12 -0700 Subject: [PATCH 281/630] Bump project.clj to 0.4.1-SNAPSHOT --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index 0c6fee87..274dfd49 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.3.8-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.4.1-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 40446c23ca751115be5bcfae424b3a964c769555 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 27 Jul 2015 01:39:51 -0500 Subject: [PATCH 282/630] [maven-release-plugin] prepare release java.jdbc-0.4.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2b6c9273..10ae9cfe 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.3.9-SNAPSHOT + 0.4.1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.4.1 From 65e32658bf67b8da86ca1175ce5c44fbdc7e828f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 27 Jul 2015 01:39:52 -0500 Subject: [PATCH 283/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 10ae9cfe..7d9386c7 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.4.1 + 0.4.2-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.4.1 + HEAD From 7c77db9e9c3b0231471a88d811e8296bd6c45404 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 23:41:51 -0700 Subject: [PATCH 284/630] 0.4.0 / 0.4.1 are identical I forgot to update the next development version so I had to jump a point release to fix it in Maven :( --- CHANGES.md | 2 +- README.md | 2 +- project.clj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 7ae24095..971e2814 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes in 0.4.0 +Changes in 0.4.0 / 0.4.1 * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. * Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. diff --git a/README.md b/README.md index 921fb285..ccb0a6fd 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ Developer Information Change Log ==================== -* Release 0.4.0 on 2015-07-26 +* Release 0.4.0 / 0.4.1 on 2015-07-26 * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. * Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. * Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109). diff --git a/project.clj b/project.clj index 274dfd49..474d05f6 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.4.1-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.4.2-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 33d37359b0b2488ccfaf44f9bd852616180bbb62 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 Jul 2015 23:45:25 -0700 Subject: [PATCH 285/630] Fix current version in README --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ccb0a6fd..cc8b3cc0 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.4.0 +Latest stable release: 0.4.1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.4.0 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.4.0"] +[org.clojure/java.jdbc "0.4.1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.4.0 + 0.4.1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: From 2210314688079e157df82010e1104be960245dfa Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Aug 2015 19:42:31 -0700 Subject: [PATCH 286/630] JDBC-107 add metadata-query macro to make usage easier Adds macro plus two tests that can act as examples. --- CHANGES.md | 4 ++++ src/main/clojure/clojure/java/jdbc.clj | 13 +++++++++++ src/test/clojure/clojure/java/test_jdbc.clj | 24 +++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 971e2814..e0b8a569 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.4.2 + +* Add `metadata-query` macro to make metadata query / results easier to work with [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). + Changes in 0.4.0 / 0.4.1 * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1e40be49..1e893de1 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -666,6 +666,19 @@ compatibility but it will be removed before a 1.0.0 release." } (result-set-seq rs-or-value :identifiers identifiers :as-arrays? as-arrays?)) rs-or-value))) +(defmacro metadata-query + "Given a Java expression that extracts metadata (in the context of with-db-metadata), + and additional optional arguments like metadata-result, manage the connection for a + single metadata-based query. Example usage: + + (with-db-metadata [meta db-spec] + (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) + :row-fn ... + :result-set-fn ...))" + [meta-query & opt-args] + `(with-open [rs# ~meta-query] + (metadata-result rs# ~@opt-args))) + (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index b514a12c..69d4ab71 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -563,6 +563,30 @@ :table_name clojure.string/lower-case)))))) +(deftest test-metadata-managed + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-metadata [metadata db] + (let [table-info (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case))))))) + +(deftest test-metadata-managed-computed + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= "fruit" + (sql/with-db-metadata [metadata db] + (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])) + :row-fn (comp clojure.string/lower-case :table_name) + :result-set-fn first)))))) + (deftest test-metadata (doseq [db (test-specs)] (create-test-table :fruit db) From 410cbdea52bec5ec7e7145f4cd2e51351ab468f6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Aug 2015 20:06:47 -0700 Subject: [PATCH 287/630] JDBC-104 prepare-statement :return-keys can be vector of column names --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 8 ++++++-- src/test/clojure/clojure/java/test_jdbc.clj | 17 +++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index e0b8a569..03a4a145 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.4.2 * Add `metadata-query` macro to make metadata query / results easier to work with [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). +* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). Changes in 0.4.0 / 0.4.1 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1e893de1..08366ae4 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -428,7 +428,9 @@ compatibility but it will be removed before a 1.0.0 release." } (defn prepare-statement "Create a prepared statement from a connection, a SQL string and an optional list of parameters: - :return-keys true | false - default false + :return-keys truthy | nil - default nil + for some drivers, this may be a vector of column names to identify + the generated keys to return, otherwise it should just be true :result-type :forward-only | :scroll-insensitive | :scroll-sensitive :concurrency :read-only | :updatable :cursors @@ -441,7 +443,9 @@ compatibility but it will be removed before a 1.0.0 release." } (let [^PreparedStatement stmt (cond return-keys (try - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS) + (if (vector? return-keys) + (.prepareStatement con sql (into-array String return-keys)) + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) (catch Exception _ ;; assume it is unsupported and try basic PreparedStatement: (.prepareStatement con sql))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 69d4ab71..01842cd2 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -312,6 +312,23 @@ (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] :result-set-fn (comp :name first)))))) +(deftest execute-with-prepared-statement-return-keys + (doseq [db (test-specs)] + ;; Derby does not have auto-generated id column which we're testing here + (when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (create-test-table :fruit db) + (sql/with-db-connection [conn db] + (let [connection (:connection conn) + prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )") + :return-keys ["id"])] + + (sql/execute! db [prepared-statement "Apple" "Green" 75]) + (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + :result-set-fn (comp :name first))))))) + (deftest test-update-values (doseq [db (test-specs)] (create-test-table :fruit db) From 3d39403cf1d6a9a79326a8e724bc7b1f610d134f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Aug 2015 20:53:38 -0700 Subject: [PATCH 288/630] Ignore test database files --- .gitignore | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 5a1aaeb2..75d90c3f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,15 +2,13 @@ .classpath .project .settings +/.lein-failures +/.lein-repl-history +/.nrepl-port +/clojure_test_* bin classes -clojure_test_derby -clojure_test_hsqldb.* derby.log +settings.xml target test-all.sh -settings.xml -/clojure_test_sqlite -/.lein-failures -/.nrepl-port -/.lein-repl-history From 59872ac51fd9f9167e7fd8fdb3663facee9bd336 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Aug 2015 20:54:29 -0700 Subject: [PATCH 289/630] Add H2 to the tests; update all libraries. Note: HSQLDB 2.x no longer returns auto-generated row IDs automatically. The new return keys test with column names does work, however. --- pom.xml | 20 ++++--- project.clj | 7 +-- src/main/clojure/clojure/java/jdbc.clj | 2 +- .../clojure/clojure/java/jdbc/deprecated.clj | 53 ++++++++++--------- .../clojure/clojure/java/test_deprecated.clj | 8 ++- src/test/clojure/clojure/java/test_jdbc.clj | 13 +++-- 6 files changed, 61 insertions(+), 42 deletions(-) diff --git a/pom.xml b/pom.xml index 7d9386c7..fa9efc79 100644 --- a/pom.xml +++ b/pom.xml @@ -29,7 +29,7 @@ mysql mysql-connector-java - 5.1.25 + 5.1.36 test @@ -39,27 +39,33 @@ test - hsqldb + org.hsqldb hsqldb - 1.8.0.10 + 2.3.3 test - postgresql + com.h2database + h2 + 1.4.188 + test + + + org.postgresql postgresql - 8.4-702.jdbc4 + 9.4-1201-jdbc41 test org.xerial sqlite-jdbc - 3.8.7 + 3.8.11.1 test net.sourceforge.jtds jtds - 1.2.4 + 1.3.1 test diff --git a/project.clj b/project.clj index 474d05f6..089e2937 100644 --- a/project.clj +++ b/project.clj @@ -18,11 +18,12 @@ ;; file exists for convenience -- the pom.xml file is the ;; "system of record" as far as dependencies go! [org.apache.derby/derby "10.11.1.1"] - [hsqldb "1.8.0.10"] + [org.hsqldb/hsqldb "2.3.3"] + [com.h2database/h2 "1.4.188"] [net.sourceforge.jtds/jtds "1.3.1"] - [mysql/mysql-connector-java "5.1.35"] + [mysql/mysql-connector-java "5.1.36"] [org.postgresql/postgresql "9.4-1201-jdbc41"] - [org.xerial/sqlite-jdbc "3.8.10.1"] + [org.xerial/sqlite-jdbc "3.8.11.1"] ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"] ] diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 08366ae4..853b1e17 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -264,7 +264,7 @@ compatibility but it will be removed before a 1.0.0 release." } "postgresql" 5432 nil)) db-sep (if (= "mssql" subprotocol) ";DATABASENAME=" "/") - url (if (#{"derby" "hsqldb" "sqlite"} subprotocol) + url (if (#{"derby" "hsqldb" "h2" "sqlite"} subprotocol) (str "jdbc:" subprotocol ":" dbname) (str "jdbc:" subprotocol "://" host (when port (str ":" port)) diff --git a/src/main/clojure/clojure/java/jdbc/deprecated.clj b/src/main/clojure/clojure/java/jdbc/deprecated.clj index e2b6ec93..dc02d736 100644 --- a/src/main/clojure/clojure/java/jdbc/deprecated.clj +++ b/src/main/clojure/clojure/java/jdbc/deprecated.clj @@ -51,7 +51,7 @@ generated keys are returned (as a map)." } (def ^{:private true :dynamic true :doc "The default entity naming strategy is to do nothing."} - *as-str* + *as-str* identity) (def ^{:private true :dynamic true @@ -117,6 +117,7 @@ generated keys are returned (as a map)." } "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" "derby" "org.apache.derby.jdbc.EmbeddedDriver" "hsqldb" "org.hsqldb.jdbcDriver" + "h2" "org.h2.Driver" "sqlite" "org.sqlite.JDBC"}) (def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols @@ -164,35 +165,35 @@ generated keys are returned (as a map)." } (cond (instance? URI db-spec) (get-connection (parse-properties-uri db-spec)) - + (string? db-spec) (get-connection (URI. (strip-jdbc db-spec))) - + factory (factory (dissoc db-spec :factory)) - + connection-uri (DriverManager/getConnection connection-uri) - + (and subprotocol subname) (let [url (format "jdbc:%s:%s" subprotocol subname) etc (dissoc db-spec :classname :subprotocol :subname) classname (or classname (classnames subprotocol))] (clojure.lang.RT/loadClassForName classname) (DriverManager/getConnection url (as-properties etc))) - + (and datasource username password) (.getConnection ^DataSource datasource ^String username ^String password) - + datasource (.getConnection ^DataSource datasource) - + name (let [env (and environment (Hashtable. ^Map environment)) context (InitialContext. env) ^DataSource datasource (.lookup context ^String name)] (.getConnection datasource)) - + :else (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] (throw (IllegalArgumentException. msg))))) @@ -252,20 +253,20 @@ generated keys are returned (as a map)." } (str q x q))) (defn as-named-identifier - "Given a naming strategy and a keyword, return the keyword as a string using the + "Given a naming strategy and a keyword, return the keyword as a string using the entity naming strategy. Given a naming strategy and a string, return the string as-is. - The naming strategy should either be a function (the entity naming strategy) or + The naming strategy should either be a function (the entity naming strategy) or a map containing :entity and/or :keyword keys which provide the entity naming strategy and/or keyword naming strategy respectively." [naming-strategy x] (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) (defn as-named-keyword - "Given a naming strategy and a string, return the string as a keyword using the + "Given a naming strategy and a string, return the string as a keyword using the keyword naming strategy. Given a naming strategy and a keyword, return the keyword as-is. - The naming strategy should either be a function (the entity naming strategy) or + The naming strategy should either be a function (the entity naming strategy) or a map containing :entity and/or :keyword keys which provide the entity naming strategy and/or keyword naming strategy respectively. Note that providing a single function will cause the default keyword naming @@ -336,7 +337,7 @@ generated keys are returned (as a map)." } URI: Parsed JDBC connection string - see below - + String: subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." @@ -435,19 +436,19 @@ generated keys are returned (as a map)." } (execute-batch stmt)))) (def ^{:private true - :doc "Map friendly :concurrency values to ResultSet constants."} + :doc "Map friendly :concurrency values to ResultSet constants."} result-set-concurrency {:read-only ResultSet/CONCUR_READ_ONLY :updatable ResultSet/CONCUR_UPDATABLE}) (def ^{:private true - :doc "Map friendly :cursors values to ResultSet constants."} + :doc "Map friendly :cursors values to ResultSet constants."} result-set-holdability {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) (def ^{:private true - :doc "Map friendly :type values to ResultSet constants."} + :doc "Map friendly :type values to ResultSet constants."} result-set-type {:forward-only ResultSet/TYPE_FORWARD_ONLY :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE @@ -469,11 +470,11 @@ generated keys are returned (as a map)." } ;; assume it is unsupported and try basic PreparedStatement: (.prepareStatement con sql))) (and result-type concurrency) (if cursors - (.prepareStatement con sql + (.prepareStatement con sql (result-type result-set-type) (concurrency result-set-concurrency) (cursors result-set-holdability)) - (.prepareStatement con sql + (.prepareStatement con sql (result-type result-set-type) (concurrency result-set-concurrency))) :else (.prepareStatement con sql))] @@ -559,7 +560,7 @@ generated keys are returned (as a map)." } (.close rs) result) (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: + ;; assume generated keys is unsupported and return counts instead: counts))))))) (defn insert-values @@ -661,12 +662,12 @@ generated keys are returned (as a map)." } "vector" "[sql param*]" (.getName sql-params-class) - (pr-str sql-params))] + (pr-str sql-params))] (throw (IllegalArgumentException. msg)))) (let [special (first sql-params) sql-is-first (string? special) options-are-first (map? special) - sql (cond sql-is-first special + sql (cond sql-is-first special options-are-first (second sql-params)) params (vec (cond sql-is-first (rest sql-params) options-are-first (rest (rest sql-params)) @@ -719,10 +720,10 @@ generated keys are returned (as a map)." } "Prints the update counts from a BatchUpdateException to *out*" [^BatchUpdateException exception] (println "Update counts:") - (dorun - (map-indexed - (fn [index count] + (dorun + (map-indexed + (fn [index count] (println (format " Statement %d: %s" index - (get special-counts count count)))) + (get special-counts count count)))) (.getUpdateCounts exception)))) diff --git a/src/test/clojure/clojure/java/test_deprecated.clj b/src/test/clojure/clojure/java/test_deprecated.clj index 5763042c..cfa67d6e 100644 --- a/src/test/clojure/clojure/java/test_deprecated.clj +++ b/src/test/clojure/clojure/java/test_deprecated.clj @@ -31,7 +31,7 @@ (if-let [dbs (System/getenv "TEST_DBS")] (map keyword (.split dbs ",")) ;; enable more by default once the build server is equipped? - [:derby :hsqldb :sqlite])) + [:derby :hsqldb :h2 :sqlite])) ;; MS SQL Server requires more specialized configuration: (def mssql-host @@ -69,6 +69,9 @@ (def hsqldb-db {:subprotocol "hsqldb" :subname "clojure_test_hsqldb"}) +(def h2-db {:subprotocol "h2" + :subname "./clojure_test_h2"}) + (def sqlite-db {:subprotocol "sqlite" :subname "clojure_test_sqlite"}) @@ -227,7 +230,8 @@ "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) - "hsqldb" (is (= '(1 1) r)) + "hsqldb" (is (= '(nil nil) r)) + "h2" (is (= '(nil nil) r)) "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} {(keyword "last_insert_rowid()") 2}) r)) "derby" (is (= '({:1 nil} {:1 nil}) r)))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 01842cd2..bf896217 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -31,7 +31,7 @@ (if-let [dbs (System/getenv "TEST_DBS")] (map keyword (.split dbs ",")) ;; enable more by default once the build server is equipped? - [:derby :hsqldb :sqlite])) + [:derby :hsqldb :h2 :sqlite])) ;; MS SQL Server requires more specialized configuration: (def mssql-host @@ -69,6 +69,9 @@ (def hsqldb-db {:dbtype "hsqldb" :dbname "clojure_test_hsqldb"}) +(def h2-db {:dbtype "h2" + :dbname "./clojure_test_h2"}) + (def sqlite-db {:dbtype "sqlite" :dbname "clojure_test_sqlite"}) @@ -279,7 +282,8 @@ "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) - "hsqldb" (is (= '(1 1) r)) + "hsqldb" (is (= '(nil nil) r)) + "h2" (is (= '(nil nil) r)) "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} {(keyword "last_insert_rowid()") 2}) r)) "derby" (is (= (list {(keyword "1") nil} {(keyword "1") nil}) r)))) @@ -622,7 +626,8 @@ (defn- returned-key [db k] (condp = (or (:subprotocol db) (:dbtype db)) "derby" {(keyword "1") nil} - "hsqldb" 1 + "hsqldb" nil + "h2" nil "mysql" {:generated_key k} nil (if (mysql? db) ; string-based tests {:generated_key k} @@ -636,6 +641,7 @@ (condp = (or (:subprotocol db) (:dbtype db)) "derby" 0 "hsqldb" 0 + "h2" 0 "jtds:sqlserver" 0 "sqlserver" 0 "sqlite" 0 @@ -644,6 +650,7 @@ (defn- float-or-double [db v] (condp = (or (:subprotocol db) (:dbtype db)) "derby" (Float. v) + "h2" (Float. v) "jtds:sqlserver" (Float. v) "sqlserver" (Float. v) "postgresql" (Float. v) From 8e0233ae55e5ee1f4a0245d6bab51cb4cc0c463f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Aug 2015 21:01:12 -0700 Subject: [PATCH 290/630] Note H2 support in CHANGES --- CHANGES.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 03a4a145..74a7c0c2 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,8 @@ Changes coming in 0.4.2 -* Add `metadata-query` macro to make metadata query / results easier to work with [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). -* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). +* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). +* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). +* Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91). Changes in 0.4.0 / 0.4.1 From 772a58b03c83446717f4114b726848dee920a8fc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 26 Aug 2015 21:11:11 -0700 Subject: [PATCH 291/630] JDBC-91 clarify docstrings Updated docstrings for db-do-commands, query, and execute! to be explicit about which JDBC method is used behind the scenes so it is easier to figure out how to do certain SQL things! --- CHANGES.md | 2 +- src/main/clojure/clojure/java/jdbc.clj | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 74a7c0c2..ee103457 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,7 +2,7 @@ Changes coming in 0.4.2 * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). -* Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91). +* Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. Changes in 0.4.0 / 0.4.1 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 853b1e17..79cda79f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -686,7 +686,8 @@ compatibility but it will be removed before a 1.0.0 release." } (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it - defaults to true." + defaults to true. + Uses executeBatch. This may affect what SQL you can run via db-do-commands." {:arglists '([db-spec sql-command & sql-commands] [db-spec transaction? sql-command & sql-commands])} [db transaction? & commands] @@ -790,7 +791,8 @@ compatibility but it will be removed before a 1.0.0 release." } (the PreparedStatement already contains the SQL query) [options sql & params] - options and a SQL query for creating a PreparedStatement, followed by any parameters it needs - See prepare-statement for supported options." + See prepare-statement for supported options. + Uses executeQuery. This may affect what SQL you can run via query." {:arglists '([db-spec [sql-string & params] func] [db-spec [stmt & params] func] [db-spec [options-map sql-string & params] func])} @@ -869,7 +871,9 @@ compatibility but it will be removed before a 1.0.0 release." } (defn execute! "Given a database connection and a vector containing SQL and optional parameters, perform a general (non-select) SQL operation. The optional keyword argument specifies - whether to run the operation in a transaction or not (default true)." + whether to run the operation in a transaction or not (default true). + If there are no parameters specified, executeUpdate will be used, otherwise + executeBatch will be used. This may affect what SQL you can run via execute!" {:arglists '([db-spec [sql & params] :multi? false :transaction? true] [db-spec [sql & param-groups] :multi? true :transaction? true])} [db sql-params & {:keys [transaction? multi?] From 88dc40b50cc568366e2451ae085ebc19c619c6a3 Mon Sep 17 00:00:00 2001 From: Michael Blume Date: Tue, 15 Sep 2015 16:16:04 -0700 Subject: [PATCH 292/630] JDBC-112 avoid reflection on .prepareStatement Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 79cda79f..d8497a5c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -425,6 +425,10 @@ compatibility but it will be removed before a 1.0.0 release." } :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) +(defn ^{:tag (class (into-array String []))} string-array + [return-keys] + (into-array String return-keys)) + (defn prepare-statement "Create a prepared statement from a connection, a SQL string and an optional list of parameters: @@ -444,7 +448,7 @@ compatibility but it will be removed before a 1.0.0 release." } stmt (cond return-keys (try (if (vector? return-keys) - (.prepareStatement con sql (into-array String return-keys)) + (.prepareStatement con sql (string-array return-keys)) (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) (catch Exception _ ;; assume it is unsupported and try basic PreparedStatement: From e91774e924bd5540fea43adfa8a5fbacc1baedfd Mon Sep 17 00:00:00 2001 From: Michael Blume Date: Tue, 15 Sep 2015 16:17:29 -0700 Subject: [PATCH 293/630] JDBC-113 remove redundant type hints because db-find-connection and get-connection have their return types hinted, the compiler can type these locals without assistance. Signed-off-by: Sean Corfield --- src/main/clojure/clojure/java/jdbc.clj | 30 +++++++++++++------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d8497a5c..9cbb8708 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -580,7 +580,7 @@ compatibility but it will be removed before a 1.0.0 release." } The read-only? option puts the transaction in readonly mode (if supported)." [db func & {:keys [isolation read-only?]}] (if (zero? (get-level db)) - (if-let [^java.sql.Connection con (db-find-connection db)] + (if-let [con (db-find-connection db)] (let [nested-db (inc-level db) auto-commit (.getAutoCommit con) old-isolation (.getTransactionIsolation con) @@ -607,12 +607,12 @@ compatibility but it will be removed before a 1.0.0 release." } (.setTransactionIsolation con old-isolation)) (when read-only? (.setReadOnly con old-readonly)))))) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (db-transaction* (add-connection db con) func :isolation isolation :read-only? read-only?))) (try (when (and isolation - (let [^java.sql.Connection con (db-find-connection db)] + (let [con (db-find-connection db)] (not= (isolation isolation-levels) (.getTransactionIsolation con)))) (let [msg "Nested transactions may not have different isolation levels"] @@ -641,7 +641,7 @@ compatibility but it will be removed before a 1.0.0 release." } ... con-db ...)" [binding & body] `(let [db-spec# ~(second binding)] - (with-open [^java.sql.Connection con# (get-connection db-spec#)] + (with-open [con# (get-connection db-spec#)] (let [~(first binding) (add-connection db-spec# con#)] ~@body)))) @@ -652,7 +652,7 @@ compatibility but it will be removed before a 1.0.0 release." } (with-db-metadata [md db-spec] ... md ...)" [binding & body] - `(with-open [^java.sql.Connection con# (get-connection ~(second binding))] + `(with-open [con# (get-connection ~(second binding))] (let [~(first binding) (.getMetaData con#)] ~@body))) @@ -697,7 +697,7 @@ compatibility but it will be removed before a 1.0.0 release." } [db transaction? & commands] (if (string? transaction?) (apply db-do-commands db true transaction? commands) - (if-let [^java.sql.Connection con (db-find-connection db)] + (if-let [con (db-find-connection db)] (with-open [^Statement stmt (.createStatement con)] (doseq [^String cmd commands] (.addBatch stmt cmd)) @@ -708,7 +708,7 @@ compatibility but it will be removed before a 1.0.0 release." } (execute-batch stmt) (catch Exception e (throw-non-rte e))))) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (apply db-do-commands (add-connection db con) transaction? commands))))) (defn db-do-prepared-return-keys @@ -719,7 +719,7 @@ compatibility but it will be removed before a 1.0.0 release." } ([db sql param-group] (db-do-prepared-return-keys db true sql param-group)) ([db transaction? sql param-group] - (if-let [^java.sql.Connection con (db-find-connection db)] + (if-let [con (db-find-connection db)] (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] ((or (:set-parameters db) set-parameters) stmt param-group) (let [exec-and-return-keys @@ -742,7 +742,7 @@ compatibility but it will be removed before a 1.0.0 release." } (exec-and-return-keys) (catch Exception e (throw-non-rte e)))))) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) (defn- db-do-execute-prepared-statement @@ -779,12 +779,12 @@ compatibility but it will be removed before a 1.0.0 release." } (if (or (string? transaction?) (instance? PreparedStatement transaction?)) (apply db-do-prepared db true transaction? opts) - (if-let [^java.sql.Connection con (db-find-connection db)] + (if-let [con (db-find-connection db)] (if (instance? PreparedStatement sql) (db-do-execute-prepared-statement db sql param-groups transaction?) (with-open [^PreparedStatement stmt (prepare-statement con sql)] (db-do-execute-prepared-statement db stmt param-groups transaction?))) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (apply db-do-prepared (add-connection db con) transaction? sql param-groups))))) (defn db-query-with-resultset @@ -826,10 +826,10 @@ compatibility but it will be removed before a 1.0.0 release." } (if (instance? PreparedStatement special) (let [^PreparedStatement stmt special] (run-query-with-params stmt)) - (if-let [^java.sql.Connection con (db-find-connection db)] + (if-let [con (db-find-connection db)] (with-open [^PreparedStatement stmt (apply prepare-statement con sql prepare-args)] (run-query-with-params stmt)) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (with-open [^PreparedStatement stmt (apply prepare-statement con sql prepare-args)] (run-query-with-params stmt))))))) @@ -892,7 +892,7 @@ compatibility but it will be removed before a 1.0.0 release." } (db-do-prepared db transaction? (first sql-params)))))] (if-let [con (db-find-connection db)] (execute-helper db) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (execute-helper (add-connection db con)))))) (defn- table-str @@ -1035,7 +1035,7 @@ compatibility but it will be removed before a 1.0.0 release." } stmts (apply insert-sql table maps-or-cols-and-values-etc)] (if-let [con (db-find-connection db)] (insert-helper db transaction? stmts) - (with-open [^java.sql.Connection con (get-connection db)] + (with-open [con (get-connection db)] (insert-helper (add-connection db con) transaction? stmts))))) (defn- update-sql From 6f5b594e04268ccc6c02065dc597c9f93712f133 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 15 Sep 2015 17:43:57 -0700 Subject: [PATCH 294/630] Update changelog/readme for 0.4.2 --- CHANGES.md | 4 +++- README.md | 13 ++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index ee103457..c32eba09 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,7 @@ -Changes coming in 0.4.2 +Changes in 0.4.2 +* Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. +* Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume. * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). * Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. diff --git a/README.md b/README.md index cc8b3cc0..ca16d433 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.4.1 +Latest stable release: 0.4.2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.4.1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.4.1"] +[org.clojure/java.jdbc "0.4.2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.4.1 + 0.4.2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,13 @@ Developer Information Change Log ==================== +* Release 0.4.2 on 2015-09-15 + * Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. + * Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume. + * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). + * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). + * Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. + * Release 0.4.0 / 0.4.1 on 2015-07-26 * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. * Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. From 8db4568c850b1b4e2d39900338ad749174d6e69a Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 15 Sep 2015 20:16:44 -0500 Subject: [PATCH 295/630] [maven-release-plugin] prepare release java.jdbc-0.4.2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index fa9efc79..2ca035c4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.4.2-SNAPSHOT + 0.4.2 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.4.2 From 5d441f7467c5a5d7692fe987b316393532185f5e Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 15 Sep 2015 20:16:44 -0500 Subject: [PATCH 296/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2ca035c4..66b75f9b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.4.2 + 0.4.3-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.4.2 + HEAD From aab5e56456f4b286f82fd6a461f1ee1305d7882f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 23 Nov 2015 15:11:19 -0800 Subject: [PATCH 297/630] Update project.clj Correct version in (shadow) project.clj file. --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index 089e2937..d685eb0c 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.4.2-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.4.3-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 4842f2951a421e5ea3c4cfa805ed97780b426393 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 23 Nov 2015 15:48:18 -0800 Subject: [PATCH 298/630] Address JDBC-114 by no longer unwrapping exceptions This was introduced for CLJ-855 which happened in Clojure 1.3.0 and was fixed in 1.4.0. We'll just drop support for 1.3.0 at this point. --- src/main/clojure/clojure/java/jdbc.clj | 38 ++++----------------- src/test/clojure/clojure/java/test_jdbc.clj | 14 ++++++-- 2 files changed, 19 insertions(+), 33 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9cbb8708..a37123cf 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -530,16 +530,6 @@ compatibility but it will be removed before a 1.0.0 release." } (or (db-find-connection db) (throw (Exception. "no current database connection")))) -(defn- throw-non-rte - "This ugliness makes it easier to catch SQLException objects - rather than something wrapped in a RuntimeException which - can really obscure your code when working with JDBC from - Clojure... :(" - [^Throwable ex] - (cond (instance? java.sql.SQLException ex) (throw ex) - (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) - :else (throw ex))) - (defn db-set-rollback-only! "Marks the outermost transaction such that it will rollback rather than commit when complete" @@ -599,7 +589,7 @@ compatibility but it will be removed before a 1.0.0 release." } result) (catch Throwable t (.rollback con) - (throw-non-rte t)) + (throw t)) (finally (db-unset-rollback-only! nested-db) (.setAutoCommit con auto-commit) @@ -610,16 +600,14 @@ compatibility but it will be removed before a 1.0.0 release." } (with-open [con (get-connection db)] (db-transaction* (add-connection db con) func :isolation isolation :read-only? read-only?))) - (try + (do (when (and isolation (let [con (db-find-connection db)] (not= (isolation isolation-levels) (.getTransactionIsolation con)))) (let [msg "Nested transactions may not have different isolation levels"] (throw (IllegalStateException. msg)))) - (func (inc-level db)) - (catch Exception e - (throw-non-rte e))))) + (func (inc-level db))))) (defmacro with-db-transaction "Evaluates body in the context of a transaction on the specified database connection. @@ -704,10 +692,7 @@ compatibility but it will be removed before a 1.0.0 release." } (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (execute-batch stmt)) - (try - (execute-batch stmt) - (catch Exception e - (throw-non-rte e))))) + (execute-batch stmt))) (with-open [con (get-connection db)] (apply db-do-commands (add-connection db con) transaction? commands))))) @@ -738,10 +723,7 @@ compatibility but it will be removed before a 1.0.0 release." } (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (exec-and-return-keys)) - (try - (exec-and-return-keys) - (catch Exception e - (throw-non-rte e)))))) + (exec-and-return-keys)))) (with-open [con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) @@ -751,10 +733,7 @@ compatibility but it will be removed before a 1.0.0 release." } (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (vector (.executeUpdate stmt))) - (try - (vector (.executeUpdate stmt)) - (catch Exception e - (throw-non-rte e)))) + (vector (.executeUpdate stmt))) (do (doseq [param-group param-groups] ((or (:set-parameters db) set-parameters) stmt param-group) @@ -762,10 +741,7 @@ compatibility but it will be removed before a 1.0.0 release." } (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (execute-batch stmt)) - (try - (execute-batch stmt) - (catch Exception e - (throw-non-rte e))))))) + (execute-batch stmt))))) (defn db-do-prepared "Executes an (optionally parameterized) SQL prepared statement on the diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index bf896217..b70c5254 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -412,6 +412,14 @@ ["name=?" "Apple"]) (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) +(defn- file-not-found-exception-via-reflection + "In Clojure 1.3.0 this caused a wrapped exception and we introduced throw-non-rte + to workaround that. This was fixed in 1.4.0 but we never removed the workaround. + Added this hack from the mailing list specifically to test the exception handling + so that we can verify only Clojure 1.3.0 fails the tests and drop support for it." + [f] + (java.io.FileReader. f)) + (deftest test-partial-exception (doseq [db (test-specs)] (create-test-table :fruit db) @@ -423,9 +431,11 @@ ["Grape" "yummy"] ["Pear" "bruised"]) (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) - (throw (Exception. "deliberate exception"))) + (file-not-found-exception-via-reflection "/etc/password_no_such_file")) + (catch java.io.FileNotFoundException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))) (catch Exception _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) + (is false "Unexpected exception encountered (not wrapped?)."))))) (deftest test-partial-exception-with-isolation (doseq [db (test-specs)] From 990928cb005b0665f8c9c90dadf3040f4295d321 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 23 Nov 2015 15:55:48 -0800 Subject: [PATCH 299/630] Bump 0.4.3 -> 0.5.0 snapshot version --- CHANGES.md | 5 +++++ pom.xml | 2 +- project.clj | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c32eba09..cb146274 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes coming in 0.5.0 + +* Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). +* Drop Clojure 1.3 compatibility. + Changes in 0.4.2 * Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. diff --git a/pom.xml b/pom.xml index 66b75f9b..c1cc7d5c 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.4.3-SNAPSHOT + 0.5.0-SNAPSHOT ${project.artifactId} diff --git a/project.clj b/project.clj index d685eb0c..5e5286e2 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.4.3-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.5.0-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 2d761e352c3ec25c852405866e373cd1b618e79d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:30:20 -0700 Subject: [PATCH 300/630] Improve generated keys fallback JDBC-115 --- src/main/clojure/clojure/java/jdbc.clj | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a37123cf..f00621b5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -448,7 +448,11 @@ compatibility but it will be removed before a 1.0.0 release." } stmt (cond return-keys (try (if (vector? return-keys) - (.prepareStatement con sql (string-array return-keys)) + (try + (.prepareStatement con sql (string-array return-keys)) + (catch Exception _ + ;; assume it is unsupported and try regular generated keys: + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) (catch Exception _ ;; assume it is unsupported and try basic PreparedStatement: From 2c8cd816b259c88d513abe378380fa1c980cdcc2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:30:47 -0700 Subject: [PATCH 301/630] Update testing project.clj Drop 1.3, add 1.8 stable, add 1.9 master for testing --- project.clj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/project.clj b/project.clj index 5e5286e2..85c54432 100644 --- a/project.clj +++ b/project.clj @@ -27,13 +27,13 @@ ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"] ] - :profiles {:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} - :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} + :profiles {:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} - :1.8 {:dependencies [[org.clojure/clojure "1.8.0-master-SNAPSHOT"]]} + :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} + :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} } - :aliases {"test-all" ["with-profile" "test,1.3:test,1.4:test,1.5:test,1.6:test,1.7:test,1.8" "test"] - "check-all" ["with-profile" "1.2:1.3:1.4:1.5:1.6:1.7:1.8" "check"]} + :aliases {"test-all" ["with-profile" "test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:test,1.9" "test"] + "check-all" ["with-profile" "1.4:1.5:1.6:1.7:1.8:1.9" "check"]} :min-lein-version "2.0.0") From 3db109447cfdb96fe0a071a0bc8e780368a5f9ba Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:31:17 -0700 Subject: [PATCH 302/630] Bump copyright date --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f00621b5..1e5feb40 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2015 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2008-2016 Sean Corfield, Stephen C. Gilardi. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be From 5321518f3551e38b33985d9b48e0ca19a29d57d1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:31:39 -0700 Subject: [PATCH 303/630] Refactor db-do-prepared-return-keys JDBC-115 Now allows for PreparedStatement instead of SQL statement. --- src/main/clojure/clojure/java/jdbc.clj | 50 +++++++++++++++----------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1e5feb40..980be337 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -700,34 +700,42 @@ compatibility but it will be removed before a 1.0.0 release." } (with-open [con (get-connection db)] (apply db-do-commands (add-connection db con) transaction? commands))))) +(defn- db-do-execute-prepared-return-keys + [db ^PreparedStatement stmt param-group transaction?] + ((or (:set-parameters db) set-parameters) stmt param-group) + (let [exec-and-return-keys + (^{:once true} fn* [] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (result-set-seq rs))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (exec-and-return-keys)) + (exec-and-return-keys)))) + (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the open database connection. The param-group is a seq of values for all of the parameters. transaction? can be ommitted and will default to true. - Return the generated keys for the (single) update/insert." + Return the generated keys for the (single) update/insert. + A PreparedStatement may be passed in, instead of a SQL string, in which + case :return-keys MUST BE SET on that PreparedStatement!" ([db sql param-group] - (db-do-prepared-return-keys db true sql param-group)) + (db-do-prepared-return-keys db true sql param-group)) ([db transaction? sql param-group] - (if-let [con (db-find-connection db)] + (if-let [con (db-find-connection db)] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-return-keys db sql param-group transaction?) (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] - ((or (:set-parameters db) set-parameters) stmt param-group) - (let [exec-and-return-keys - (^{:once true} fn* [] - (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))] - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (exec-and-return-keys)) - (exec-and-return-keys)))) + (db-do-execute-prepared-return-keys db stmt param-group transaction?))) (with-open [con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) From 25813a4e301db723600f8fad2825a340299adcf5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:32:41 -0700 Subject: [PATCH 304/630] Refactor generated key tests JDBC-115 Reuse returned-key in additional tests by moving it further up the file. --- src/test/clojure/clojure/java/test_jdbc.clj | 79 +++++++++------------ 1 file changed, 34 insertions(+), 45 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index b70c5254..2cd715e6 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -194,6 +194,39 @@ (java.net.URI. "mysql://clojure_test:clojure_test@localhost:3306/clojure_test"))))) +(defn- returned-key [db k] + (condp = (or (:subprotocol db) (:dbtype db)) + "derby" {(keyword "1") nil} + "hsqldb" nil + "h2" nil + "mysql" {:generated_key k} + nil (if (mysql? db) ; string-based tests + {:generated_key k} + k) + "jtds:sqlserver" {:id nil} + "sqlserver" {:generated_keys nil} + "sqlite" {(keyword "last_insert_rowid()") k} + k)) + +(defn- generated-key [db k] + (condp = (or (:subprotocol db) (:dbtype db)) + "derby" 0 + "hsqldb" 0 + "h2" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + k)) + +(defn- float-or-double [db v] + (condp = (or (:subprotocol db) (:dbtype db)) + "derby" (Float. v) + "h2" (Float. v) + "jtds:sqlserver" (Float. v) + "sqlserver" (Float. v) + "postgresql" (Float. v) + v)) + (deftest test-create-table (doseq [db (test-specs)] (create-test-table :fruit db) @@ -275,18 +308,7 @@ :fruit {:name "Pomegranate" :appearance "fresh" :cost 585} {:name "Kiwifruit" :grade 93})] - (condp = (or (:subprotocol db) (:dbtype db)) - nil (when (mysql? db) - (is (= '({:generated_key 1} {:generated_key 2}) r))) - "postgresql" (is (= 2 (count r))) - "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) - "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) - "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) - "hsqldb" (is (= '(nil nil) r)) - "h2" (is (= '(nil nil) r)) - "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} - {(keyword "last_insert_rowid()") 2}) r)) - "derby" (is (= (list {(keyword "1") nil} {(keyword "1") nil}) r)))) + (is (= (list (returned-key db 1) (returned-key db 2)) r))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] :result-set-fn (comp :name first)))))) @@ -633,39 +655,6 @@ :table_name clojure.string/lower-case)))))))) -(defn- returned-key [db k] - (condp = (or (:subprotocol db) (:dbtype db)) - "derby" {(keyword "1") nil} - "hsqldb" nil - "h2" nil - "mysql" {:generated_key k} - nil (if (mysql? db) ; string-based tests - {:generated_key k} - k) - "jtds:sqlserver" {:id nil} - "sqlserver" {:generated_keys nil} - "sqlite" {(keyword "last_insert_rowid()") k} - k)) - -(defn- generated-key [db k] - (condp = (or (:subprotocol db) (:dbtype db)) - "derby" 0 - "hsqldb" 0 - "h2" 0 - "jtds:sqlserver" 0 - "sqlserver" 0 - "sqlite" 0 - k)) - -(defn- float-or-double [db v] - (condp = (or (:subprotocol db) (:dbtype db)) - "derby" (Float. v) - "h2" (Float. v) - "jtds:sqlserver" (Float. v) - "sqlserver" (Float. v) - "postgresql" (Float. v) - v)) - (deftest empty-query (doseq [db (test-specs)] (create-test-table :fruit db) From 5b9dd09db5476b7bf03a6be6595e372772d68197 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:33:32 -0700 Subject: [PATCH 305/630] Add asserts to previous execute! with PreparedStatement JDBC-104 This should have been added when return named keys was added. --- src/test/clojure/clojure/java/test_jdbc.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 2cd715e6..a1f69558 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -340,7 +340,7 @@ (deftest execute-with-prepared-statement-return-keys (doseq [db (test-specs)] - ;; Derby does not have auto-generated id column which we're testing here + ;; Derby/SQL Server does not have auto-generated id column which we're testing here (when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) (create-test-table :fruit db) (sql/with-db-connection [conn db] @@ -348,9 +348,9 @@ prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " "VALUES ( ?, ?, ? )") :return-keys ["id"])] - - (sql/execute! db [prepared-statement "Apple" "Green" 75]) - (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))) + ;; what is returned is affected row counts due to how execute! works + (is (= [1] (sql/execute! db [prepared-statement "Apple" "Green" 75]))) + (is (= [1] (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] :result-set-fn (comp :name first))))))) From acdcf93439d6204fb429ba3f63cb1f946a424fef Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:34:30 -0700 Subject: [PATCH 306/630] Add more PreparedStatement tests JDBC-115 --- src/test/clojure/clojure/java/test_jdbc.clj | 36 ++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index a1f69558..4ceed046 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -246,12 +246,46 @@ (is (thrown? java.sql.SQLException (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) -(deftest test-do-prepared1 +(deftest test-do-prepared1a (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) +(deftest test-do-prepared1b + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")] + (is (= [1] (sql/db-do-prepared db stmt))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared1c + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" []))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared1d + (doseq [db (test-specs)] + (create-test-table :fruit db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" + :return-keys true)] + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-do-prepared1e + (doseq [db (test-specs)] + ;; Derby/SQL Server does not have auto-generated id column which we're testing here + (when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (create-test-table :fruit db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" + :return-keys ["id"])] + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))))) + (deftest test-do-prepared2 (doseq [db (test-specs)] (create-test-table :fruit2 db) From 8090a721141b868154e2a779beda54abe6d8cc28 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 26 Mar 2016 21:36:02 -0700 Subject: [PATCH 307/630] Update change log for JDBC-115 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index cb146274..38c1d9a7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.5.0 +* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). * Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). * Drop Clojure 1.3 compatibility. From 5e85a6ef9cf133d1b1a8c49e19c2cd655fb25464 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 27 Mar 2016 10:33:22 -0700 Subject: [PATCH 308/630] Prep for 0.5.0 release --- CHANGES.md | 2 +- README.md | 12 +++++++++--- project.clj | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 38c1d9a7..f1022555 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.5.0 +Changes in 0.5.0 * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). * Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). diff --git a/README.md b/README.md index ca16d433..fa9c591d 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.4.2 +Latest stable release: 0.5.0 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.4.2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.4.2"] +[org.clojure/java.jdbc "0.5.0"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.4.2 + 0.5.0 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,12 @@ Developer Information Change Log ==================== +* Release 0.5.0 on 2016-03-27 + * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). + * Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). + * Drop Clojure 1.3 compatibility. + + * Release 0.4.2 on 2015-09-15 * Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. * Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume. diff --git a/project.clj b/project.clj index 85c54432..0814d68b 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.0-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.5.1-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From fac4d15c3268be505ee1e9eda2df4a0611e9d582 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 27 Mar 2016 12:38:55 -0500 Subject: [PATCH 309/630] [maven-release-plugin] prepare release java.jdbc-0.5.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c1cc7d5c..af8aa04c 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.0-SNAPSHOT + 0.5.0 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.5.0 From 38a301ad64a65730afa5fa3ce32b80128c99b6e0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 27 Mar 2016 12:38:56 -0500 Subject: [PATCH 310/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index af8aa04c..7bed17f3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.0 + 0.5.1-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.5.0 + HEAD From 64dbdd432f346227fadb73f726fe3fbcf4f59498 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 Apr 2016 23:14:13 -0700 Subject: [PATCH 311/630] Ensure protocol-modifying test cleans up on exceptions --- src/test/clojure/clojure/java/test_jdbc.clj | 36 +++++++++++---------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 4ceed046..d360d4ee 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -828,23 +828,25 @@ String (result-set-read-column [s _ _] ::FOO)) - (doseq [db (test-specs)] - (create-test-table :fruit db) - (sql/insert! db - :fruit - [:name :cost :grade] - ["Crepes" 12 87.7] - ["Vegetables" -88 nil] - ["Teenage Mutant Ninja Turtles" 0 100.0]) - (is (= {:name ::FOO, :cost -88, :grade nil} - (sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?" - "Vegetables"] - :result-set-fn first)))) - - ;; somewhat "undo" the first extension - (extend-protocol sql/IResultSetReadColumn - String - (result-set-read-column [s _ _] s))) + (try + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost :grade] + ["Crepes" 12 87.7] + ["Vegetables" -88 nil] + ["Teenage Mutant Ninja Turtles" 0 100.0]) + (is (= {:name ::FOO, :cost -88, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?" + "Vegetables"] + :result-set-fn first)))) + + ;; somewhat "undo" the first extension + (finally + (extend-protocol sql/IResultSetReadColumn + String + (result-set-read-column [s _ _] s))))) (deftest test-sql-value (extend-protocol sql/ISQLValue From a5b5454f5b1c4786d1111e6aa2901743044584b2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 Apr 2016 23:16:40 -0700 Subject: [PATCH 312/630] Whitespace / indentation cleanup --- src/main/clojure/clojure/java/jdbc.clj | 190 ++++++++++++------------- 1 file changed, 95 insertions(+), 95 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 980be337..1e229e0f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -18,8 +18,8 @@ ;; Migrated from clojure.contrib.sql 17 April 2011 (ns - ^{:author "Stephen C. Gilardi, Sean Corfield", - :doc "A Clojure interface to SQL databases via JDBC + ^{:author "Stephen C. Gilardi, Sean Corfield", + :doc "A Clojure interface to SQL databases via JDBC clojure.java.jdbc provides a simple abstraction for CRUD (create, read, update, delete) operations on a SQL database, along with basic transaction @@ -61,14 +61,14 @@ compatibility but it will be removed before a 1.0.0 release." } joined back together so x.y might become `x`.`y` if the naming strategy quotes identifiers with `." ([f] - (fn [x] - (as-sql-name f x))) + (fn [x] + (as-sql-name f x))) ([f x] - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))))) + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\."))))))) (defn quoted "With a single argument, returns a naming strategy function that quotes @@ -79,12 +79,12 @@ compatibility but it will be removed before a 1.0.0 release." } (quoted \\` \"foo\") will return \"`foo`\" (quoted [\\[ \\]] \"foo\") will return \"[foo]\"" ([q] - (fn [x] - (quoted q x))) + (fn [x] + (quoted q x))) ([q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q)))) + (if (vector? q) + (str (first q) x (last q)) + (str q x q)))) (defn- ^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. @@ -156,8 +156,8 @@ compatibility but it will be removed before a 1.0.0 release." } (.getSchemeSpecificPart uri)) :subprotocol (subprotocols scheme scheme)} (if-let [user-info (.getUserInfo uri)] - {:user (first (str/split user-info #":")) - :password (second (str/split user-info #":"))}) + {:user (first (str/split user-info #":")) + :password (second (str/split user-info #":"))}) (walk/keywordize-keys (into {} query-parts))))) (defn- strip-jdbc [^String spec] @@ -232,65 +232,65 @@ compatibility but it will be removed before a 1.0.0 release." } name environment] :as db-spec}] (cond - connection - connection - - (instance? URI db-spec) - (get-connection (parse-properties-uri db-spec)) - - (string? db-spec) - (get-connection (URI. (strip-jdbc db-spec))) - - factory - (factory (dissoc db-spec :factory)) - - connection-uri - (DriverManager/getConnection connection-uri) - - (and subprotocol subname) - (let [url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname) - classname (or classname (classnames subprotocol))] - (clojure.lang.RT/loadClassForName classname) - (DriverManager/getConnection url (as-properties etc))) - - (and dbtype dbname) - (let [subprotocol dbtype - host (or host "127.0.0.1") - port (or port (condp = subprotocol - "mysql" 3306 - "mssql" 1433 - "jtds" 1433 - "postgresql" 5432 - nil)) - db-sep (if (= "mssql" subprotocol) ";DATABASENAME=" "/") - url (if (#{"derby" "hsqldb" "h2" "sqlite"} subprotocol) - (str "jdbc:" subprotocol ":" dbname) - (str "jdbc:" subprotocol "://" host - (when port (str ":" port)) - db-sep dbname)) - etc (dissoc db-spec :dbtype :dbname)] - (clojure.lang.RT/loadClassForName (classnames subprotocol)) - (DriverManager/getConnection url (as-properties etc))) - - (or (and datasource username password) - (and datasource user password)) - (.getConnection ^DataSource datasource ^String (or username user) ^String password) - - datasource - (.getConnection ^DataSource datasource) - - name - (when-available - javax.naming.InitialContext - (let [env (and environment (Hashtable. ^Map environment)) - context (javax.naming.InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (.getConnection datasource))) - - :else - (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] - (throw (IllegalArgumentException. msg))))) + connection + connection + + (instance? URI db-spec) + (get-connection (parse-properties-uri db-spec)) + + (string? db-spec) + (get-connection (URI. (strip-jdbc db-spec))) + + factory + (factory (dissoc db-spec :factory)) + + connection-uri + (DriverManager/getConnection connection-uri) + + (and subprotocol subname) + (let [url (format "jdbc:%s:%s" subprotocol subname) + etc (dissoc db-spec :classname :subprotocol :subname) + classname (or classname (classnames subprotocol))] + (clojure.lang.RT/loadClassForName classname) + (DriverManager/getConnection url (as-properties etc))) + + (and dbtype dbname) + (let [subprotocol dbtype + host (or host "127.0.0.1") + port (or port (condp = subprotocol + "mysql" 3306 + "mssql" 1433 + "jtds" 1433 + "postgresql" 5432 + nil)) + db-sep (if (= "mssql" subprotocol) ";DATABASENAME=" "/") + url (if (#{"derby" "hsqldb" "h2" "sqlite"} subprotocol) + (str "jdbc:" subprotocol ":" dbname) + (str "jdbc:" subprotocol "://" host + (when port (str ":" port)) + db-sep dbname)) + etc (dissoc db-spec :dbtype :dbname)] + (clojure.lang.RT/loadClassForName (classnames subprotocol)) + (DriverManager/getConnection url (as-properties etc))) + + (or (and datasource username password) + (and datasource user password)) + (.getConnection ^DataSource datasource ^String (or username user) ^String password) + + datasource + (.getConnection ^DataSource datasource) + + name + (when-available + javax.naming.InitialContext + (let [env (and environment (Hashtable. ^Map environment)) + context (javax.naming.InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (.getConnection datasource))) + + :else + (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] + (throw (IllegalArgumentException. msg))))) (defn- make-name-unique "Given a collection of column names and a new column name, @@ -487,14 +487,14 @@ compatibility but it will be removed before a 1.0.0 release." } [^SQLException exception] (let [^Class exception-class (class exception)] (println - (format (str "%s:" \newline - " Message: %s" \newline - " SQLState: %s" \newline - " Error Code: %d") - (.getSimpleName exception-class) - (.getMessage exception) - (.getSQLState exception) - (.getErrorCode exception))))) + (format (str "%s:" \newline + " Message: %s" \newline + " SQLState: %s" \newline + " Error Code: %d") + (.getSimpleName exception-class) + (.getMessage exception) + (.getSQLState exception) + (.getErrorCode exception))))) (defn print-sql-exception-chain "Prints a chain of SQLExceptions to *out*" @@ -513,12 +513,12 @@ compatibility but it will be removed before a 1.0.0 release." } [^BatchUpdateException exception] (println "Update counts:") (dorun - (map-indexed - (fn [index count] - (println (format " Statement %d: %s" - index - (get special-counts count count)))) - (.getUpdateCounts exception)))) + (map-indexed + (fn [index count] + (println (format " Statement %d: %s" + index + (get special-counts count count)))) + (.getUpdateCounts exception)))) ;; java.jdbc pieces rewritten to not use dynamic bindings @@ -685,7 +685,7 @@ compatibility but it will be removed before a 1.0.0 release." } defaults to true. Uses executeBatch. This may affect what SQL you can run via db-do-commands." {:arglists '([db-spec sql-command & sql-commands] - [db-spec transaction? sql-command & sql-commands])} + [db-spec transaction? sql-command & sql-commands])} [db transaction? & commands] (if (string? transaction?) (apply db-do-commands db true transaction? commands) @@ -748,8 +748,8 @@ compatibility but it will be removed before a 1.0.0 release." } (vector (.executeUpdate stmt))) (do (doseq [param-group param-groups] - ((or (:set-parameters db) set-parameters) stmt param-group) - (.addBatch stmt)) + ((or (:set-parameters db) set-parameters) stmt param-group) + (.addBatch stmt)) (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (execute-batch stmt)) @@ -762,7 +762,7 @@ compatibility but it will be removed before a 1.0.0 release." } The sql parameter can either be a SQL string or a PreparedStatement. Return a seq of update counts (one count for each param-group)." {:arglists '([db-spec sql & param-groups] - [db-spec transaction? sql & param-groups])} + [db-spec transaction? sql & param-groups])} [db transaction? & [sql & param-groups :as opts]] (if (or (string? transaction?) (instance? PreparedStatement transaction?)) @@ -786,8 +786,8 @@ compatibility but it will be removed before a 1.0.0 release." } See prepare-statement for supported options. Uses executeQuery. This may affect what SQL you can run via query." {:arglists '([db-spec [sql-string & params] func] - [db-spec [stmt & params] func] - [db-spec [options-map sql-string & params] func])} + [db-spec [stmt & params] func] + [db-spec [options-map sql-string & params] func])} [db sql-params func] (when-not (vector? sql-params) (let [^Class sql-params-class (class sql-params) From 07abb9edcac46ab511b728f56eeaf9de38b4044d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 Apr 2016 23:18:15 -0700 Subject: [PATCH 313/630] Clean up arities and docstrings / arglists JDBC-117 --- src/main/clojure/clojure/java/jdbc.clj | 376 +++++++++++++------------ 1 file changed, 197 insertions(+), 179 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1e229e0f..623b1228 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -367,32 +367,34 @@ compatibility but it will be removed before a 1.0.0 release." } java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it respects the specified naming strategy. Duplicate column names are made unique by appending _N before applying the naming strategy (where N is a unique integer)." - [^ResultSet rs & {:keys [identifiers as-arrays?] - :or {identifiers str/lower-case}}] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) - keys (->> idxs - (map (fn [^Integer i] (.getColumnLabel rsmeta i))) - col-name-fn - (map (comp keyword identifiers))) - row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) - ;; This used to use create-struct (on keys) and then struct to populate each row. - ;; That had the side effect of preserving the order of columns in each row. As - ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't - ;; want to switch to records so we're using regular maps instead. We no longer - ;; guarantee column order in rows but using into {} should preserve order for up - ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying - ;; on the order-preserving behavior of structmaps, we can reconsider... - records (fn thisfn [] - (when (.next rs) - (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) - rows (fn thisfn [] - (when (.next rs) - (cons (vec (row-values)) (lazy-seq (thisfn)))))] - (if as-arrays? - (cons (vec keys) (rows)) - (records)))) + ([rs] (result-set-seq rs {})) + ([^ResultSet rs {:keys [identifiers as-arrays?] + :or {identifiers str/lower-case}}] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) + keys (->> idxs + (map (fn [^Integer i] (.getColumnLabel rsmeta i))) + col-name-fn + (map (comp keyword identifiers))) + row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) + ;; This used to use create-struct (on keys) and then struct to populate each row. + ;; That had the side effect of preserving the order of columns in each row. As + ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't + ;; want to switch to records so we're using regular maps instead. We no longer + ;; guarantee column order in rows but using into {} should preserve order for up + ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying + ;; on the order-preserving behavior of structmaps, we can reconsider... + records (fn thisfn [] + (when (.next rs) + (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) + rows (fn thisfn [] + (when (.next rs) + (cons (vec (row-values)) (lazy-seq (thisfn)))))] + (if as-arrays? + (cons (vec keys) (rows)) + (records)))) + ([rs k v & kvs] (result-set-seq rs (apply hash-map k v kvs)))) (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. @@ -441,39 +443,42 @@ compatibility but it will be removed before a 1.0.0 release." } :fetch-size n :max-rows n :timeout n" - [^java.sql.Connection con ^String sql & - {:keys [return-keys result-type concurrency cursors - fetch-size max-rows timeout]}] - (let [^PreparedStatement - stmt (cond return-keys - (try - (if (vector? return-keys) - (try - (.prepareStatement con sql (string-array return-keys)) - (catch Exception _ - ;; assume it is unsupported and try regular generated keys: - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) - (catch Exception _ - ;; assume it is unsupported and try basic PreparedStatement: - (.prepareStatement con sql))) - - (and result-type concurrency) - (if cursors - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency) - (get result-set-holdability cursors cursors)) - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency))) - - :else - (.prepareStatement con sql))] - (when fetch-size (.setFetchSize stmt fetch-size)) - (when max-rows (.setMaxRows stmt max-rows)) - (when timeout (.setQueryTimeout stmt timeout)) - stmt)) + ([con sql] (prepare-statement con sql {})) + ([^java.sql.Connection con ^String sql + {:keys [return-keys result-type concurrency cursors + fetch-size max-rows timeout]}] + (let [^PreparedStatement + stmt (cond return-keys + (try + (if (vector? return-keys) + (try + (.prepareStatement con sql (string-array return-keys)) + (catch Exception _ + ;; assume it is unsupported and try regular generated keys: + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) + (catch Exception _ + ;; assume it is unsupported and try basic PreparedStatement: + (.prepareStatement con sql))) + + (and result-type concurrency) + (if cursors + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency) + (get result-set-holdability cursors cursors)) + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency))) + + :else + (.prepareStatement con sql))] + (when fetch-size (.setFetchSize stmt fetch-size)) + (when max-rows (.setMaxRows stmt max-rows)) + (when timeout (.setQueryTimeout stmt timeout)) + stmt)) + ([con sql k v & kvs] + (prepare-statement con sql (apply hash-map k v kvs)))) (defn- set-parameters "Add the parameters to the given statement." @@ -572,46 +577,48 @@ compatibility but it will be removed before a 1.0.0 release." } all of those isolation levels, and may either throw an exception or substitute another isolation level. The read-only? option puts the transaction in readonly mode (if supported)." - [db func & {:keys [isolation read-only?]}] - (if (zero? (get-level db)) - (if-let [con (db-find-connection db)] - (let [nested-db (inc-level db) - auto-commit (.getAutoCommit con) - old-isolation (.getTransactionIsolation con) - old-readonly (.isReadOnly con)] - (io! - (when isolation - (.setTransactionIsolation con (isolation isolation-levels))) - (when read-only? - (.setReadOnly con true)) - (.setAutoCommit con false) - (try - (let [result (func nested-db)] - (if (db-is-rollback-only nested-db) - (.rollback con) - (.commit con)) - result) - (catch Throwable t - (.rollback con) - (throw t)) - (finally - (db-unset-rollback-only! nested-db) - (.setAutoCommit con auto-commit) - (when isolation - (.setTransactionIsolation con old-isolation)) - (when read-only? - (.setReadOnly con old-readonly)))))) - (with-open [con (get-connection db)] - (db-transaction* (add-connection db con) func - :isolation isolation :read-only? read-only?))) - (do - (when (and isolation - (let [con (db-find-connection db)] - (not= (isolation isolation-levels) - (.getTransactionIsolation con)))) - (let [msg "Nested transactions may not have different isolation levels"] - (throw (IllegalStateException. msg)))) - (func (inc-level db))))) + ([db func] (db-transaction* db func {})) + ([db func {:keys [isolation read-only?] :as opts}] + (if (zero? (get-level db)) + (if-let [con (db-find-connection db)] + (let [nested-db (inc-level db) + auto-commit (.getAutoCommit con) + old-isolation (.getTransactionIsolation con) + old-readonly (.isReadOnly con)] + (io! + (when isolation + (.setTransactionIsolation con (isolation isolation-levels))) + (when read-only? + (.setReadOnly con true)) + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-is-rollback-only nested-db) + (.rollback con) + (.commit con)) + result) + (catch Throwable t + (.rollback con) + (throw t)) + (finally + (db-unset-rollback-only! nested-db) + (.setAutoCommit con auto-commit) + (when isolation + (.setTransactionIsolation con old-isolation)) + (when read-only? + (.setReadOnly con old-readonly)))))) + (with-open [con (get-connection db)] + (db-transaction* (add-connection db con) func opts))) + (do + (when (and isolation + (let [con (db-find-connection db)] + (not= (isolation isolation-levels) + (.getTransactionIsolation con)))) + (let [msg "Nested transactions may not have different isolation levels"] + (throw (IllegalStateException. msg)))) + (func (inc-level db))))) + ([db func k v & kvs] + (db-transaction* db func (apply hash-map k v kvs)))) (defmacro with-db-transaction "Evaluates body in the context of a transaction on the specified database connection. @@ -654,17 +661,20 @@ compatibility but it will be removed before a 1.0.0 release." } Also accepts :identifiers, :as-arrays?, :row-fn, and :result-set-fn to control how the ResultSet is transformed and returned. See query for more details." - [rs-or-value & {:keys [identifiers as-arrays? row-fn result-set-fn] - :or {identifiers str/lower-case row-fn identity}}] - (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] - (if (instance? java.sql.ResultSet rs-or-value) - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rs-or-value :identifiers identifiers :as-arrays? as-arrays?)) - rs-or-value))) + ([rs-or-value] (metadata-result rs-or-value {})) + ([rs-or-value {:keys [identifiers as-arrays? row-fn result-set-fn] + :or {identifiers str/lower-case row-fn identity}}] + (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (if (instance? java.sql.ResultSet rs-or-value) + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rs-or-value {:identifiers identifiers :as-arrays? as-arrays?})) + rs-or-value))) + ([rs-or-value k v & kvs] + (metadata-result rs-or-value (apply hash-map k v kvs)))) (defmacro metadata-query "Given a Java expression that extracts metadata (in the context of with-db-metadata), @@ -673,8 +683,8 @@ compatibility but it will be removed before a 1.0.0 release." } (with-db-metadata [meta db-spec] (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) - :row-fn ... - :result-set-fn ...))" + {:row-fn ... + :result-set-fn ...}))" [meta-query & opt-args] `(with-open [rs# ~meta-query] (metadata-result rs# ~@opt-args))) @@ -734,10 +744,10 @@ compatibility but it will be removed before a 1.0.0 release." } (if-let [con (db-find-connection db)] (if (instance? PreparedStatement sql) (db-do-execute-prepared-return-keys db sql param-group transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql :return-keys true)] + (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] (db-do-execute-prepared-return-keys db stmt param-group transaction?))) - (with-open [con (get-connection db)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) + (with-open [con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) (defn- db-do-execute-prepared-statement [db ^PreparedStatement stmt param-groups transaction?] @@ -806,7 +816,7 @@ compatibility but it will be removed before a 1.0.0 release." } params (vec (cond sql-is-first (rest sql-params) options-are-first (rest (rest sql-params)) :else (rest sql-params))) - prepare-args (when (map? special) (flatten (seq special))) + prepare-args (when (map? special) special) run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] ((or (:set-parameters db) set-parameters) stmt params) (with-open [rset (.executeQuery stmt)] @@ -825,8 +835,8 @@ compatibility but it will be removed before a 1.0.0 release." } (defn query "Given a database connection and a vector containing SQL and optional parameters, - perform a simple database query. The optional keyword arguments specify how to - construct the result set: + perform a simple database query. The options specify how to construct the result + set: :result-set-fn - applied to the entire result set, default doall / vec if :as-arrays? true, :result-set-fn will default to vec if :as-arrays? false, :result-set-fn will default to doall @@ -834,69 +844,69 @@ compatibility but it will be removed before a 1.0.0 release." } :identifiers - applied to each column name in the result set, default lower-case :as-arrays? - return the results as a set of arrays, default false. The second argument is a vector containing a SQL string or PreparedStatement, followed - by any parameters it needs. See db-query-with-resultset for details." - {:arglists '([db-spec sql-and-params - :as-arrays? false :identifiers clojure.string/lower-case - :result-set-fn doall :row-fn identity] - [db-spec sql-and-params - :as-arrays? true :identifiers clojure.string/lower-case - :result-set-fn vec :row-fn identity] - [db-spec [sql-string & params]] - [db-spec [stmt & params]] - [db-spec [option-map sql-string & params]])} - [db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?] - :or {row-fn identity - identifiers str/lower-case}}] - (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) - sql-params-vector (if (string? sql-params) - (vector sql-params) - (vec sql-params))] - (db-query-with-resultset db sql-params-vector - (^{:once true} fn* [rset] - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rset :identifiers identifiers :as-arrays? as-arrays?)))))) + by any parameters it needs. It may optionally include an options map before the SQL + string or PreparedStatement. See db-query-with-resultset for details." + ([db sql-params] (query db sql-params {})) + ([db sql-params {:keys [result-set-fn row-fn identifiers as-arrays?] + :or {row-fn identity + identifiers str/lower-case}}] + (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) + sql-params-vector (if (string? sql-params) + (vector sql-params) + (vec sql-params))] + (db-query-with-resultset db sql-params-vector + (^{:once true} fn* [rset] + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?})))))) + ([db sql-params k v & kvs] (query db sql-params (apply hash-map k v kvs)))) (defn execute! - "Given a database connection and a vector containing SQL and optional parameters, - perform a general (non-select) SQL operation. The optional keyword argument specifies - whether to run the operation in a transaction or not (default true). + "Given a database connection and a vector containing SQL (or PreparedStatement) + followed by optional parameters, perform a general (non-select) SQL operation. + The :transaction? option specifies whether to run the operation in a + transaction or not (default true). + If the :multi? option is false (the default), the SQL statement should be + followed by the parameters for that statement. + If the :multi? option is true, the SQL statement should be followed by one or + more vectors of parameters, one for each application of the SQL statement. If there are no parameters specified, executeUpdate will be used, otherwise executeBatch will be used. This may affect what SQL you can run via execute!" - {:arglists '([db-spec [sql & params] :multi? false :transaction? true] - [db-spec [sql & param-groups] :multi? true :transaction? true])} - [db sql-params & {:keys [transaction? multi?] - :or {transaction? true multi? false}}] - (let [param-groups (rest sql-params) - execute-helper - (^{:once true} fn* [db] - (if multi? - (apply db-do-prepared db transaction? (first sql-params) param-groups) - (if (seq param-groups) - (db-do-prepared db transaction? (first sql-params) param-groups) - (db-do-prepared db transaction? (first sql-params)))))] - (if-let [con (db-find-connection db)] - (execute-helper db) - (with-open [con (get-connection db)] - (execute-helper (add-connection db con)))))) + ([db sql-params] (execute! db sql-params {})) + ([db sql-params {:keys [transaction? multi?] + :or {transaction? true multi? false}}] + (let [param-groups (rest sql-params) + execute-helper + (^{:once true} fn* [db] + (if multi? + (apply db-do-prepared db transaction? (first sql-params) param-groups) + (if (seq param-groups) + (db-do-prepared db transaction? (first sql-params) param-groups) + (db-do-prepared db transaction? (first sql-params)))))] + (if-let [con (db-find-connection db)] + (execute-helper db) + (with-open [con (get-connection db)] + (execute-helper (add-connection db con)))))) + ([db sql-params k v & kvs] (execute! db sql-params (apply hash-map k v kvs)))) (defn- table-str "Transform a table spec to an entity name for SQL. The table spec may be a string, a keyword or a map with a single pair - table name and alias." [table entities] - (if (map? table) - (let [[k v] (first table)] - (str (as-sql-name entities k) " " (as-sql-name entities v))) - (as-sql-name entities table))) + (let [entities (or entities identity)] + (if (map? table) + (let [[k v] (first table)] + (str (as-sql-name entities k) " " (as-sql-name entities v))) + (as-sql-name entities table)))) (defn- delete-sql "Given a table name, a where class and its parameters and an optional entities spec, return a vector of the SQL for that delete operation followed by its parameters. The entities spec (default 'as-is') specifies how to transform column names." - [table [where & params] & {:keys [entities] :or {entities identity}}] + [table [where & params] entities] (into [(str "DELETE FROM " (table-str table entities) (when where " WHERE ") where)] params)) @@ -910,11 +920,14 @@ compatibility but it will be removed before a 1.0.0 release." } (delete! db :person [\"zip = ?\" 94546]) is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" - [db table where-clause & {:keys [entities transaction?] - :or {entities identity transaction? true}}] - (execute! db - (delete-sql table where-clause :entities entities) - :transaction? transaction?)) + ([db table where-clause] (delete! db table where-clause {})) + ([db table where-clause {:keys [entities transaction?] + :or {entities identity transaction? true}}] + (execute! db + (delete-sql table where-clause entities) + {:transaction? transaction?})) + ([db table where-clause k v & kvs] + (delete! db table where-clause (apply hash-map k v kvs)))) (defn- multi-insert-helper "Given a (connected) database connection and some SQL statements (for multiple @@ -1060,11 +1073,14 @@ compatibility but it will be removed before a 1.0.0 release." } (update! db :person {:zip 94540} [\"zip = ?\" 94546]) is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" - [db table set-map where-clause & {:keys [entities transaction?] - :or {entities identity transaction? true}}] - (execute! db - (update-sql table set-map where-clause :entities entities) - :transaction? transaction?)) + ([db table set-map where-clause] (update! db table set-map where-clause {})) + ([db table set-map where-clause {:keys [entities transaction?] + :or {entities identity transaction? true}}] + (execute! db + (update-sql table set-map where-clause entities) + {:transaction? transaction?})) + ([db table set-map where-clause k v & kvs] + (update! db table set-map where-clause (apply hash-map k v kvs)))) (defn create-table-ddl "Given a table name and column specs with an optional table-spec @@ -1086,8 +1102,10 @@ compatibility but it will be removed before a 1.0.0 release." } (defn drop-table-ddl "Given a table name, return the DDL string for dropping that table." - [name & {:keys [entities] :or {entities identity}}] - (format "DROP TABLE %s" (as-sql-name entities name))) + ([name] (drop-table-ddl name {})) + ([name k v & kvs] (drop-table-ddl name (apply hash-map k v kvs))) + ([name {:keys [entities] :or {entities identity}}] + (format "DROP TABLE %s" (as-sql-name entities name)))) (defmacro ^{:doc "Original name for with-db-transaction. Use that instead." From 310781429225b614cab01256f3adce54917644aa Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 Apr 2016 23:18:42 -0700 Subject: [PATCH 314/630] Rewrite / simplify insert! argument handling JDBC-117 This doesn't quite fall under the arity / optional keyword argument cleanup of JDBC-117 but insert! was the odd function out in terms of how flexible its arguments are and not using map-destructuring directly. --- src/main/clojure/clojure/java/jdbc.clj | 134 ++++++++++++++----------- 1 file changed, 74 insertions(+), 60 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 623b1228..1d8e45c0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -942,21 +942,9 @@ compatibility but it will be removed before a 1.0.0 release." } "Given a (connected) database connection, a transaction flag and some SQL statements (for one or more inserts), run a prepared statement or a sequence of them." [db transaction? stmts] - (if (string? (first stmts)) - (apply db-do-prepared db transaction? (first stmts) (rest stmts)) - (if transaction? - (with-db-transaction [t-db db] (multi-insert-helper t-db stmts)) - (multi-insert-helper db stmts)))) - -(defn- extract-transaction? - "Given a sequence of data, look for :transaction? arg in it and return a pair of - the transaction? value (defaulting to true) and the data without the option." - [data] - (let [before (take-while (partial not= :transaction?) data) - after (drop-while (partial not= :transaction?) data)] - (if (seq after) - [(second after) (concat before (nnext after))] - [true data]))) + (if transaction? + (with-db-transaction [t-db db] (multi-insert-helper t-db stmts)) + (multi-insert-helper db stmts))) (defn- col-str "Transform a column spec to an entity name for SQL. The column spec may be a @@ -999,58 +987,84 @@ compatibility but it will be removed before a 1.0.0 release." } " )")] (vals row)))) -(defn- insert-sql - "Given a table name and either column names and values or maps representing rows, - return a vector of the SQL for that insert operation followed by its parameters. An - optional entities spec (default 'as-is') specifies how to transform column names." - [table & clauses] - (let [rows (take-while map? clauses) - n-rows (count rows) - cols-and-vals-etc (drop n-rows clauses) - cols-and-vals (take-while (comp not keyword?) cols-and-vals-etc) - n-cols-and-vals (count cols-and-vals) - no-cols-and-vals (zero? n-cols-and-vals) - options (drop (+ n-rows n-cols-and-vals) clauses) - {:keys [entities] :or {entities identity}} (apply hash-map options)] - (if (zero? n-rows) - (if no-cols-and-vals - (throw (IllegalArgumentException. "insert called without data to insert")) - (if (< n-cols-and-vals 2) - (throw (IllegalArgumentException. "insert called with columns but no values")) - (insert-multi-row-sql table (first cols-and-vals) (rest cols-and-vals) entities))) - (if no-cols-and-vals - (map (fn [row] (insert-single-row-sql table row entities)) rows) - (throw (IllegalArgumentException. "insert may take records or columns and values, not both")))))) +(defn- parse-insert!-options + "Given, potentially, options to insert! turn them into a hash map. + If the only key is :options, assume the value is the entire options." + [arguments] + (let [options (if (seq arguments) (apply hash-map arguments) {})] + (if (:options options) + (:options options) + options))) + +(defn- parse-insert!-rows + "Given arguments to insert! starting with a map, return a map of all the + rows and any options that follow." + [arguments] + (let [[maps other] (split-with map? arguments) + options (parse-insert!-options other)] + {:rows maps :options options})) + +(defn- parse-insert!-cols + "Given arguments to insert! starting with a vector, return a map of all the + column names and values and any options that follow." + [names arguments] + (let [[values other] (split-with vector? arguments) + options (parse-insert!-options other)] + {:names names :values values :options options})) + +(defn- parse-insert! + "Given arguments to insert! return a map of the various parts: + rows (maps) or names & values (vectors), options (keyword pairs) + If the keyword :options is present, assume the value is the entire set of + options to pass back, otherwise accumulate key/value pairs." + [arguments] + (cond (map? (first arguments)) + (parse-insert!-rows arguments) + (and (or (nil? (first arguments)) + (vector? (first arguments))) + (vector? (second arguments))) + (parse-insert!-cols (first arguments) (rest arguments)) + :else + (throw (IllegalArgumentException. "insert! expects row maps or column name/value vectors")))) (defn insert! "Given a database connection, a table name and either maps representing rows or - a list of column names followed by lists of column values, perform an insert. - Use :transaction? argument to specify whether to run in a transaction or not. - The default is true (use a transaction). Use :entities to specify how to convert - the table name and column names to SQL entities." - {:arglists '([db-spec table row-map :transaction? true :entities identity] - [db-spec table row-map & row-maps :transaction? true :entities identity] - [db-spec table col-name-vec col-val-vec & col-val-vecs :transaction? true :entities identity])} - [db table & options] - (let [[transaction? maps-or-cols-and-values-etc] (extract-transaction? options) - stmts (apply insert-sql table maps-or-cols-and-values-etc)] - (if-let [con (db-find-connection db)] - (insert-helper db transaction? stmts) - (with-open [con (get-connection db)] - (insert-helper (add-connection db con) transaction? stmts))))) + a list of column names followed by lists of column values, perform an insert. + The rows or columns may be followed by :options and a map of options (or, for + backward compatibility, just the unrolled options instead). + The :transaction? option specifies whether to run in a transaction or not. + The default is true (use a transaction). The :entities options specifies how + to convert the table name and column names to SQL entities." + {:arglists '([db-spec table row-map & row-maps] + [db-spec table col-name-vec col-val-vec & col-val-vecs] + [db-spec table rows-or-col-name-val-vecs :options options])} + [db table & arguments] + (let [{:keys [rows names values options]} (parse-insert! arguments) + transaction? (:transaction? options true) + entities (:entities options identity)] + (if rows + + (let [stmts (map (fn [row] (insert-single-row-sql table row entities)) rows)] + (if-let [con (db-find-connection db)] + (insert-helper db transaction? stmts) + (with-open [con (get-connection db)] + (insert-helper (add-connection db con) transaction? stmts)))) + + (let [stmts (insert-multi-row-sql table names values entities)] + (if-let [con (db-find-connection db)] + (apply db-do-prepared db transaction? stmts) + (with-open [con (get-connection db)] + (apply db-do-prepared (add-connection db con) transaction? stmts))))))) (defn- update-sql - "Given a table name and a map of columns to set, and optional map of columns to - match (and an optional entities spec), return a vector of the SQL for that update - followed by its parameters. Example: - (update :person {:zip 94540} [\"zip = ?\" 94546]) + "Given a table name, a map of columns to set, a optional map of columns to + match, and an entities, return a vector of the SQL for that update followed + by its parameters. Example: + (update :person {:zip 94540} [\"zip = ?\" 94546] identity) returns: [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" - [table set-map & where-etc] - (let [[where-clause & options] (when-not (keyword? (first where-etc)) where-etc) - [where & params] where-clause - {:keys [entities] :or {entities identity}} (if (keyword? (first where-etc)) where-etc options) - ks (keys set-map) + [table set-map [where & params] entities] + (let [ks (keys set-map) vs (vals set-map)] (cons (str "UPDATE " (table-str table entities) " SET " (str/join From 9e9925ccca7275444b64a63fce300be098ea50ae Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 8 Apr 2016 23:26:21 -0700 Subject: [PATCH 315/630] Bump to 0.5.5-SNAPSHOT Preparing to deprecate the unrolled optional keyword argument forms of call. --- CHANGES.md | 4 ++++ README.md | 1 - pom.xml | 2 +- project.clj | 2 +- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f1022555..ce97138e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.5.5 + +* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated and will go away in 0.6.0. + Changes in 0.5.0 * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). diff --git a/README.md b/README.md index fa9c591d..780667c7 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,6 @@ Change Log * Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). * Drop Clojure 1.3 compatibility. - * Release 0.4.2 on 2015-09-15 * Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. * Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume. diff --git a/pom.xml b/pom.xml index 7bed17f3..53091cb3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.1-SNAPSHOT + 0.5.5-SNAPSHOT ${project.artifactId} diff --git a/project.clj b/project.clj index 0814d68b..155e1215 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.1-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.5.5-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From a0e71397bccb1a9f28c8099864da73c05a8b805b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 00:28:25 -0700 Subject: [PATCH 316/630] Add DEPRECATED warnings; update tests to use new call format JDBC-117 --- CHANGES.md | 2 +- src/main/clojure/clojure/java/jdbc.clj | 28 +++- src/test/clojure/clojure/java/test_jdbc.clj | 166 ++++++++++---------- 3 files changed, 109 insertions(+), 87 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index ce97138e..45efa707 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,6 @@ Changes coming in 0.5.5 -* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated and will go away in 0.6.0. +* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. Changes in 0.5.0 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1d8e45c0..f1edda7c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -394,7 +394,9 @@ compatibility but it will be removed before a 1.0.0 release." } (if as-arrays? (cons (vec keys) (rows)) (records)))) - ([rs k v & kvs] (result-set-seq rs (apply hash-map k v kvs)))) + ([rs k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to result-seq-seq") + (result-set-seq rs (apply hash-map k v kvs)))) (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. @@ -478,6 +480,7 @@ compatibility but it will be removed before a 1.0.0 release." } (when timeout (.setQueryTimeout stmt timeout)) stmt)) ([con sql k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to prepare-statement") (prepare-statement con sql (apply hash-map k v kvs)))) (defn- set-parameters @@ -618,6 +621,7 @@ compatibility but it will be removed before a 1.0.0 release." } (throw (IllegalStateException. msg)))) (func (inc-level db))))) ([db func k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to db-transaction*") (db-transaction* db func (apply hash-map k v kvs)))) (defmacro with-db-transaction @@ -674,6 +678,7 @@ compatibility but it will be removed before a 1.0.0 release." } (result-set-seq rs-or-value {:identifiers identifiers :as-arrays? as-arrays?})) rs-or-value))) ([rs-or-value k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to metadata-result") (metadata-result rs-or-value (apply hash-map k v kvs)))) (defmacro metadata-query @@ -862,7 +867,9 @@ compatibility but it will be removed before a 1.0.0 release." } (map row-fn (rest rs))) (map row-fn rs)))) (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?})))))) - ([db sql-params k v & kvs] (query db sql-params (apply hash-map k v kvs)))) + ([db sql-params k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to query") + (query db sql-params (apply hash-map k v kvs)))) (defn execute! "Given a database connection and a vector containing SQL (or PreparedStatement) @@ -890,7 +897,9 @@ compatibility but it will be removed before a 1.0.0 release." } (execute-helper db) (with-open [con (get-connection db)] (execute-helper (add-connection db con)))))) - ([db sql-params k v & kvs] (execute! db sql-params (apply hash-map k v kvs)))) + ([db sql-params k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to execute!") + (execute! db sql-params (apply hash-map k v kvs)))) (defn- table-str "Transform a table spec to an entity name for SQL. The table spec may be a @@ -927,6 +936,7 @@ compatibility but it will be removed before a 1.0.0 release." } (delete-sql table where-clause entities) {:transaction? transaction?})) ([db table where-clause k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to delete!") (delete! db table where-clause (apply hash-map k v kvs)))) (defn- multi-insert-helper @@ -994,7 +1004,10 @@ compatibility but it will be removed before a 1.0.0 release." } (let [options (if (seq arguments) (apply hash-map arguments) {})] (if (:options options) (:options options) - options))) + (do + (when (seq options) + (println "DEPRECATED: unrolled key/value arguments to insert!")) + options)))) (defn- parse-insert!-rows "Given arguments to insert! starting with a map, return a map of all the @@ -1094,6 +1107,7 @@ compatibility but it will be removed before a 1.0.0 release." } (update-sql table set-map where-clause entities) {:transaction? transaction?})) ([db table set-map where-clause k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to update!") (update! db table set-map where-clause (apply hash-map k v kvs)))) (defn create-table-ddl @@ -1117,9 +1131,11 @@ compatibility but it will be removed before a 1.0.0 release." } (defn drop-table-ddl "Given a table name, return the DDL string for dropping that table." ([name] (drop-table-ddl name {})) - ([name k v & kvs] (drop-table-ddl name (apply hash-map k v kvs))) ([name {:keys [entities] :or {entities identity}}] - (format "DROP TABLE %s" (as-sql-name entities name)))) + (format "DROP TABLE %s" (as-sql-name entities name))) + ([name k v & kvs] + (println "DEPRECATED: unrolled key/value arguments to drop-table-ddl") + (drop-table-ddl name (apply hash-map k v kvs)))) (defmacro ^{:doc "Original name for with-db-transaction. Use that instead." diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index d360d4ee..9d25852c 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -230,27 +230,27 @@ (deftest test-create-table (doseq [db (test-specs)] (create-test-table :fruit db) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-drop-table (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-commands db (sql/drop-table-ddl :fruit2)) (is (thrown? java.sql.SQLException - (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-commands (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-commands db "DROP TABLE fruit2") (is (thrown? java.sql.SQLException - (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1a (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") - (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1b (doseq [db (test-specs)] @@ -258,22 +258,22 @@ (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")] (is (= [1] (sql/db-do-prepared db stmt))))) - (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1c (doseq [db (test-specs)] (create-test-table :fruit2 db) (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" []))) - (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1d (doseq [db (test-specs)] (create-test-table :fruit db) (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" - :return-keys true)] + {:return-keys true})] (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-do-prepared1e (doseq [db (test-specs)] @@ -282,28 +282,28 @@ (create-test-table :fruit db) (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" - :return-keys ["id"])] + {:return-keys ["id"]})] (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))) (deftest test-do-prepared2 (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-prepared db "DROP TABLE fruit2") (is (thrown? java.sql.SQLException - (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared3 (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) - (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared4 (doseq [db (test-specs)] (create-test-table :fruit2 db) (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) - (is (= 2 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-insert-rows (doseq [db (test-specs)] @@ -317,9 +317,9 @@ [3 "Peach" "fuzzy" 139 90.0] [4 "Orange" "juicy" 89 88.6])] (is (= '(1 1 1 1) r))) - (is (= 4 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] :result-set-fn (comp :name first)))) - (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] :result-set-fn (comp :appearance first)))))) + (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) + (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first}))))) (deftest test-insert-values (doseq [db (test-specs)] @@ -331,8 +331,8 @@ ["Mango" 722] ["Feijoa" 441])] (is (= '(1 1) r))) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= "Mango" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 722] :result-set-fn (comp :name first)))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= "Mango" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 722] {:row-fn :name :result-set-fn first}))))) (deftest test-insert-records (doseq [db (test-specs)] @@ -343,8 +343,8 @@ {:name "Pomegranate" :appearance "fresh" :cost 585} {:name "Kiwifruit" :grade 93})] (is (= (list (returned-key db 1) (returned-key db 2)) r))) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] :result-set-fn (comp :name first)))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] {:row-fn :name :result-set-fn first}))))) (deftest test-insert-via-execute (doseq [db (test-specs)] @@ -354,9 +354,9 @@ "Apple" "Green" 75]) (sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) " "VALUES ( 'Pear', 'Yellow', 99 )")]) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] - :result-set-fn (comp :name first)))))) + {:row-fn :name :result-set-fn first}))))) (deftest execute-with-prepared-statement (doseq [db (test-specs)] @@ -368,9 +368,9 @@ (sql/execute! db [prepared-statement "Apple" "Green" 75]) (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] - :result-set-fn (comp :name first)))))) + {:row-fn :name :result-set-fn first}))))) (deftest execute-with-prepared-statement-return-keys (doseq [db (test-specs)] @@ -381,13 +381,13 @@ (let [connection (:connection conn) prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " "VALUES ( ?, ?, ? )") - :return-keys ["id"])] + {:return-keys ["id"]})] ;; what is returned is affected row counts due to how execute! works (is (= [1] (sql/execute! db [prepared-statement "Apple" "Green" 75]))) (is (= [1] (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))))) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] - :result-set-fn (comp :name first))))))) + {:row-fn :name :result-set-fn first})))))) (deftest test-update-values (doseq [db (test-specs)] @@ -405,10 +405,13 @@ :fruit {:appearance "bruised" :cost 14} ["name=?" "Banana"]) - (is (= 4 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] :result-set-fn (comp :name first)))) - (is (= "Banana" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] :result-set-fn (comp :name first)))) - (is (= 14 (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Banana"] :result-set-fn (comp :cost first)))))) + (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:row-fn :name :result-set-fn first}))) + (is (= "Banana" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] + {:row-fn :name :result-set-fn first}))) + (is (= 14 (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Banana"] + {:row-fn :cost :result-set-fn first}))))) (defn update-or-insert-values [db table row where] @@ -420,7 +423,7 @@ (defn update-or-insert-values-with-isolation [db table row where] - (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (let [result (sql/update! t-conn table row where)] (if (zero? (first result)) (sql/insert! t-conn table row) @@ -433,19 +436,21 @@ :fruit {:name "Pomegranate" :appearance "fresh" :cost 585} ["name=?" "Pomegranate"]) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] :result-set-fn (comp :cost first)))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] + {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db :fruit {:name "Pomegranate" :appearance "ripe" :cost 565} ["name=?" "Pomegranate"]) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] :result-set-fn (comp :cost first)))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] + {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db :fruit {:name "Apple" :appearance "green" :cost 74} ["name=?" "Apple"]) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-update-or-insert-values-with-isolation (doseq [db (test-specs)] @@ -454,19 +459,21 @@ :fruit {:name "Pomegranate" :appearance "fresh" :cost 585} ["name=?" "Pomegranate"]) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] :result-set-fn (comp :cost first)))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] + {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db :fruit {:name "Pomegranate" :appearance "ripe" :cost 565} ["name=?" "Pomegranate"]) - (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) - (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] :result-set-fn (comp :cost first)))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] + {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db :fruit {:name "Apple" :appearance "green" :cost 74} ["name=?" "Apple"]) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (defn- file-not-found-exception-via-reflection "In Clojure 1.3.0 this caused a wrapped exception and we introduced throw-non-rte @@ -486,10 +493,10 @@ [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"]) - (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))) (file-not-found-exception-via-reflection "/etc/password_no_such_file")) (catch java.io.FileNotFoundException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))) (catch Exception _ (is false "Unexpected exception encountered (not wrapped?)."))))) @@ -497,16 +504,16 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/with-db-transaction [t-conn db :isolation :serializable] + (sql/with-db-transaction [t-conn db {:isolation :serializable}] (sql/insert! t-conn :fruit [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"]) - (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))) (throw (Exception. "deliberate exception"))) (catch Exception _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))))) (deftest test-sql-exception (doseq [db (test-specs)] @@ -518,21 +525,21 @@ [:name :appearance] ["Apple" "strange" "whoops"])) (catch IllegalArgumentException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-sql-exception-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (sql/insert! t-conn :fruit [:name :appearance] ["Apple" "strange" "whoops"])) (catch IllegalArgumentException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-insert-values-exception (doseq [db (test-specs)] @@ -545,20 +552,20 @@ ["Grape" "yummy"] ["Pear" "bruised"] ["Apple" "strange" "whoops"])))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-insert-values-exception-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) (is (thrown? IllegalArgumentException - (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (sql/insert! t-conn :fruit [:name :appearance] ["Grape" "yummy"] ["Pear" "bruised"] ["Apple" "strange" "whoops"])))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-rollback (doseq [db (test-specs)] @@ -574,16 +581,16 @@ ["Grape" "yummy"] ["Pear" "bruised"] ["Apple" "strange"]) - (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))) (catch java.sql.SQLException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-rollback-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) (try - (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (is (not (sql/db-is-rollback-only t-conn))) (sql/db-set-rollback-only! t-conn) (is (sql/db-is-rollback-only t-conn)) @@ -593,10 +600,10 @@ ["Grape" "yummy"] ["Pear" "bruised"] ["Apple" "strange"]) - (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))) (catch java.sql.SQLException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-transactions-with-possible-generated-keys-result-set (doseq [db (test-specs)] @@ -607,32 +614,32 @@ :fruit [:name :appearance] ["Grape" "yummy"]) - (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-transactions-with-possible-generated-keys-result-set-and-isolation (doseq [db (test-specs)] (create-test-table :fruit db) - (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (sql/db-set-rollback-only! t-conn) (sql/insert! t-conn :fruit [:name :appearance] ["Grape" "yummy"]) - (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-nested-transactions-check-transaction-isolation-level (doseq [db (test-specs)] (create-test-table :fruit db) - (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (is (thrown? IllegalStateException - (sql/with-db-transaction [t-conn' t-conn :isolation :serializable] + (sql/with-db-transaction [t-conn' t-conn {:isolation :serializable}] (sql/insert! t-conn' :fruit [:name :appearance] ["Grape" "yummy"]))))) - (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-raw-metadata (doseq [db (test-specs)] @@ -671,8 +678,8 @@ (sql/metadata-query (.getTables metadata nil nil nil (into-array ["TABLE" "VIEW"])) - :row-fn (comp clojure.string/lower-case :table_name) - :result-set-fn first)))))) + {:row-fn (comp clojure.string/lower-case :table_name) + :result-set-fn first})))))) (deftest test-metadata (doseq [db (test-specs)] @@ -730,7 +737,7 @@ (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] - :as-arrays? :cols-as-is)] + {:as-arrays? :cols-as-is})] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [[:id :name :appearance :cost :grade] [(generated-key db 1) "Apple" nil nil nil] @@ -788,11 +795,10 @@ (deftest illegal-insert-arguments (doseq [db (test-specs)] (is (thrown? IllegalArgumentException (sql/insert! db))) - (is (thrown? IllegalArgumentException (sql/insert! db :entities identity))) (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :entities identity))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :options {:entities identity}))) (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db [:name] :entities identity))))) + (is (thrown? IllegalArgumentException (sql/insert! db [:name] :options {:entities identity}))))) (deftest test-execute!-fails-with-multi-param-groups (doseq [db (test-specs)] @@ -816,7 +822,7 @@ ["Apple" "rosy"] ["Pear" "yellow"] ["Orange" "round"]] - :multi? true) + {:multi? true}) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [1 1 1] counts)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance "rosy" :cost nil :grade nil} @@ -840,7 +846,7 @@ (is (= {:name ::FOO, :cost -88, :grade nil} (sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?" "Vegetables"] - :result-set-fn first)))) + {:result-set-fn first})))) ;; somewhat "undo" the first extension (finally @@ -861,7 +867,7 @@ [:test 12 nil]) (is (= {:name "KW", :cost 12, :grade nil} (sql/query db ["SELECT name, cost, grade FROM fruit"] - :result-set-fn first)))) + {:result-set-fn first})))) ;; somewhat "undo" the first extension (extend-protocol sql/ISQLValue @@ -884,7 +890,7 @@ [:test :twelve nil]) (is (= {:name "test1", :cost 12, :grade nil} (sql/query db ["SELECT name, cost, grade FROM fruit"] - :result-set-fn first)))) + {:result-set-fn first})))) ;; somewhat "undo" the first extension (extend-protocol sql/ISQLParameter From 828ad782c938766f7bdd08ecdd8f922bb6a3a222 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 01:21:37 -0700 Subject: [PATCH 317/630] Convert create-table-ddl to :options JDBC-117 --- src/main/clojure/clojure/java/jdbc.clj | 25 +++++++++++-------- src/test/clojure/clojure/java/test_jdbc.clj | 6 ++--- .../clojure/clojure/java/test_utilities.clj | 6 ++--- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f1edda7c..e7044ef5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1111,18 +1111,21 @@ compatibility but it will be removed before a 1.0.0 release." } (update! db table set-map where-clause (apply hash-map k v kvs)))) (defn create-table-ddl - "Given a table name and column specs with an optional table-spec - return the DDL string for creating that table." + "Given a table name and column specs return the DDL string for creating that + table. The column specs may be followed by :options and an options map that + includes :table-spec -- a string that is appended to the DDL -- and/or + :entities -- a function to specify how column names are transformed. + For backward compatibility, those options may be specified inline instead of + via :options (but that is deprecated)." [table & specs] - (let [col-specs (take-while (fn [s] - (not (or (= :table-spec s) - (= :entities s)))) specs) - other-specs (drop (count col-specs) specs) - {:keys [table-spec entities] :or {entities identity}} other-specs - table-spec-str (or (and table-spec (str " " table-spec)) "") - spec-to-string (fn [spec] - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))))] + (let [[col-specs other] (split-with (complement keyword?) specs) + options (parse-options other "create-table-ddl") + table-spec (:table-spec options) + entities (:entities options identity) + table-spec-str (or (and table-spec (str " " table-spec)) "") + spec-to-string (fn [spec] + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))))] (format "CREATE TABLE %s (%s)%s" (as-sql-name entities table) (str/join ", " (map spec-to-string col-specs)) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9d25852c..a44ea30c 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -154,7 +154,7 @@ [:appearance "VARCHAR(32)"] [:cost :int] [:grade :real] - :table-spec "ENGINE=InnoDB"))) + :options {:table-spec "ENGINE=InnoDB"}))) (defmethod create-test-table :postgres [table db] @@ -166,7 +166,7 @@ [:appearance "VARCHAR(32)"] [:cost :int] [:grade :real] - :table-spec ""))) + :options {:table-spec ""}))) (defmethod create-test-table :default [table db] @@ -178,7 +178,7 @@ [:appearance "VARCHAR(32)"] [:cost :int] [:grade :real] - :table-spec ""))) + :options {:table-spec ""}))) (deftest test-uri-spec-parsing (is (= {:advanced "false" :ssl "required" :password "clojure_test" diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index 5d28ea8a..5a1dec16 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -59,8 +59,8 @@ (deftest test-create-table-ddl (is (= "CREATE TABLE THING (COL1 INT, COL2 int)" (sql/create-table-ddl :thing ["col1 int"] [:col2 :int] - :entities clojure.string/upper-case))) + :options {:entities clojure.string/upper-case}))) (is (= "CREATE TABLE THING (COL1 int, COL2 int) ENGINE=MyISAM" (sql/create-table-ddl :thing [:col1 "int"] ["col2" :int] - :table-spec "ENGINE=MyISAM" - :entities clojure.string/upper-case)))) \ No newline at end of file + :options {:table-spec "ENGINE=MyISAM" + :entities clojure.string/upper-case})))) From 34a2ad405aaacfe0ffa703a1ba4450da46775fdd Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 01:21:59 -0700 Subject: [PATCH 318/630] Update docstrings to reflect options map JDBC-117 --- src/main/clojure/clojure/java/jdbc.clj | 58 ++++++++++++++------------ 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e7044ef5..8c689532 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -364,9 +364,13 @@ compatibility but it will be removed before a 1.0.0 release." } (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the - java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it - respects the specified naming strategy. Duplicate column names are made unique - by appending _N before applying the naming strategy (where N is a unique integer)." + java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it + respects the specified naming strategy. Duplicate column names are made unique + by appending _N before applying the naming strategy (where N is a unique integer), + unless the :as-arrays? option is :cols-as-is, in which case the column names + are untouched (the result set maintains column name/value order). + The :identifiers option specifies how SQL column names are converted to Clojure + keywords. The default is to convert them to lower case." ([rs] (result-set-seq rs {})) ([^ResultSet rs {:keys [identifiers as-arrays?] :or {identifiers str/lower-case}}] @@ -434,8 +438,8 @@ compatibility but it will be removed before a 1.0.0 release." } (into-array String return-keys)) (defn prepare-statement - "Create a prepared statement from a connection, a SQL string and an - optional list of parameters: + "Create a prepared statement from a connection, a SQL string and a map + of options: :return-keys truthy | nil - default nil for some drivers, this may be a vector of column names to identify the generated keys to return, otherwise it should just be true @@ -630,7 +634,7 @@ compatibility but it will be removed before a 1.0.0 release." } that is bound for evaluation of the body. The binding may also specify the isolation level for the transaction, via the :isolation option and/or set the transaction to readonly via the :read-only? option. - (with-db-transaction [t-con db-spec :isolation level :read-only? true] + (with-db-transaction [t-con db-spec {:isolation level :read-only? true}] ... t-con ...) See db-transaction* for more details." [binding & body] @@ -661,10 +665,10 @@ compatibility but it will be removed before a 1.0.0 release." } (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, - else return it as-is. This makes working with metadata easier. - Also accepts :identifiers, :as-arrays?, :row-fn, and :result-set-fn - to control how the ResultSet is transformed and returned. - See query for more details." + else return it as-is. This makes working with metadata easier. + Also accepts an option map containing :identifiers, :as-arrays?, :row-fn, + and :result-set-fn to control how the ResultSet is transformed and returned. + See query for more details." ([rs-or-value] (metadata-result rs-or-value {})) ([rs-or-value {:keys [identifiers as-arrays? row-fn result-set-fn] :or {identifiers str/lower-case row-fn identity}}] @@ -683,13 +687,12 @@ compatibility but it will be removed before a 1.0.0 release." } (defmacro metadata-query "Given a Java expression that extracts metadata (in the context of with-db-metadata), - and additional optional arguments like metadata-result, manage the connection for a - single metadata-based query. Example usage: + and a map of options like metadata-result, manage the connection for a single + metadata-based query. Example usage: (with-db-metadata [meta db-spec] (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) - {:row-fn ... - :result-set-fn ...}))" + {:row-fn ... :result-set-fn ...}))" [meta-query & opt-args] `(with-open [rs# ~meta-query] (metadata-result rs# ~@opt-args))) @@ -716,6 +719,8 @@ compatibility but it will be removed before a 1.0.0 release." } (apply db-do-commands (add-connection db con) transaction? commands))))) (defn- db-do-execute-prepared-return-keys + "Executes a PreparedStatement, optionally in a transaction, and (attempts to) + return any generated keys." [db ^PreparedStatement stmt param-group transaction?] ((or (:set-parameters db) set-parameters) stmt param-group) (let [exec-and-return-keys @@ -755,6 +760,7 @@ compatibility but it will be removed before a 1.0.0 release." } (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) (defn- db-do-execute-prepared-statement + "Execute a PreparedStatment, optionally in a transaction." [db ^PreparedStatement stmt param-groups transaction?] (if (empty? param-groups) (if transaction? @@ -922,9 +928,8 @@ compatibility but it will be removed before a 1.0.0 release." } (defn delete! "Given a database connection, a table name and a where clause of columns to match, - perform a delete. The optional keyword arguments specify how to transform - column names in the map (default 'as-is') and whether to run the delete in - a transaction (default true). + perform a delete. The options may specify how to transform column names in the + map (default 'as-is') and whether to run the delete in a transaction (default true). Example: (delete! db :person [\"zip = ?\" 94546]) is equivalent to: @@ -997,16 +1002,17 @@ compatibility but it will be removed before a 1.0.0 release." } " )")] (vals row)))) -(defn- parse-insert!-options +(defn- parse-options "Given, potentially, options to insert! turn them into a hash map. - If the only key is :options, assume the value is the entire options." - [arguments] + If the only key is :options, assume the value is the entire options. + Otherwise this a deprecated legacy form of insert! options." + [arguments caller] (let [options (if (seq arguments) (apply hash-map arguments) {})] (if (:options options) (:options options) (do (when (seq options) - (println "DEPRECATED: unrolled key/value arguments to insert!")) + (println "DEPRECATED: unrolled key/value arguments to" caller)) options)))) (defn- parse-insert!-rows @@ -1014,7 +1020,7 @@ compatibility but it will be removed before a 1.0.0 release." } rows and any options that follow." [arguments] (let [[maps other] (split-with map? arguments) - options (parse-insert!-options other)] + options (parse-options other "insert!")] {:rows maps :options options})) (defn- parse-insert!-cols @@ -1022,7 +1028,7 @@ compatibility but it will be removed before a 1.0.0 release." } column names and values and any options that follow." [names arguments] (let [[values other] (split-with vector? arguments) - options (parse-insert!-options other)] + options (parse-options other "insert!")] {:names names :values values :options options})) (defn- parse-insert! @@ -1044,7 +1050,7 @@ compatibility but it will be removed before a 1.0.0 release." } "Given a database connection, a table name and either maps representing rows or a list of column names followed by lists of column values, perform an insert. The rows or columns may be followed by :options and a map of options (or, for - backward compatibility, just the unrolled options instead). + backward compatibility, just the unrolled options instead, but that is deprecated). The :transaction? option specifies whether to run in a transaction or not. The default is true (use a transaction). The :entities options specifies how to convert the table name and column names to SQL entities." @@ -1093,8 +1099,8 @@ compatibility but it will be removed before a 1.0.0 release." } (defn update! "Given a database connection, a table name, a map of column values to set and a - where clause of columns to match, perform an update. The optional keyword arguments - specify how column names (in the set / match maps) should be transformed (default + where clause of columns to match, perform an update. The options may specify + how column names (in the set / match maps) should be transformed (default 'as-is') and whether to run the update in a transaction (default true). Example: (update! db :person {:zip 94540} [\"zip = ?\" 94546]) From 9f32fdd4941ce1a99b39bf1a7ae23a1fec5d855a Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 9 Apr 2016 13:53:11 -0500 Subject: [PATCH 319/630] [maven-release-plugin] prepare release java.jdbc-0.5.5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 53091cb3..4b9207e2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.5-SNAPSHOT + 0.5.5 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.5.5 From 490de0b4eeaa132ed538823946ec52c8161b83d9 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 9 Apr 2016 13:53:11 -0500 Subject: [PATCH 320/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 4b9207e2..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.5 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.5.5 + HEAD From da1bedbcb99b0368e467c73fa8c92128d2619519 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 11:55:41 -0700 Subject: [PATCH 321/630] Update CHANGES/README for 0.5.5 release --- CHANGES.md | 2 +- README.md | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 45efa707..a6d9c52c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.5.5 +Changes in 0.5.5 * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. diff --git a/README.md b/README.md index 780667c7..cbe774cc 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.5.0 +Latest stable release: 0.5.5 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.5.0 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.5.0"] +[org.clojure/java.jdbc "0.5.5"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.5.0 + 0.5.5 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,10 @@ Developer Information Change Log ==================== +* Release 0.5.5 on 2016-04-09 + * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). + - The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. + * Release 0.5.0 on 2016-03-27 * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). * Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). From a6e7e5e69667b69cd6a5fa4464093ee15565c834 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 14:29:51 -0700 Subject: [PATCH 322/630] Update README example to new syntax JDBC-117 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cbe774cc..4355b678 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Example Usage (j/query mysql-db ["select * from fruit where appearance = ?" "rosy"] - :row-fn :cost) + {:row-fn :cost}) ;; (24) ``` For more detail see the [generated documentation on github](http://clojure.github.com/java.jdbc/). From 250c9cce0fa6c424d1ab309ef31e51da41574f85 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 18:36:13 -0700 Subject: [PATCH 323/630] Clean up create-table-ddl arguments JDBC-120 Added `legacy-create-table-ddl` which issues a warning, ensured `parse-options` doesn't warn for that, cleaned up `create-table-ddl`. Also sets version to 0.5.6-SNAPSHOT. --- CHANGES.md | 4 ++ pom.xml | 2 +- project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 60 +++++++++++++------ src/test/clojure/clojure/java/test_jdbc.clj | 36 +++++------ .../clojure/clojure/java/test_utilities.clj | 10 ++-- 6 files changed, 70 insertions(+), 44 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index a6d9c52c..7b91df3c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.5.6 + +* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. + Changes in 0.5.5 * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. diff --git a/pom.xml b/pom.xml index 95806b9f..e8569c40 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.5.6-SNAPSHOT ${project.artifactId} diff --git a/project.clj b/project.clj index 155e1215..cc1dddb7 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.5-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.5.6-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8c689532..6a683ff5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1003,15 +1003,15 @@ compatibility but it will be removed before a 1.0.0 release." } (vals row)))) (defn- parse-options - "Given, potentially, options to insert! turn them into a hash map. - If the only key is :options, assume the value is the entire options. - Otherwise this a deprecated legacy form of insert! options." + "Given, potentially, options to insert! / create-table-ddl turn them into a + hash map. If the only key is :options, assume the value is the entire options. + Otherwise this a deprecated legacy form of options." [arguments caller] (let [options (if (seq arguments) (apply hash-map arguments) {})] (if (:options options) (:options options) (do - (when (seq options) + (when (and caller (seq options)) (println "DEPRECATED: unrolled key/value arguments to" caller)) options)))) @@ -1116,26 +1116,48 @@ compatibility but it will be removed before a 1.0.0 release." } (println "DEPRECATED: unrolled key/value arguments to update!") (update! db table set-map where-clause (apply hash-map k v kvs)))) +(declare legacy-create-table-ddl) + (defn create-table-ddl "Given a table name and column specs return the DDL string for creating that - table. The column specs may be followed by :options and an options map that - includes :table-spec -- a string that is appended to the DDL -- and/or + table. An options map may be provided that can contain: + :table-spec -- a string that is appended to the DDL -- and/or :entities -- a function to specify how column names are transformed. - For backward compatibility, those options may be specified inline instead of - via :options (but that is deprecated)." + For backward compatibility, those options may be specified inline or via a + map introduced with the delimiting keyword :options (but that is deprecated). + In addition, also for backward compatibility, the column specs may be + specified as individual arguments rather than collected into a vector (but + that is also deprecated)." + ([table specs] (create-table-ddl table specs {})) + ([table specs opts] + ;; check for deprecated legacy syntax + (if-not (vector? (first specs)) + (legacy-create-table-ddl table specs opts) + (let [table-spec (:table-spec opts) + entities (:entities opts identity) + table-spec-str (or (and table-spec (str " " table-spec)) "") + spec-to-string (fn [spec] + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))))] + (format "CREATE TABLE %s (%s)%s" + (as-sql-name entities table) + (str/join ", " (map spec-to-string specs)) + table-spec-str)))) + ([table spec1 spec2 spec3 & specs] + ;; just in case someone wraps the specs in a vector but still provides :options + ;; this allows for a DEPRECATED warning rather than an unpleasant exception + (if (and (= :options spec2) + (vector? (first spec1))) + (apply legacy-create-table-ddl table (concat spec1 [spec2 spec3] specs)) + (apply legacy-create-table-ddl table spec1 spec2 spec3 specs)))) + +(defn legacy-create-table-ddl + "Deprecated version of create-table-ddl." [table & specs] + (println "DEPRECATED: unrolled column specs / key/value arguments to create-table-ddl") (let [[col-specs other] (split-with (complement keyword?) specs) - options (parse-options other "create-table-ddl") - table-spec (:table-spec options) - entities (:entities options identity) - table-spec-str (or (and table-spec (str " " table-spec)) "") - spec-to-string (fn [spec] - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))))] - (format "CREATE TABLE %s (%s)%s" - (as-sql-name entities table) - (str/join ", " (map spec-to-string col-specs)) - table-spec-str))) + options (parse-options other nil)] + (create-table-ddl table col-specs options))) (defn drop-table-ddl "Given a table name, return the DDL string for dropping that table." diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index a44ea30c..7bc1e43d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -149,36 +149,36 @@ (sql/db-do-commands db (sql/create-table-ddl table - [:id :int "PRIMARY KEY AUTO_INCREMENT"] - [:name "VARCHAR(32)"] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :options {:table-spec "ENGINE=InnoDB"}))) + [[:id :int "PRIMARY KEY AUTO_INCREMENT"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real]] + {:table-spec "ENGINE=InnoDB"}))) (defmethod create-test-table :postgres [table db] (sql/db-do-commands db (sql/create-table-ddl table - [:id :serial "PRIMARY KEY"] - [:name "VARCHAR(32)"] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :options {:table-spec ""}))) + [[:id :serial "PRIMARY KEY"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real]] + {:table-spec ""}))) (defmethod create-test-table :default [table db] (sql/db-do-commands db (sql/create-table-ddl table - [:id :int "DEFAULT 0"] - [:name "VARCHAR(32)" "PRIMARY KEY"] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :options {:table-spec ""}))) + [[:id :int "DEFAULT 0"] + [:name "VARCHAR(32)" "PRIMARY KEY"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real]] + {:table-spec ""}))) (deftest test-uri-spec-parsing (is (= {:advanced "false" :ssl "required" :password "clojure_test" diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index 5a1dec16..b4a0d557 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -58,9 +58,9 @@ (deftest test-create-table-ddl (is (= "CREATE TABLE THING (COL1 INT, COL2 int)" - (sql/create-table-ddl :thing ["col1 int"] [:col2 :int] - :options {:entities clojure.string/upper-case}))) + (sql/create-table-ddl :thing [["col1 int"] [:col2 :int]] + {:entities clojure.string/upper-case}))) (is (= "CREATE TABLE THING (COL1 int, COL2 int) ENGINE=MyISAM" - (sql/create-table-ddl :thing [:col1 "int"] ["col2" :int] - :options {:table-spec "ENGINE=MyISAM" - :entities clojure.string/upper-case})))) + (sql/create-table-ddl :thing [[:col1 "int"] ["col2" :int]] + {:table-spec "ENGINE=MyISAM" + :entities clojure.string/upper-case})))) From 1928ff4d627243c9d2e0bf309a8b4f965f5034d3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 22:44:31 -0700 Subject: [PATCH 324/630] Added insert-multi!; deprecated multi-row insert! JDBC-120 Tests pass. Lots of DEPRECATED warnings. --- src/main/clojure/clojure/java/jdbc.clj | 134 +++++++++++++++++++------ 1 file changed, 106 insertions(+), 28 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6a683ff5..5be704c4 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1004,23 +1004,19 @@ compatibility but it will be removed before a 1.0.0 release." } (defn- parse-options "Given, potentially, options to insert! / create-table-ddl turn them into a - hash map. If the only key is :options, assume the value is the entire options. - Otherwise this a deprecated legacy form of options." - [arguments caller] + hash map. If the only key is :options, assume the value is the entire options." + [arguments] (let [options (if (seq arguments) (apply hash-map arguments) {})] (if (:options options) (:options options) - (do - (when (and caller (seq options)) - (println "DEPRECATED: unrolled key/value arguments to" caller)) - options)))) + options))) (defn- parse-insert!-rows "Given arguments to insert! starting with a map, return a map of all the rows and any options that follow." [arguments] (let [[maps other] (split-with map? arguments) - options (parse-options other "insert!")] + options (parse-options other)] {:rows maps :options options})) (defn- parse-insert!-cols @@ -1028,7 +1024,7 @@ compatibility but it will be removed before a 1.0.0 release." } column names and values and any options that follow." [names arguments] (let [[values other] (split-with vector? arguments) - options (parse-options other "insert!")] + options (parse-options other)] {:names names :values values :options options})) (defn- parse-insert! @@ -1046,34 +1042,116 @@ compatibility but it will be removed before a 1.0.0 release." } :else (throw (IllegalArgumentException. "insert! expects row maps or column name/value vectors")))) +(defn- insert-rows! + "Given a database connection, a table name, a sequence of rows, and an options + map, insert the rows into the database." + [db table rows opts] + (let [entities (:entities opts identity) + sql-params (map (fn [row] + (when-not (map? row) + (throw (IllegalArgumentException. "insert-row! called with a non-map row"))) + (insert-single-row-sql table row entities)) rows)] + (if-let [con (db-find-connection db)] + (insert-helper db (:transaction? opts) sql-params) + (with-open [con (get-connection db)] + (insert-helper (add-connection db con) (:transaction? opts) sql-params))))) + +(defn- insert-cols! + "Given a database connection, a table name, a sequence of columns names, a + sequence of vectors of column values, one per row, and an options map, + insert the rows into the database." + [db table cols values opts] + (let [sql-params (insert-multi-row-sql table cols values (:entities opts identity))] + (if-let [con (db-find-connection db)] + (apply db-do-prepared db (:transaction? opts) sql-params) + (with-open [con (get-connection db)] + (apply db-do-prepared (add-connection db con) (:transaction? opts) sql-params))))) + +(defn- is-options-map? + "Given a map, return true if it seems to be an options map." + [opts] + (let [other (dissoc opts :transaction? :entities)] + (cond (seq other) + false ; it has other keys + (:entities opts) (fn? (:entities opts)) + :else true))) + (defn insert! "Given a database connection, a table name and either maps representing rows or a list of column names followed by lists of column values, perform an insert. The rows or columns may be followed by :options and a map of options (or, for backward compatibility, just the unrolled options instead, but that is deprecated). The :transaction? option specifies whether to run in a transaction or not. - The default is true (use a transaction). The :entities options specifies how + The default is true (use a transaction). The :entities option specifies how to convert the table name and column names to SQL entities." {:arglists '([db-spec table row-map & row-maps] [db-spec table col-name-vec col-val-vec & col-val-vecs] [db-spec table rows-or-col-name-val-vecs :options options])} - [db table & arguments] - (let [{:keys [rows names values options]} (parse-insert! arguments) - transaction? (:transaction? options true) - entities (:entities options identity)] - (if rows - - (let [stmts (map (fn [row] (insert-single-row-sql table row entities)) rows)] - (if-let [con (db-find-connection db)] - (insert-helper db transaction? stmts) - (with-open [con (get-connection db)] - (insert-helper (add-connection db con) transaction? stmts)))) - - (let [stmts (insert-multi-row-sql table names values entities)] - (if-let [con (db-find-connection db)] - (apply db-do-prepared db transaction? stmts) - (with-open [con (get-connection db)] - (apply db-do-prepared (add-connection db con) transaction? stmts))))))) + ([db table row] (insert! db table row {})) + ([db table cols-or-row values-or-opts] + (if (map? values-or-opts) + (if (is-options-map? values-or-opts) ; non-legacy version + (insert-rows! db table [cols-or-row] values-or-opts) + (do + (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") + (insert-rows! db table [cols-or-row values-or-opts] {}))) + (do + (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") + (insert-cols! db table cols-or-row [values-or-opts] {})))) + ([db table cols values opts] + ;; could also be + ;; cols values-1 values-2 + ;; or row-1 row-2 row-3 + ;; or row-1 option value + (cond (keyword? values) (do + (println "DEPRECATED: insert! with :options or unrolled key/value arguments") + (if (= :options values) + (insert-rows! db table [cols] opts) + (insert-rows! db table [cols] {values opts}))) + (map? cols) (do + (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") + (insert-rows! db table [cols values opts])) + (map? opts) ; this is the only non-legacy version + (insert-cols! db table cols values opts) + :else (do + (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") + (insert-cols! db table cols [values opts] {})))) + ;; legacy version + ([db table cols-or-row row-or-values-1 row-or-values-2 row-or-values-3 & more] + (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") + (let [{:keys [rows names values options]} + (parse-insert! (concat [cols-or-row row-or-values-1 row-or-values-2 row-or-values-3] more)) + transaction? (:transaction? options true) + entities (:entities options identity)] + (if rows + + (let [stmts (map (fn [row] (insert-single-row-sql table row entities)) rows)] + (if-let [con (db-find-connection db)] + (insert-helper db transaction? stmts) + (with-open [con (get-connection db)] + (insert-helper (add-connection db con) transaction? stmts)))) + + (let [stmts (insert-multi-row-sql table names values entities)] + (if-let [con (db-find-connection db)] + (apply db-do-prepared db transaction? stmts) + (with-open [con (get-connection db)] + (apply db-do-prepared (add-connection db con) transaction? stmts)))))))) + +(defn insert-multi! + "Given a database connection, a table name and either a sequence of maps (for + rows) or a sequence of column names, followed by a sequence of vectors (for + the values in each row), and possibly a map of options, insert that data into + the database. + The :transaction? option specifies whether to run in a transaction or not. + The default is true (use a transaction). The :entities option specifies how + to convert the table name and column names to SQL entities." + ([db table rows] (insert-rows! db table rows {})) + ([db table cols-or-rows values-or-opts] + (if (map? values-or-opts) + (insert-rows! db table cols-or-rows values-or-opts) + (insert-cols! db table cols-or-rows values-or-opts {}))) + ([db table cols values opts] + (insert-cols! db table cols values opts))) (defn- update-sql "Given a table name, a map of columns to set, a optional map of columns to @@ -1156,7 +1234,7 @@ compatibility but it will be removed before a 1.0.0 release." } [table & specs] (println "DEPRECATED: unrolled column specs / key/value arguments to create-table-ddl") (let [[col-specs other] (split-with (complement keyword?) specs) - options (parse-options other nil)] + options (parse-options other)] (create-table-ddl table col-specs options))) (defn drop-table-ddl From f894ae44d1cb812e28f7cfba05dea0101b5d66d6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 23:03:58 -0700 Subject: [PATCH 325/630] Correct mislabeled non-legacy call JDBC-119 --- src/main/clojure/clojure/java/jdbc.clj | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5be704c4..c1514731 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1095,9 +1095,8 @@ compatibility but it will be removed before a 1.0.0 release." } (do (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") (insert-rows! db table [cols-or-row values-or-opts] {}))) - (do - (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") - (insert-cols! db table cols-or-row [values-or-opts] {})))) + ;; also non-legacy version: column names and one set of row values + (insert-cols! db table cols-or-row [values-or-opts] {}))) ([db table cols values opts] ;; could also be ;; cols values-1 values-2 From db35d95e17ce5cc2ae2c0f99a10bdf63e359caef Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 23:04:54 -0700 Subject: [PATCH 326/630] Update tests to avoid deprecated calls JDBC-119 --- src/test/clojure/clojure/java/test_jdbc.clj | 188 ++++++++++---------- 1 file changed, 92 insertions(+), 96 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 7bc1e43d..180d8ce2 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -140,9 +140,9 @@ For MySQL, ensure table uses an engine that supports transactions!" (fn [table db] (cond - (mysql? db) :mysql - (postgres? db) :postgres - :else :default))) + (mysql? db) :mysql + (postgres? db) :postgres + :else :default))) (defmethod create-test-table :mysql [table db] @@ -308,14 +308,13 @@ (deftest test-insert-rows (doseq [db (test-specs)] (create-test-table :fruit db) - (let [r (sql/insert! - db - :fruit - nil - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])] + (let [r (sql/insert-multi! db + :fruit + nil + [[1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6]])] (is (= '(1 1 1 1) r))) (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) @@ -324,12 +323,11 @@ (deftest test-insert-values (doseq [db (test-specs)] (create-test-table :fruit db) - (let [r (sql/insert! - db - :fruit - [:name :cost] - ["Mango" 722] - ["Feijoa" 441])] + (let [r (sql/insert-multi! db + :fruit + [:name :cost] + [["Mango" 722] + ["Feijoa" 441]])] (is (= '(1 1) r))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Mango" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 722] {:row-fn :name :result-set-fn first}))))) @@ -337,11 +335,10 @@ (deftest test-insert-records (doseq [db (test-specs)] (create-test-table :fruit db) - (let [r (sql/insert! - db - :fruit - {:name "Pomegranate" :appearance "fresh" :cost 585} - {:name "Kiwifruit" :grade 93})] + (let [r (sql/insert-multi! db + :fruit + [{:name "Pomegranate" :appearance "fresh" :cost 585} + {:name "Kiwifruit" :grade 93}])] (is (= (list (returned-key db 1) (returned-key db 2)) r))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] {:row-fn :name :result-set-fn first}))))) @@ -392,19 +389,18 @@ (deftest test-update-values (doseq [db (test-specs)] (create-test-table :fruit db) - (let [r (sql/insert! - db - :fruit - nil - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])] + (let [r (sql/insert-multi! db + :fruit + nil + [[1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6]])] (is (= '(1 1 1 1) r))) (sql/update! db - :fruit - {:appearance "bruised" :cost 14} - ["name=?" "Banana"]) + :fruit + {:appearance "bruised" :cost 14} + ["name=?" "Banana"]) (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) @@ -433,46 +429,46 @@ (doseq [db (test-specs)] (create-test-table :fruit db) (update-or-insert-values db - :fruit - {:name "Pomegranate" :appearance "fresh" :cost 585} - ["name=?" "Pomegranate"]) + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + ["name=?" "Pomegranate"]) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db - :fruit - {:name "Pomegranate" :appearance "ripe" :cost 565} - ["name=?" "Pomegranate"]) + :fruit + {:name "Pomegranate" :appearance "ripe" :cost 565} + ["name=?" "Pomegranate"]) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db - :fruit - {:name "Apple" :appearance "green" :cost 74} - ["name=?" "Apple"]) + :fruit + {:name "Apple" :appearance "green" :cost 74} + ["name=?" "Apple"]) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-update-or-insert-values-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) (update-or-insert-values-with-isolation db - :fruit - {:name "Pomegranate" :appearance "fresh" :cost 585} - ["name=?" "Pomegranate"]) + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + ["name=?" "Pomegranate"]) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db - :fruit - {:name "Pomegranate" :appearance "ripe" :cost 565} - ["name=?" "Pomegranate"]) + :fruit + {:name "Pomegranate" :appearance "ripe" :cost 565} + ["name=?" "Pomegranate"]) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] {:row-fn :cost :result-set-fn first}))) (update-or-insert-values db - :fruit - {:name "Apple" :appearance "green" :cost 74} - ["name=?" "Apple"]) + :fruit + {:name "Apple" :appearance "green" :cost 74} + ["name=?" "Apple"]) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (defn- file-not-found-exception-via-reflection @@ -488,11 +484,11 @@ (create-test-table :fruit db) (try (sql/with-db-transaction [t-conn db] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"]]) (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))) (file-not-found-exception-via-reflection "/etc/password_no_such_file")) (catch java.io.FileNotFoundException _ @@ -505,11 +501,11 @@ (create-test-table :fruit db) (try (sql/with-db-transaction [t-conn db {:isolation :serializable}] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"]]) (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))) (throw (Exception. "deliberate exception"))) (catch Exception _ @@ -546,12 +542,12 @@ (create-test-table :fruit db) (is (thrown? IllegalArgumentException (sql/with-db-transaction [t-conn db] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"])))) + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]])))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-insert-values-exception-with-isolation @@ -559,12 +555,12 @@ (create-test-table :fruit db) (is (thrown? IllegalArgumentException (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"])))) + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]])))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-rollback @@ -575,12 +571,12 @@ (is (not (sql/db-is-rollback-only t-conn))) (sql/db-set-rollback-only! t-conn) (is (sql/db-is-rollback-only t-conn)) - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange"]) + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]]) (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))) (catch java.sql.SQLException _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) @@ -594,12 +590,12 @@ (is (not (sql/db-is-rollback-only t-conn))) (sql/db-set-rollback-only! t-conn) (is (sql/db-is-rollback-only t-conn)) - (sql/insert! t-conn - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange"]) + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]]) (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))) (catch java.sql.SQLException _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) @@ -724,7 +720,7 @@ (deftest insert-two-by-map-and-query (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + (let [new-keys (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}]) new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) @@ -734,7 +730,7 @@ (deftest insert-two-by-map-and-query-as-arrays (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + (let [new-keys (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}]) new-keys (if (postgres? db) (map :id new-keys) new-keys) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] {:as-arrays? :cols-as-is})] @@ -746,7 +742,7 @@ (deftest insert-two-by-cols-and-query (doseq [db (test-specs)] (create-test-table :fruit db) - (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) + (let [update-counts (sql/insert-multi! db :fruit [:name] [["Apple"] ["Pear"]]) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [1 1] update-counts)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} @@ -796,9 +792,9 @@ (doseq [db (test-specs)] (is (thrown? IllegalArgumentException (sql/insert! db))) (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :options {:entities identity}))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] {:entities identity}))) (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db [:name] :options {:entities identity}))))) + (is (thrown? ClassCastException (sql/insert! db [:name] {:entities identity}))))) (deftest test-execute!-fails-with-multi-param-groups (doseq [db (test-specs)] @@ -837,12 +833,12 @@ (try (doseq [db (test-specs)] (create-test-table :fruit db) - (sql/insert! db - :fruit - [:name :cost :grade] - ["Crepes" 12 87.7] - ["Vegetables" -88 nil] - ["Teenage Mutant Ninja Turtles" 0 100.0]) + (sql/insert-multi! db + :fruit + [:name :cost :grade] + [["Crepes" 12 87.7] + ["Vegetables" -88 nil] + ["Teenage Mutant Ninja Turtles" 0 100.0]]) (is (= {:name ::FOO, :cost -88, :grade nil} (sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?" "Vegetables"] From fc7f8258c743a7e2908a00bf2e71cda9ae51c742 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 9 Apr 2016 23:13:51 -0700 Subject: [PATCH 327/630] Prep for version 0.5.6 with insert! changes And also create-table-ddl changes (but those are minor). --- CHANGES.md | 4 +++- README.md | 13 ++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 7b91df3c..982c7f0f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ -Changes coming in 0.5.6 +Changes in 0.5.6 * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. +* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. +* NOTE: all deprecated functionality will go away in version 0.6.0! Changes in 0.5.5 diff --git a/README.md b/README.md index 4355b678..a3c0c08a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.5.5 +Latest stable release: 0.5.6 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.5.5 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.5.5"] +[org.clojure/java.jdbc "0.5.6"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.5.5 + 0.5.6 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,13 @@ Developer Information Change Log ==================== +* Release 0.5.6 on 2016-04-10 + * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). + - If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. + * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/JDBC-119). + - If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. + * NOTE: all deprecated functionality will go away in version 0.6.0! + * Release 0.5.5 on 2016-04-09 * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). - The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. From eb323a2e3ee2b5c762e087e55ddcced70caca381 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 10 Apr 2016 05:47:17 -0500 Subject: [PATCH 328/630] [maven-release-plugin] prepare release java.jdbc-0.5.6 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index e8569c40..849cd9a1 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.6-SNAPSHOT + 0.5.6 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.5.6 From 5a06565d5eb04cb7c5d2a2ec652b0297e61491c5 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 10 Apr 2016 05:47:17 -0500 Subject: [PATCH 329/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 849cd9a1..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.6 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.5.6 + HEAD From d46c6638083416953f7e38aa23b3befe93d2b625 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Apr 2016 11:49:13 -0700 Subject: [PATCH 330/630] Remove all deprecations JDBC-118 Also adds some more tests for `insert!` that highlighted a bug in 0.5.6 --- src/main/clojure/clojure/java/jdbc.clj | 217 +----- .../clojure/clojure/java/jdbc/deprecated.clj | 729 ------------------ .../clojure/clojure/java/test_deprecated.clj | 411 ---------- src/test/clojure/clojure/java/test_jdbc.clj | 21 + 4 files changed, 50 insertions(+), 1328 deletions(-) delete mode 100644 src/main/clojure/clojure/java/jdbc/deprecated.clj delete mode 100644 src/test/clojure/clojure/java/test_deprecated.clj diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c1514731..65d56962 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -38,12 +38,7 @@ generated keys are returned (as a map). For more documentation, see: -http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html - -As of release 0.3.0, the API has undergone a major overhaul and most of the -original API has been deprecated in favor of a more idiomatic API. The -original API has been moved to java.jdbc.deprecated for backward -compatibility but it will be removed before a 1.0.0 release." } +http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } clojure.java.jdbc (:import [java.net URI] [java.sql BatchUpdateException DriverManager @@ -397,10 +392,7 @@ compatibility but it will be removed before a 1.0.0 release." } (cons (vec (row-values)) (lazy-seq (thisfn)))))] (if as-arrays? (cons (vec keys) (rows)) - (records)))) - ([rs k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to result-seq-seq") - (result-set-seq rs (apply hash-map k v kvs)))) + (records))))) (defn- execute-batch "Executes a batch of SQL commands and returns a sequence of update counts. @@ -482,10 +474,7 @@ compatibility but it will be removed before a 1.0.0 release." } (when fetch-size (.setFetchSize stmt fetch-size)) (when max-rows (.setMaxRows stmt max-rows)) (when timeout (.setQueryTimeout stmt timeout)) - stmt)) - ([con sql k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to prepare-statement") - (prepare-statement con sql (apply hash-map k v kvs)))) + stmt))) (defn- set-parameters "Add the parameters to the given statement." @@ -623,10 +612,7 @@ compatibility but it will be removed before a 1.0.0 release." } (.getTransactionIsolation con)))) (let [msg "Nested transactions may not have different isolation levels"] (throw (IllegalStateException. msg)))) - (func (inc-level db))))) - ([db func k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to db-transaction*") - (db-transaction* db func (apply hash-map k v kvs)))) + (func (inc-level db)))))) (defmacro with-db-transaction "Evaluates body in the context of a transaction on the specified database connection. @@ -680,10 +666,7 @@ compatibility but it will be removed before a 1.0.0 release." } (map row-fn (rest rs))) (map row-fn rs)))) (result-set-seq rs-or-value {:identifiers identifiers :as-arrays? as-arrays?})) - rs-or-value))) - ([rs-or-value k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to metadata-result") - (metadata-result rs-or-value (apply hash-map k v kvs)))) + rs-or-value)))) (defmacro metadata-query "Given a Java expression that extracts metadata (in the context of with-db-metadata), @@ -872,10 +855,7 @@ compatibility but it will be removed before a 1.0.0 release." } (cons (first rs) (map row-fn (rest rs))) (map row-fn rs)))) - (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?})))))) - ([db sql-params k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to query") - (query db sql-params (apply hash-map k v kvs)))) + (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?}))))))) (defn execute! "Given a database connection and a vector containing SQL (or PreparedStatement) @@ -902,10 +882,7 @@ compatibility but it will be removed before a 1.0.0 release." } (if-let [con (db-find-connection db)] (execute-helper db) (with-open [con (get-connection db)] - (execute-helper (add-connection db con)))))) - ([db sql-params k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to execute!") - (execute! db sql-params (apply hash-map k v kvs)))) + (execute-helper (add-connection db con))))))) (defn- table-str "Transform a table spec to an entity name for SQL. The table spec may be a @@ -939,10 +916,7 @@ compatibility but it will be removed before a 1.0.0 release." } :or {entities identity transaction? true}}] (execute! db (delete-sql table where-clause entities) - {:transaction? transaction?})) - ([db table where-clause k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to delete!") - (delete! db table where-clause (apply hash-map k v kvs)))) + {:transaction? transaction?}))) (defn- multi-insert-helper "Given a (connected) database connection and some SQL statements (for multiple @@ -1002,46 +976,6 @@ compatibility but it will be removed before a 1.0.0 release." } " )")] (vals row)))) -(defn- parse-options - "Given, potentially, options to insert! / create-table-ddl turn them into a - hash map. If the only key is :options, assume the value is the entire options." - [arguments] - (let [options (if (seq arguments) (apply hash-map arguments) {})] - (if (:options options) - (:options options) - options))) - -(defn- parse-insert!-rows - "Given arguments to insert! starting with a map, return a map of all the - rows and any options that follow." - [arguments] - (let [[maps other] (split-with map? arguments) - options (parse-options other)] - {:rows maps :options options})) - -(defn- parse-insert!-cols - "Given arguments to insert! starting with a vector, return a map of all the - column names and values and any options that follow." - [names arguments] - (let [[values other] (split-with vector? arguments) - options (parse-options other)] - {:names names :values values :options options})) - -(defn- parse-insert! - "Given arguments to insert! return a map of the various parts: - rows (maps) or names & values (vectors), options (keyword pairs) - If the keyword :options is present, assume the value is the entire set of - options to pass back, otherwise accumulate key/value pairs." - [arguments] - (cond (map? (first arguments)) - (parse-insert!-rows arguments) - (and (or (nil? (first arguments)) - (vector? (first arguments))) - (vector? (second arguments))) - (parse-insert!-cols (first arguments) (rest arguments)) - :else - (throw (IllegalArgumentException. "insert! expects row maps or column name/value vectors")))) - (defn- insert-rows! "Given a database connection, a table name, a sequence of rows, and an options map, insert the rows into the database." @@ -1067,74 +1001,21 @@ compatibility but it will be removed before a 1.0.0 release." } (with-open [con (get-connection db)] (apply db-do-prepared (add-connection db con) (:transaction? opts) sql-params))))) -(defn- is-options-map? - "Given a map, return true if it seems to be an options map." - [opts] - (let [other (dissoc opts :transaction? :entities)] - (cond (seq other) - false ; it has other keys - (:entities opts) (fn? (:entities opts)) - :else true))) - (defn insert! - "Given a database connection, a table name and either maps representing rows or - a list of column names followed by lists of column values, perform an insert. - The rows or columns may be followed by :options and a map of options (or, for - backward compatibility, just the unrolled options instead, but that is deprecated). + "Given a database connection, a table name and either a map representing a rows, + or a list of column names followed by a list of column values also representing + a single row, perform an insert. + The row map or column value vector may be followed by a map of options: The :transaction? option specifies whether to run in a transaction or not. The default is true (use a transaction). The :entities option specifies how to convert the table name and column names to SQL entities." - {:arglists '([db-spec table row-map & row-maps] - [db-spec table col-name-vec col-val-vec & col-val-vecs] - [db-spec table rows-or-col-name-val-vecs :options options])} ([db table row] (insert! db table row {})) ([db table cols-or-row values-or-opts] (if (map? values-or-opts) - (if (is-options-map? values-or-opts) ; non-legacy version - (insert-rows! db table [cols-or-row] values-or-opts) - (do - (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") - (insert-rows! db table [cols-or-row values-or-opts] {}))) - ;; also non-legacy version: column names and one set of row values + (insert-rows! db table [cols-or-row] values-or-opts) (insert-cols! db table cols-or-row [values-or-opts] {}))) ([db table cols values opts] - ;; could also be - ;; cols values-1 values-2 - ;; or row-1 row-2 row-3 - ;; or row-1 option value - (cond (keyword? values) (do - (println "DEPRECATED: insert! with :options or unrolled key/value arguments") - (if (= :options values) - (insert-rows! db table [cols] opts) - (insert-rows! db table [cols] {values opts}))) - (map? cols) (do - (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") - (insert-rows! db table [cols values opts])) - (map? opts) ; this is the only non-legacy version - (insert-cols! db table cols values opts) - :else (do - (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") - (insert-cols! db table cols [values opts] {})))) - ;; legacy version - ([db table cols-or-row row-or-values-1 row-or-values-2 row-or-values-3 & more] - (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") - (let [{:keys [rows names values options]} - (parse-insert! (concat [cols-or-row row-or-values-1 row-or-values-2 row-or-values-3] more)) - transaction? (:transaction? options true) - entities (:entities options identity)] - (if rows - - (let [stmts (map (fn [row] (insert-single-row-sql table row entities)) rows)] - (if-let [con (db-find-connection db)] - (insert-helper db transaction? stmts) - (with-open [con (get-connection db)] - (insert-helper (add-connection db con) transaction? stmts)))) - - (let [stmts (insert-multi-row-sql table names values entities)] - (if-let [con (db-find-connection db)] - (apply db-do-prepared db transaction? stmts) - (with-open [con (get-connection db)] - (apply db-do-prepared (add-connection db con) transaction? stmts)))))))) + (insert-cols! db table cols [values] opts))) (defn insert-multi! "Given a database connection, a table name and either a sequence of maps (for @@ -1188,68 +1069,28 @@ compatibility but it will be removed before a 1.0.0 release." } :or {entities identity transaction? true}}] (execute! db (update-sql table set-map where-clause entities) - {:transaction? transaction?})) - ([db table set-map where-clause k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to update!") - (update! db table set-map where-clause (apply hash-map k v kvs)))) - -(declare legacy-create-table-ddl) + {:transaction? transaction?}))) (defn create-table-ddl - "Given a table name and column specs return the DDL string for creating that - table. An options map may be provided that can contain: + "Given a table name and a vector of column specs return the DDL string for + creating that table. An options map may be provided that can contain: :table-spec -- a string that is appended to the DDL -- and/or - :entities -- a function to specify how column names are transformed. - For backward compatibility, those options may be specified inline or via a - map introduced with the delimiting keyword :options (but that is deprecated). - In addition, also for backward compatibility, the column specs may be - specified as individual arguments rather than collected into a vector (but - that is also deprecated)." + :entities -- a function to specify how column names are transformed." ([table specs] (create-table-ddl table specs {})) ([table specs opts] - ;; check for deprecated legacy syntax - (if-not (vector? (first specs)) - (legacy-create-table-ddl table specs opts) - (let [table-spec (:table-spec opts) - entities (:entities opts identity) - table-spec-str (or (and table-spec (str " " table-spec)) "") - spec-to-string (fn [spec] - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))))] - (format "CREATE TABLE %s (%s)%s" - (as-sql-name entities table) - (str/join ", " (map spec-to-string specs)) - table-spec-str)))) - ([table spec1 spec2 spec3 & specs] - ;; just in case someone wraps the specs in a vector but still provides :options - ;; this allows for a DEPRECATED warning rather than an unpleasant exception - (if (and (= :options spec2) - (vector? (first spec1))) - (apply legacy-create-table-ddl table (concat spec1 [spec2 spec3] specs)) - (apply legacy-create-table-ddl table spec1 spec2 spec3 specs)))) - -(defn legacy-create-table-ddl - "Deprecated version of create-table-ddl." - [table & specs] - (println "DEPRECATED: unrolled column specs / key/value arguments to create-table-ddl") - (let [[col-specs other] (split-with (complement keyword?) specs) - options (parse-options other)] - (create-table-ddl table col-specs options))) + (let [table-spec (:table-spec opts) + entities (:entities opts identity) + table-spec-str (or (and table-spec (str " " table-spec)) "") + spec-to-string (fn [spec] + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))))] + (format "CREATE TABLE %s (%s)%s" + (as-sql-name entities table) + (str/join ", " (map spec-to-string specs)) + table-spec-str)))) (defn drop-table-ddl "Given a table name, return the DDL string for dropping that table." ([name] (drop-table-ddl name {})) ([name {:keys [entities] :or {entities identity}}] - (format "DROP TABLE %s" (as-sql-name entities name))) - ([name k v & kvs] - (println "DEPRECATED: unrolled key/value arguments to drop-table-ddl") - (drop-table-ddl name (apply hash-map k v kvs)))) - -(defmacro - ^{:doc "Original name for with-db-transaction. Use that instead." - :deprecated "0.3.0"} - db-transaction - [binding & body] - (println "DEPRECATED: Use with-db-transaction instead of db-transaction.") - `(db-transaction* ~(second binding) - (^{:once true} fn* [~(first binding)] ~@body))) + (format "DROP TABLE %s" (as-sql-name entities name)))) diff --git a/src/main/clojure/clojure/java/jdbc/deprecated.clj b/src/main/clojure/clojure/java/jdbc/deprecated.clj deleted file mode 100644 index dc02d736..00000000 --- a/src/main/clojure/clojure/java/jdbc/deprecated.clj +++ /dev/null @@ -1,729 +0,0 @@ -;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. -;; -;; jdbc.clj -;; -;; A Clojure interface to sql databases via jdbc -;; -;; scgilardi (gmail) -;; Created 2 April 2008 -;; -;; seancorfield (gmail) -;; Migrated from clojure.contrib.sql 17 April 2011 - -(ns - ^{ - :author "Stephen C. Gilardi, Sean Corfield", - :doc "A Clojure interface to SQL databases via JDBC - -This namespace contains the old API (0.2.3) which was deprecated in the 0.3.0 -release and is provided for backward compatibility. This API will be removed -completely before a 1.0.0 release so will need to migrate code to the new API -before that release. - -clojure.java.jdbc provides a simple abstraction for CRUD (create, read, -update, delete) operations on a SQL database, along with basic transaction -support. Basic DDL operations are also supported (create table, drop table, -access to table metadata). - -Maps are used to represent records, making it easy to store and retrieve -data. Results can be processed using any standard sequence operations. - -For most operations, Java's PreparedStatement is used so your SQL and -parameters can be represented as simple vectors where the first element -is the SQL string, with ? for each parameter, and the remaining elements -are the parameter values to be substituted. In general, operations return -the number of rows affected, except for a single record insert where any -generated keys are returned (as a map)." } - clojure.java.jdbc.deprecated - (:import [java.net URI] - [java.sql BatchUpdateException DriverManager PreparedStatement ResultSet SQLException Statement] - [java.util Hashtable Map Properties] - [javax.naming InitialContext Name] - [javax.sql DataSource]) - (:refer-clojure :exclude [resultset-seq]) - (:require [clojure.string :as str])) - -(def ^{:private true :dynamic true - :doc "The default entity naming strategy is to do nothing."} - *as-str* - identity) - -(def ^{:private true :dynamic true - :doc "The default keyword naming strategy is to lowercase the entity."} - *as-key* - str/lower-case) - -(defn as-str - "Given a naming strategy and a keyword, return the keyword as a - string per that naming strategy. Given (a naming strategy and) - a string, return it as-is. - A keyword of the form :x.y is treated as keywords :x and :y, - both are turned into strings via the naming strategy and then - joined back together so :x.y might become `x`.`y` if the naming - strategy quotes identifiers with `." - [f x] - (if (instance? clojure.lang.Named x) - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))) - (str x))) - -(defn as-key - "Given a naming strategy and a string, return the string as a - keyword per that naming strategy. Given (a naming strategy and) - a keyword, return it as-is." - [f x] - (if (instance? clojure.lang.Named x) - x - (keyword (f (str x))))) - -(defn as-identifier - "Given a keyword, convert it to a string using the current naming - strategy. - Given a string, return it as-is." - ([x] (as-identifier x *as-str*)) - ([x f-entity] (as-str f-entity x))) - -(defn as-keyword - "Given an entity name (string), convert it to a keyword using the - current naming strategy. - Given a keyword, return it as-is." - ([x] (as-keyword x *as-key*)) - ([x f-keyword] (as-key f-keyword x))) - -(defn- ^Properties as-properties - "Convert any seq of pairs to a java.utils.Properties instance. - Uses as-str to convert both keys and values into strings." - [m] - (let [p (Properties.)] - (doseq [[k v] m] - (.setProperty p (as-str identity k) (as-str identity v))) - p)) - -(def ^{:private true :dynamic true} *db* {:connection nil :level 0}) - -(def ^{:private true :doc "Map of classnames to subprotocols"} classnames - {"postgresql" "org.postgresql.Driver" - "mysql" "com.mysql.jdbc.Driver" - "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver" - "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" - "derby" "org.apache.derby.jdbc.EmbeddedDriver" - "hsqldb" "org.hsqldb.jdbcDriver" - "h2" "org.h2.Driver" - "sqlite" "org.sqlite.JDBC"}) - -(def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols - {"postgres" "postgresql"}) - -(defn find-connection - "Returns the current database connection (or nil if there is none)" - ^java.sql.Connection [] - (:connection *db*)) - -(defn connection - "Returns the current database connection (or throws if there is none)" - ^java.sql.Connection [] - (or (find-connection) - (throw (Exception. "no current database connection")))) - -(defn- parse-properties-uri [^URI uri] - (let [host (.getHost uri) - port (if (pos? (.getPort uri)) (.getPort uri)) - path (.getPath uri) - scheme (.getScheme uri)] - (merge - {:subname (if port - (str "//" host ":" port path) - (str "//" host path)) - :subprotocol (subprotocols scheme scheme)} - (if-let [user-info (.getUserInfo uri)] - {:user (first (str/split user-info #":")) - :password (second (str/split user-info #":"))})))) - -(defn- strip-jdbc [^String spec] - (if (.startsWith spec "jdbc:") - (.substring spec 5) - spec)) - -(defn- get-connection - "Creates a connection to a database. db-spec is a map containing connection - parameters - see with-connection for full details." - [{:keys [factory - connection-uri - classname subprotocol subname - datasource username password - name environment] - :as db-spec}] - (cond - (instance? URI db-spec) - (get-connection (parse-properties-uri db-spec)) - - (string? db-spec) - (get-connection (URI. (strip-jdbc db-spec))) - - factory - (factory (dissoc db-spec :factory)) - - connection-uri - (DriverManager/getConnection connection-uri) - - (and subprotocol subname) - (let [url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname) - classname (or classname (classnames subprotocol))] - (clojure.lang.RT/loadClassForName classname) - (DriverManager/getConnection url (as-properties etc))) - - (and datasource username password) - (.getConnection ^DataSource datasource ^String username ^String password) - - datasource - (.getConnection ^DataSource datasource) - - name - (let [env (and environment (Hashtable. ^Map environment)) - context (InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (.getConnection datasource)) - - :else - (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] - (throw (IllegalArgumentException. msg))))) - -(defn- make-name-unique - "Given a collection of column names and a new column name, - return the new column name made unique, if necessary, by - appending _N where N is some unique integer suffix." - [cols col-name n] - (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] - (if (apply distinct? suffixed-name cols) - suffixed-name - (recur cols col-name (inc n))))) - -(defn- make-cols-unique - "Given a collection of column names, rename duplicates so - that the result is a collection of unique column names." - [cols] - (if (or (empty? cols) (apply distinct? cols)) - cols - (reduce (fn [unique-cols col-name] (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) - -(defn resultset-seq - "Creates and returns a lazy sequence of maps corresponding to - the rows in the java.sql.ResultSet rs. Based on clojure.core/resultset-seq - but it respects the current naming strategy. Duplicate column names are - made unique by appending _N before applying the naming strategy (where - N is a unique integer)." - [^ResultSet rs] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (->> idxs - (map (fn [^Integer i] (.getColumnLabel rsmeta i))) - make-cols-unique - (map (comp keyword *as-key*))) - row-values (fn [] (map (fn [^Integer i] (.getObject rs i)) idxs)) - ;; This used to use create-struct (on keys) and then struct to populate each row. - ;; That had the side effect of preserving the order of columns in each row. As - ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't - ;; want to switch to records so we're using regular maps instead. We no longer - ;; guarantee column order in rows but using into {} should preserve order for up - ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying - ;; on the order-preserving behavior of structmaps, we can reconsider... - rows (fn thisfn [] - (when (.next rs) - (cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))] - (rows))) - -(defn as-quoted-str - "Given a quoting pattern - either a single character or a vector pair of - characters - and a string, return the quoted string: - (as-quoted-str X foo) will return XfooX - (as-quoted-str [A B] foo) will return AfooB" - [q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q))) - -(defn as-named-identifier - "Given a naming strategy and a keyword, return the keyword as a string using the - entity naming strategy. - Given a naming strategy and a string, return the string as-is. - The naming strategy should either be a function (the entity naming strategy) or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or keyword naming strategy respectively." - [naming-strategy x] - (as-identifier x (if (map? naming-strategy) (or (:entity naming-strategy) identity) naming-strategy))) - -(defn as-named-keyword - "Given a naming strategy and a string, return the string as a keyword using the - keyword naming strategy. - Given a naming strategy and a keyword, return the keyword as-is. - The naming strategy should either be a function (the entity naming strategy) or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or keyword naming strategy respectively. - Note that providing a single function will cause the default keyword naming - strategy to be used!" - [naming-strategy x] - (as-keyword x (if (and (map? naming-strategy) (:keyword naming-strategy)) (:keyword naming-strategy) str/lower-case))) - -(defn as-quoted-identifier - "Given a quote pattern - either a single character or a pair of characters in - a vector - and a keyword, return the keyword as a string using a simple - quoting naming strategy. - Given a qote pattern and a string, return the string as-is. - (as-quoted-identifier X :name) will return XnameX as a string. - (as-quoted-identifier [A B] :name) will return AnameB as a string." - [q x] - (as-identifier x (partial as-quoted-str q))) - -(defmacro with-naming-strategy - "Evaluates body in the context of a naming strategy. - The naming strategy is either a function - the entity naming strategy - or - a map containing :entity and/or :keyword keys which provide the entity naming - strategy and/or the keyword naming strategy respectively. The default entity - naming strategy is identity; the default keyword naming strategy is lower-case." - [naming-strategy & body ] - `(binding [*as-str* (if (map? ~naming-strategy) (or (:entity ~naming-strategy) identity) ~naming-strategy) - *as-key* (if (map? ~naming-strategy) (or (:keyword ~naming-strategy) str/lower-case))] ~@body)) - -(defmacro with-quoted-identifiers - "Evaluates body in the context of a simple quoting naming strategy." - [q & body ] - `(binding [*as-str* (partial as-quoted-str ~q)] ~@body)) - -(defn with-connection* - "Evaluates func in the context of a new connection to a database then - closes the connection." - [db-spec func] - (with-open [^java.sql.Connection con (get-connection db-spec)] - (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] - (func)))) - -(defmacro with-connection - "Evaluates body in the context of a new connection to a database then - closes the connection. db-spec is a map containing values for one of the - following parameter sets: - - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DriverManager: - :subprotocol (required) a String, the jdbc subprotocol - :subname (required) a String, the jdbc subname - :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties. - - DataSource: - :datasource (required) a javax.sql.DataSource - :username (optional) a String - :password (optional) a String, required if :username is supplied - - JNDI: - :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map - - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - - URI: - Parsed JDBC connection string - see below - - String: - subprotocol://user:password@host:post/subname - An optional prefix of jdbc: is allowed." - [db-spec & body] - `(with-connection* ~db-spec (fn [] ~@body))) - -(defn- rollback - "Accessor for the rollback flag on the current connection" - ([] - (deref (:rollback *db*))) - ([val] - (swap! (:rollback *db*) (fn [_] val)))) - -(defn transaction* - "Evaluates func as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If rollback is set within scope of the outermost transaction, - the entire transaction will be rolled back rather than committed when - complete." - [func] - (binding [*db* (update-in *db* [:level] inc)] - ;; This ugliness makes it easier to catch SQLException objects - ;; rather than something wrapped in a RuntimeException which - ;; can really obscure your code when working with JDBC from - ;; Clojure... :( - (letfn [(throw-non-rte [^Throwable ex] - (cond (instance? java.sql.SQLException ex) (throw ex) - (and (instance? RuntimeException ex) (.getCause ex)) (throw-non-rte (.getCause ex)) - :else (throw ex)))] - (if (= (:level *db*) 1) - (let [^java.sql.Connection con (connection) - auto-commit (.getAutoCommit con)] - (io! - (.setAutoCommit con false) - (try - (let [result (func)] - (if (rollback) - (.rollback con) - (.commit con)) - result) - (catch Exception e - (.rollback con) - (throw-non-rte e)) - (finally - (rollback false) - (.setAutoCommit con auto-commit))))) - (try - (func) - (catch Exception e - (throw-non-rte e))))))) - -(defmacro transaction - "Evaluates body as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If set-rollback-only is called within scope of the outermost - transaction, the entire transaction will be rolled back rather than - committed when complete." - [& body] - `(transaction* (fn [] ~@body))) - -(defn set-rollback-only - "Marks the outermost transaction such that it will rollback rather than - commit when complete" - [] - (rollback true)) - -(defn is-rollback-only - "Returns true if the outermost transaction will rollback rather than - commit when complete" - [] - (rollback)) - -(defn- execute-batch - "Executes a batch of SQL commands and returns a sequence of update counts. - (-2) indicates a single operation operating on an unknown number of rows. - Specifically, Oracle returns that and we must call getUpdateCount() to get - the actual number of rows affected. In general, operations return an array - of update counts, so this may not be a general solution for Oracle..." - [^Statement stmt] - (let [result (.executeBatch stmt)] - (if (and (= 1 (count result)) (= -2 (first result))) - (list (.getUpdateCount stmt)) - (seq result)))) - -(defn do-commands - "Executes SQL commands on the open database connection." - [& commands] - (with-open [^Statement stmt (let [^java.sql.Connection con (connection)] (.createStatement con))] - (doseq [^String cmd commands] - (.addBatch stmt cmd)) - (transaction - (execute-batch stmt)))) - -(def ^{:private true - :doc "Map friendly :concurrency values to ResultSet constants."} - result-set-concurrency - {:read-only ResultSet/CONCUR_READ_ONLY - :updatable ResultSet/CONCUR_UPDATABLE}) - -(def ^{:private true - :doc "Map friendly :cursors values to ResultSet constants."} - result-set-holdability - {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT - :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) - -(def ^{:private true - :doc "Map friendly :type values to ResultSet constants."} - result-set-type - {:forward-only ResultSet/TYPE_FORWARD_ONLY - :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE - :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) - -(defn prepare-statement - "Create a prepared statement from a connection, a SQL string and an - optional list of parameters: - :return-keys true | false - default false - :result-type :forward-only | :scroll-insensitive | :scroll-sensitive - :concurrency :read-only | :updatable - :fetch-size n - :max-rows n" - [^java.sql.Connection con ^String sql & {:keys [return-keys result-type concurrency cursors fetch-size max-rows]}] - (let [^PreparedStatement stmt (cond - return-keys (try - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS) - (catch Exception _ - ;; assume it is unsupported and try basic PreparedStatement: - (.prepareStatement con sql))) - (and result-type concurrency) (if cursors - (.prepareStatement con sql - (result-type result-set-type) - (concurrency result-set-concurrency) - (cursors result-set-holdability)) - (.prepareStatement con sql - (result-type result-set-type) - (concurrency result-set-concurrency))) - :else (.prepareStatement con sql))] - (when fetch-size (.setFetchSize stmt fetch-size)) - (when max-rows (.setMaxRows stmt max-rows)) - stmt)) - -(defn- set-parameters - "Add the parameters to the given statement." - [^PreparedStatement stmt params] - (dorun - (map-indexed - (fn [ix value] - (.setObject stmt (inc ix) value)) - params))) - -(defn do-prepared - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. Each param-group is a seq of values for all of - the parameters. - Return a seq of update counts (one count for each param-group)." - [sql & param-groups] - (with-open [^PreparedStatement stmt (prepare-statement (connection) sql)] - (if (empty? param-groups) - (transaction* (fn [] (vector (.executeUpdate stmt)))) - (do - (doseq [param-group param-groups] - (set-parameters stmt param-group) - (.addBatch stmt)) - (transaction* (fn [] (execute-batch stmt))))))) - -(defn create-table-ddl - "Given a table name and column specs with an optional table-spec - return the DDL string for creating a table based on that." - [name & specs] - (let [split-specs (partition-by #(= :table-spec %) specs) - col-specs (first split-specs) - table-spec (first (second (rest split-specs))) - table-spec-str (or (and table-spec (str " " table-spec)) "") - specs-to-string (fn [specs] - (apply str - (map as-identifier - (apply concat - (interpose [", "] - (map (partial interpose " ") specs))))))] - (format "CREATE TABLE %s (%s)%s" - (as-identifier name) - (specs-to-string col-specs) - table-spec-str))) - -(defn create-table - "Creates a table on the open database connection given a table name and - specs. Each spec is either a column spec: a vector containing a column - name and optionally a type and other constraints, or a table-level - constraint: a vector containing words that express the constraint. An - optional suffix to the CREATE TABLE DDL describing table attributes may - by provided as :table-spec {table-attributes-string}. All words used to - describe the table may be supplied as strings or keywords." - [name & specs] - (do-commands (apply create-table-ddl name specs))) - -(defn drop-table - "Drops a table on the open database connection given its name, a string - or keyword" - [name] - (do-commands - (format "DROP TABLE %s" (as-identifier name)))) - -(defn do-prepared-return-keys - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. The param-group is a seq of values for all of - the parameters. - Return the generated keys for the (single) update/insert." - [sql param-group] - (with-open [^PreparedStatement stmt (prepare-statement (connection) sql :return-keys true)] - (set-parameters stmt param-group) - (transaction* (fn [] (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (resultset-seq rs))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))))) - -(defn insert-values - "Inserts rows into a table with values for specified columns only. - column-names is a vector of strings or keywords identifying columns. Each - value-group is a vector containing a value for each column in - order. When inserting complete rows (all columns), consider using - insert-rows instead. - If a single set of values is inserted, returns a map of the generated keys." - [table column-names & value-groups] - (let [column-strs (map as-identifier column-names) - n (count (first value-groups)) - return-keys (= 1 (count value-groups)) - prepared-statement (if return-keys do-prepared-return-keys do-prepared) - template (apply str (interpose "," (repeat n "?"))) - columns (if (seq column-names) - (format "(%s)" (apply str (interpose "," column-strs))) - "")] - (apply prepared-statement - (format "INSERT INTO %s %s VALUES (%s)" - (as-identifier table) columns template) - value-groups))) - -(defn insert-rows - "Inserts complete rows into a table. Each row is a vector of values for - each of the table's columns in order. - If a single row is inserted, returns a map of the generated keys." - [table & rows] - (apply insert-values table nil rows)) - -(defn insert-records - "Inserts records into a table. records are maps from strings or keywords - (identifying columns) to values. Inserts the records one at a time. - Returns a sequence of maps containing the generated keys for each record." - [table & records] - (let [ins-v (fn [record] (insert-values table (keys record) (vals record)))] - (doall (map ins-v records)))) - -(defn insert-record - "Inserts a single record into a table. A record is a map from strings or - keywords (identifying columns) to values. - Returns a map of the generated keys." - [table record] - (let [keys (insert-records table record)] - (first keys))) - -(defn delete-rows - "Deletes rows from a table. where-params is a vector containing a string - providing the (optionally parameterized) selection criteria followed by - values for any parameters." - [table where-params] - (let [[where & params] where-params] - (do-prepared - (format "DELETE FROM %s WHERE %s" - (as-identifier table) where) - params))) - -(defn update-values - "Updates values on selected rows in a table. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." - [table where-params record] - (let [[where & params] where-params - column-strs (map as-identifier (keys record)) - columns (apply str (concat (interpose "=?, " column-strs) "=?"))] - (do-prepared - (format "UPDATE %s SET %s WHERE %s" - (as-identifier table) columns where) - (concat (vals record) params)))) - -(defn update-or-insert-values - "Updates values on selected rows in a table, or inserts a new row when no - existing row matches the selection criteria. where-params is a vector - containing a string providing the (optionally parameterized) selection - criteria followed by values for any parameters. record is a map from - strings or keywords (identifying columns) to updated values." - [table where-params record] - (transaction - (let [result (update-values table where-params record)] - (if (zero? (first result)) - (insert-values table (keys record) (vals record)) - result)))) - -(defn with-query-results* - "Executes a query, then evaluates func passing in a seq of the results as - an argument. The first argument is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs - See prepare-statement for supported options." - [sql-params func] - (when-not (vector? sql-params) - (let [^Class sql-params-class (class sql-params) - ^String msg (format "\"%s\" expected %s %s, found %s %s" - "sql-params" - "vector" - "[sql param*]" - (.getName sql-params-class) - (pr-str sql-params))] - (throw (IllegalArgumentException. msg)))) - (let [special (first sql-params) - sql-is-first (string? special) - options-are-first (map? special) - sql (cond sql-is-first special - options-are-first (second sql-params)) - params (vec (cond sql-is-first (rest sql-params) - options-are-first (rest (rest sql-params)) - :else (rest sql-params))) - prepare-args (when (map? special) (flatten (seq special)))] - (with-open [^PreparedStatement stmt (if (instance? PreparedStatement special) special (apply prepare-statement (connection) sql prepare-args))] - (set-parameters stmt params) - (with-open [rset (.executeQuery stmt)] - (func (resultset-seq rset)))))) - -(defmacro with-query-results - "Executes a query, then evaluates body with results bound to a seq of the - results. sql-params is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, follwed by any parameters it needs - See prepare-statement for supported options." - [results sql-params & body] - `(with-query-results* ~sql-params (fn [~results] ~@body))) - -(defn print-sql-exception - "Prints the contents of an SQLException to *out*" - [^SQLException exception] - (let [^Class exception-class (class exception)] - (println - (format (str "%s:" \newline - " Message: %s" \newline - " SQLState: %s" \newline - " Error Code: %d") - (.getSimpleName exception-class) - (.getMessage exception) - (.getSQLState exception) - (.getErrorCode exception))))) - -(defn print-sql-exception-chain - "Prints a chain of SQLExceptions to *out*" - [^SQLException exception] - (loop [e exception] - (when e - (print-sql-exception e) - (recur (.getNextException e))))) - -(def ^{:private true} special-counts - {Statement/EXECUTE_FAILED "EXECUTE_FAILED" - Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) - -(defn print-update-counts - "Prints the update counts from a BatchUpdateException to *out*" - [^BatchUpdateException exception] - (println "Update counts:") - (dorun - (map-indexed - (fn [index count] - (println (format " Statement %d: %s" - index - (get special-counts count count)))) - (.getUpdateCounts exception)))) diff --git a/src/test/clojure/clojure/java/test_deprecated.clj b/src/test/clojure/clojure/java/test_deprecated.clj deleted file mode 100644 index cfa67d6e..00000000 --- a/src/test/clojure/clojure/java/test_deprecated.clj +++ /dev/null @@ -1,411 +0,0 @@ -;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By -;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, -;; from this software. -;; -;; test_jdbc.clj -;; -;; This namespace contains tests that exercise the deprecated API for java.jdbc -;; so these tests expect databases to be available. Embedded databases can -;; be tested without external infrastructure (Apache Derby, HSQLDB). Other -;; databases will be available for testing in different environments. The -;; available databases for testing can be configured below. -;; -;; scgilardi (gmail) -;; Created 13 September 2008 -;; -;; seancorfield (gmail) -;; Migrated from clojure.contrib.test-sql 17 April 2011 - -(ns clojure.java.test-deprecated - (:use clojure.test) - (:require [clojure.java.jdbc.deprecated :as sql])) - -;; Set test-databases according to whether you have the local database available: -;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] -;; Apache Derby and HSQLDB can run without an external setup. -(def test-databases - (if-let [dbs (System/getenv "TEST_DBS")] - (map keyword (.split dbs ",")) - ;; enable more by default once the build server is equipped? - [:derby :hsqldb :h2 :sqlite])) - -;; MS SQL Server requires more specialized configuration: -(def mssql-host - (if-let [host (System/getenv "TEST_MSSQL_HOST")] host "127.0.0.1\\SQLEXPRESS")) -(def mssql-port - (if-let [port (System/getenv "TEST_MSSQL_PORT")] port "1433")) -(def mssql-user - (if-let [user (System/getenv "TEST_MSSQL_USER")] user "sa")) -(def mssql-pass - (if-let [pass (System/getenv "TEST_MSSQL_PASS")] pass "")) -(def mssql-dbname - (if-let [name (System/getenv "TEST_MSSQL_NAME")] name "clojure_test")) -(def jtds-host - (if-let [host (System/getenv "TEST_JTDS_HOST")] host mssql-host)) -(def jtds-port - (if-let [port (System/getenv "TEST_JTDS_PORT")] port mssql-port)) -(def jtds-user - (if-let [user (System/getenv "TEST_JTDS_USER")] user mssql-user)) -(def jtds-pass - (if-let [pass (System/getenv "TEST_JTDS_PASS")] pass mssql-pass)) -(def jtds-dbname - (if-let [name (System/getenv "TEST_JTDS_NAME")] name mssql-dbname)) - -;; database connections used for testing: - -(def mysql-db {:subprotocol "mysql" - :subname "//127.0.0.1:3306/clojure_test" - :user "clojure_test" - :password "clojure_test"}) - -(def derby-db {:subprotocol "derby" - :subname "clojure_test_derby" - :create true}) - -(def hsqldb-db {:subprotocol "hsqldb" - :subname "clojure_test_hsqldb"}) - -(def h2-db {:subprotocol "h2" - :subname "./clojure_test_h2"}) - -(def sqlite-db {:subprotocol "sqlite" - :subname "clojure_test_sqlite"}) - -(def postgres-db {:subprotocol "postgresql" - :subname "clojure_test" - :user "clojure_test" - :password "clojure_test"}) - -(def mssql-db {:subprotocol "sqlserver" - :subname (str "//" mssql-host ":" mssql-port ";DATABASENAME=" mssql-dbname) - :user mssql-user - :password mssql-pass}) - -(def jtds-db {:subprotocol "jtds:sqlserver" - :subname (str "//" jtds-host ":" jtds-port "/" jtds-dbname) - :user jtds-user - :password jtds-pass}) - -;; To test against the stringified DB connection settings: -(def mysql-str-db - "mysql://clojure_test:clojure_test@localhost:3306/clojure_test") - -(def mysql-jdbc-str-db - "jdbc:mysql://clojure_test:clojure_test@localhost:3306/clojure_test") - -(def postgres-str-db - "postgres://clojure_test:clojure_test@localhost/clojure_test") - -(defn- test-specs - "Return a sequence of db-spec maps that should be used for tests" - [] - (for [db test-databases] - @(ns-resolve 'clojure.java.test-deprecated (symbol (str (name db) "-db"))))) - -(defn- clean-up - "Attempt to drop any test tables before we start a test." - [t] - (doseq [db (test-specs)] - (sql/with-connection db - (doseq [table [:fruit :fruit2 :veggies :veggies2]] - (try - (sql/drop-table table) - (catch Exception _ - ;; ignore - ))))) - (t)) - -(use-fixtures - :each clean-up) - -;; We start with all tables dropped and each test has to create the tables -;; necessary for it to do its job, and populate it as needed... - -(defn- create-test-table - "Create a standard test table. Must be inside with-connection. - For MySQL, ensure table uses an engine that supports transactions!" - [table db] - (let [p (:subprotocol db)] - (sql/create-table - table - [:id :int (if (= "mysql" p) "PRIMARY KEY AUTO_INCREMENT" "DEFAULT 0")] - [:name "VARCHAR(32)" (if (= "mysql" p) "" "PRIMARY KEY")] - [:appearance "VARCHAR(32)"] - [:cost :int] - [:grade :real] - :table-spec (if (or (= "mysql" p) (and (string? db) (re-find #"mysql:" db))) - "ENGINE=InnoDB" "")))) - -(deftest test-create-table - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) - -(deftest test-drop-table - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/drop-table :fruit2) - (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) - -(deftest test-do-commands - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-commands "DROP TABLE fruit2") - (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) - -(deftest test-do-prepared1 - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) - -(deftest test-do-prepared2 - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "DROP TABLE fruit2") - (is (thrown? java.sql.SQLException (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) - -(deftest test-do-prepared3 - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) - -(deftest test-do-prepared4 - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit2 db) - (sql/do-prepared "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit2"] (count res))))))) - -(deftest test-insert-rows - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-rows - :fruit - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])] - (is (= '(1 1 1 1) r))) - (is (= 4 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Apple" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "red"] (:name (first res))))) - (is (= "juicy" (sql/with-query-results res ["SELECT * FROM fruit WHERE name = ?" "Orange"] (:appearance (first res)))))))) - -(deftest test-insert-values - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-values - :fruit - [:name :cost] - ["Mango" 722] - ["Feijoa" 441])] - (is (= '(1 1) r))) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Mango" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 722] (:name (first res)))))))) - -(deftest test-insert-records - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-records - :fruit - {:name "Pomegranate" :appearance "fresh" :cost 585} - {:name "Kiwifruit" :grade 93})] - (condp = (:subprotocol db) - nil nil ; for the string connection args - "postgresql" (is (= 2 (count r))) - "mysql" (is (= '({:generated_key 1} {:generated_key 2}) r)) - "sqlserver" (is (= '({:generated_keys nil} {:generated_keys nil}) r)) - "jtds:sqlserver" (is (= '({:id nil} {:id nil}) r)) - "hsqldb" (is (= '(nil nil) r)) - "h2" (is (= '(nil nil) r)) - "sqlite" (is (= (list {(keyword "last_insert_rowid()") 1} - {(keyword "last_insert_rowid()") 2}) r)) - "derby" (is (= '({:1 nil} {:1 nil}) r)))) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Pomegranate" (sql/with-query-results res ["SELECT * FROM fruit WHERE cost = ?" 585] (:name (first res)))))))) - -(deftest test-update-values - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (let [r (sql/insert-rows - :fruit - [1 "Apple" "red" 59 87] - [2 "Banana" "yellow" 29 92.2] - [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6])] - (is (= '(1 1 1 1) r))) - (sql/update-values - :fruit - ["name=?" "Banana"] - {:appearance "bruised" :cost 14}) - (is (= 4 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= "Apple" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "red"] (:name (first res))))) - (is (= "Banana" (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] (:name (first res))))) - (is (= 14 (sql/with-query-results res ["SELECT * FROM fruit WHERE name = ?" "Banana"] (:cost (first res)))))))) - -(deftest test-update-or-insert-values - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (sql/update-or-insert-values - :fruit - ["name=?" "Pomegranate"] - {:name "Pomegranate" :appearance "fresh" :cost 585}) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= 585 (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] (:cost (first res))))) - (sql/update-or-insert-values - :fruit - ["name=?" "Pomegranate"] - {:name "Pomegranate" :appearance "ripe" :cost 565}) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (is (= 565 (sql/with-query-results res ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] (:cost (first res))))) - (sql/update-or-insert-values - :fruit - ["name=?" "Apple"] - {:name "Apple" :appearance "green" :cost 74}) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) - -(deftest test-partial-exception - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"]) - (is (= 2 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))) - (throw (Exception. "deliberate exception"))) - (catch Exception _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))))) - -(deftest test-sql-exception - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - ;; sqlite does not throw exception for too many items - (throw (java.sql.SQLException.))) - (catch java.sql.SQLException _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) - -(deftest test-rollback - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (is (not (sql/is-rollback-only))) - (sql/set-rollback-only) - (is (sql/is-rollback-only)) - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]) - (is (= 3 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))) - (catch java.sql.SQLException _ - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) - -(deftest test-transactions-with-possible-generated-keys-result-set - (doseq [db (test-specs)] - (sql/with-connection db - (create-test-table :fruit db) - (try - (sql/transaction - (sql/set-rollback-only) - (sql/insert-values - :fruit - [:name :appearance] - ["Grape" "yummy"]) - (is (= 1 (sql/with-query-results res ["SELECT * FROM fruit"] (count res)))))) - (is (= 0 (sql/with-query-results res ["SELECT * FROM fruit"] (count res))))))) - -(deftest test-metadata - (doseq [db (test-specs)] - (when-not (and (map? db) (.endsWith ^String (:subprotocol db) "sqlserver")) - (let [metadata (sql/with-connection - db - (into [] - (sql/resultset-seq - (-> (sql/connection) - (.getMetaData) - (.getTables nil nil nil (into-array ["TABLE" "VIEW"]))))))] - (is (= [] metadata)))))) - -;; basic tests for keyword / entity conversion - -(deftest test-as-identifier - (is (= "kw" (sql/as-identifier "kw"))) - (is (= "kw" (sql/as-identifier :kw))) - (is (= "KW" (sql/as-identifier "KW"))) - (is (= "KW" (sql/as-identifier :KW))) - (is (= "k.w" (sql/as-identifier :k.w)))) - -(deftest test-as-keyword - (is (= :kw (sql/as-keyword "kw"))) - (is (= :kw (sql/as-keyword :kw))) - (is (= :kw (sql/as-keyword "KW"))) - (is (= :KW (sql/as-keyword :KW))) - (is (= :k.w (sql/as-keyword :k.w)))) - -(deftest test-quoted - (is (= "kw" (sql/as-quoted-identifier [ \[ \] ] "kw"))) - (is (= "[kw]" (sql/as-quoted-identifier [ \[ \] ] :kw))) - (is (= "KW" (sql/as-quoted-identifier \` "KW"))) - (is (= "`KW`" (sql/as-quoted-identifier \` :KW))) - (is (= "`k`.`w`" (sql/as-quoted-identifier \` :k.w)))) - -(def quote-dash { :entity (partial sql/as-quoted-str \`) :keyword #(.replace % "_" "-") }) - -(deftest test-named - (is (= "kw" (sql/as-named-identifier quote-dash "kw"))) - (is (= "`kw`" (sql/as-named-identifier quote-dash :kw))) - (is (= "`k`.`w`" (sql/as-named-identifier quote-dash :k.w))) - (is (= :K-W (sql/as-named-keyword quote-dash "K_W"))) - (is (= :K_W (sql/as-named-keyword quote-dash :K_W))) - (is (= :k.w (sql/as-named-keyword quote-dash :k.w)))) - -(deftest test-with-quote - (sql/with-quoted-identifiers [ \[ \] ] - (is (= "kw" (sql/as-identifier "kw"))) - (is (= "[kw]" (sql/as-identifier :kw))) - (is (= "KW" (sql/as-identifier "KW"))) - (is (= "[KW]" (sql/as-identifier :KW))) - (is (= "[k].[w]" (sql/as-identifier :k.w))))) - -(deftest test-with-naming - (sql/with-naming-strategy quote-dash - (is (= "kw" (sql/as-identifier "kw"))) - (is (= "`kw`" (sql/as-identifier :kw))) - (is (= "`k`.`w`" (sql/as-identifier :k.w))) - (is (= :K-W (sql/as-keyword "K_W"))) - (is (= :K_W (sql/as-keyword :K_W))) - (is (= :k.w (sql/as-keyword :k.w))))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 180d8ce2..44f0893d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -709,6 +709,27 @@ new-keys (if (postgres? db) (map :id new-keys) new-keys)] (is (= [(returned-key db 1)] new-keys))))) +(deftest insert-one-row-opts + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [(returned-key db 1)] new-keys))))) + +(deftest insert-one-col-val + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit [:name] ["Apple"]) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [1] new-keys))))) + +(deftest insert-one-col-val-opts + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit [:name] ["Apple"] {}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [1] new-keys))))) + (deftest insert-query (doseq [db (test-specs)] (create-test-table :fruit db) From 8a2acd9a1fafd25c8e27c33016590d8d540667d3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Apr 2016 11:52:11 -0700 Subject: [PATCH 331/630] Fix JDBC-121 by wrapping single vector of values So that `(insert! db table [:col] ["val"] {})` works correctly. --- src/main/clojure/clojure/java/jdbc.clj | 2 +- src/test/clojure/clojure/java/test_jdbc.clj | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c1514731..c4f3dd1c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1111,7 +1111,7 @@ compatibility but it will be removed before a 1.0.0 release." } (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") (insert-rows! db table [cols values opts])) (map? opts) ; this is the only non-legacy version - (insert-cols! db table cols values opts) + (insert-cols! db table cols [values] opts) :else (do (println "DEPRECATED: insert! with multiple rows; use insert-multi! instead") (insert-cols! db table cols [values opts] {})))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 180d8ce2..44f0893d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -709,6 +709,27 @@ new-keys (if (postgres? db) (map :id new-keys) new-keys)] (is (= [(returned-key db 1)] new-keys))))) +(deftest insert-one-row-opts + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [(returned-key db 1)] new-keys))))) + +(deftest insert-one-col-val + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit [:name] ["Apple"]) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [1] new-keys))))) + +(deftest insert-one-col-val-opts + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit [:name] ["Apple"] {}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [1] new-keys))))) + (deftest insert-query (doseq [db (test-specs)] (create-test-table :fruit db) From 72123e74e030be8e2821928bfc2b8ac16d7dcf81 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Apr 2016 11:56:29 -0700 Subject: [PATCH 332/630] Prep for 0.5.7 --- CHANGES.md | 4 ++++ README.md | 9 ++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 982c7f0f..b5ede1f5 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.5.7 + +* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). + Changes in 0.5.6 * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. diff --git a/README.md b/README.md index a3c0c08a..10a47d99 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.5.6 +Latest stable release: 0.5.7 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.5.6 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.5.6"] +[org.clojure/java.jdbc "0.5.7"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.5.6 + 0.5.7 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,9 @@ Developer Information Change Log ==================== +* Release 0.5.7 on 2016-04-10 + * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). + * Release 0.5.6 on 2016-04-10 * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). - If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. From 846414f35a8c2323b03f6b3f3caaa175993b8045 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 10 Apr 2016 13:59:24 -0500 Subject: [PATCH 333/630] [maven-release-plugin] prepare release java.jdbc-0.5.7 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95806b9f..cb955566 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.5.7 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.5.7 From fa8dad6ab85bb6a27cf5408bee5dcfcab713db4e Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 10 Apr 2016 13:59:24 -0500 Subject: [PATCH 334/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index cb955566..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.7 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.5.7 + HEAD From 04df6ac7b38d4685018afb939cbbc21db0cb1350 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Apr 2016 12:09:02 -0700 Subject: [PATCH 335/630] Prep for 0.6.0 --- CHANGES.md | 8 ++++++++ project.clj | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index b5ede1f5..75295e43 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,11 @@ +Changes coming in 0.6.0 + +* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). + - See changes described in versions 0.5.5 and 0.5.6 for what was deprecated + - Use version 0.5.7 as a bridge to identify any deprecated API calls on which your code relies! + - `db-transaction` (deprecated in version 0.3.0) has been removed + - The `java.jdbc.deprecated` namespace has been removed + Changes in 0.5.7 * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). diff --git a/project.clj b/project.clj index cc1dddb7..ab006a94 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.6-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.6.0-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 16954109a673a1c20d5ca35b0d500dd8269df817 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Apr 2016 14:49:23 -0700 Subject: [PATCH 336/630] First part of JDBC-122: db-do-commands --- CHANGES.md | 4 ++ src/main/clojure/clojure/java/jdbc.clj | 46 ++++++++++++++------- src/test/clojure/clojure/java/test_jdbc.clj | 29 +++++++++++++ 3 files changed, 63 insertions(+), 16 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b5ede1f5..23ccca5f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.5.8 + +* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning to printed to the console. + Changes in 0.5.7 * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c4f3dd1c..78feaa3d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -700,23 +700,37 @@ compatibility but it will be removed before a 1.0.0 release." } (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it - defaults to true. + defaults to true. Accepts a single SQL command (string) or a vector of them. + For backward compatibility, also accepts multiple string arguments but that + is deprecated and will be removed in 0.6.0. Uses executeBatch. This may affect what SQL you can run via db-do-commands." - {:arglists '([db-spec sql-command & sql-commands] - [db-spec transaction? sql-command & sql-commands])} - [db transaction? & commands] - (if (string? transaction?) - (apply db-do-commands db true transaction? commands) - (if-let [con (db-find-connection db)] - (with-open [^Statement stmt (.createStatement con)] - (doseq [^String cmd commands] - (.addBatch stmt cmd)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt))) - (with-open [con (get-connection db)] - (apply db-do-commands (add-connection db con) transaction? commands))))) + ([db sql-commands] + (db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands))) + ([db transaction? sql-commands] + (cond (string? transaction?) + ;; legacy call with two commands + (do + (println "DEPRECATED: unrolled SQL string arguments in db-do-commands") + (db-do-commands db true [transaction? sql-commands])) + (string? sql-commands) + ;; (db-do-commands db bool-val "SQL string") is acceptable + (db-do-commands db transaction? [sql-commands]) + :else + (if-let [con (db-find-connection db)] + (with-open [^Statement stmt (.createStatement con)] + (doseq [^String cmd sql-commands] + (.addBatch stmt cmd)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt))) + (with-open [con (get-connection db)] + (db-do-commands (add-connection db con) transaction? sql-commands))))) + ([db t-or-cmd cmd-1 cmd-2 & cmds] + (println "DEPRECATED: unrolled SQL string arguments in db-do-commands") + (if (string? t-or-cmd) + (db-do-commands db true (concat [t-or-cmd cmd-1 cmd-2] cmds)) + (db-do-commands db t-or-cmd (concat [cmd-1 cmd-2] cmds))))) (defn- db-do-execute-prepared-return-keys "Executes a PreparedStatement, optionally in a transaction, and (attempts to) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 44f0893d..e5f94dfe 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -246,6 +246,35 @@ (is (thrown? java.sql.SQLException (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) +(deftest test-do-commands-transaction + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-commands db true "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) + +(deftest test-do-commands-multi + (doseq [db (test-specs)] + (sql/db-do-commands db + [(sql/create-table-ddl :fruit3 + [[:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int]]) + "DROP TABLE fruit3"]) + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) + +(deftest test-do-commands-multi-transaction + (doseq [db (test-specs)] + (sql/db-do-commands db true + [(sql/create-table-ddl :fruit3 + [[:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int]]) + "DROP TABLE fruit3"]) + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) + (deftest test-do-prepared1a (doseq [db (test-specs)] (create-test-table :fruit2 db) From 8b9a89a5006485b7d0c7b9fefee9281e3435e1b5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 10 Apr 2016 16:21:03 -0700 Subject: [PATCH 337/630] First cut of db-do-prepared - nothing deprecated yet JDBC-122 This just reorganizes the code to prepare for identifying the deprecated cases. I need to add several more tests before I move forward, to ensure I'm covering all cases. Then rewrite any uses of db-do-prepared to use the new argument format. Then I need to figure out what to do about [sql a b c] vs [sql [a] [b] [c]]. --- src/main/clojure/clojure/java/jdbc.clj | 37 +++++++++++++++++--------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 78feaa3d..3ac3e77f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -798,17 +798,30 @@ compatibility but it will be removed before a 1.0.0 release." } Return a seq of update counts (one count for each param-group)." {:arglists '([db-spec sql & param-groups] [db-spec transaction? sql & param-groups])} - [db transaction? & [sql & param-groups :as opts]] - (if (or (string? transaction?) - (instance? PreparedStatement transaction?)) - (apply db-do-prepared db true transaction? opts) - (if-let [con (db-find-connection db)] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql param-groups transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql)] - (db-do-execute-prepared-statement db stmt param-groups transaction?))) - (with-open [con (get-connection db)] - (apply db-do-prepared (add-connection db con) transaction? sql param-groups))))) + ([db sql-param-groups] + (db-do-prepared db true sql-param-groups)) + ([db transaction? sql-param-groups] + (cond (string? transaction?) + ;; legacy deprecated + (db-do-prepared db true [transaction? sql-param-groups]) + (or (string? sql-param-groups) + (instance? PreparedStatement sql-param-groups)) + ;; string or stmt is acceptable, no param groups + (db-do-prepared db transaction? [sql-param-groups]) + :else + (let [[sql & param-groups] sql-param-groups] + (if-let [con (db-find-connection db)] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-statement db sql param-groups transaction?) + (with-open [^PreparedStatement stmt (prepare-statement con sql)] + (db-do-execute-prepared-statement db stmt param-groups transaction?))) + (with-open [con (get-connection db)] + (db-do-prepared (add-connection db con) transaction? sql-param-groups)))))) + ([db t-or-sql-p-g sql-pg-1 pg-2 & pgs] + ;; legacy deprecated + (if (string? t-or-sql-p-g) + (db-do-prepared db true (concat [t-or-sql-p-g sql-pg-1 pg-2] pgs)) + (db-do-prepared db t-or-sql-p-g (concat [sql-pg-1 pg-2] pgs))))) (defn db-query-with-resultset "Executes a query, then evaluates func passing in the raw ResultSet as an @@ -907,7 +920,7 @@ compatibility but it will be removed before a 1.0.0 release." } :or {transaction? true multi? false}}] (let [param-groups (rest sql-params) execute-helper - (^{:once true} fn* [db] + (^{:once true} fn* [db] (if multi? (apply db-do-prepared db transaction? (first sql-params) param-groups) (if (seq param-groups) From 5eb70bba981c5fe81862d59bf0d8b59898cc3919 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 11 Apr 2016 11:24:32 -0700 Subject: [PATCH 338/630] Clean up db-do-prepared calls JDBC-122 Movely remove `apply` from calls; add tests to ensure `[prepare-args sql params]` and `[prepared-stmt params]` work as expected. --- CHANGES.md | 3 ++- src/main/clojure/clojure/java/jdbc.clj | 28 ++++++++++----------- src/test/clojure/clojure/java/test_jdbc.clj | 11 +++++++- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 23ccca5f..d7ee255b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.5.8 -* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning to printed to the console. +* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. +* `db-do-prepared` now expects to receive a `db-spec`, an optional `transaction?` boolean, and a final argument that is either a `PreparedStatement`, a SQL string, or a vector containing a SQL string followed by parameter groups -- vectors of parameters values, like the `:multi? true` version of `execute!` [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with multiple arguments -- the SQL string / statement and the parameter groups unrolled is deprecated and will produce "DEPRECATED" warnings printed to the console. Changes in 0.5.7 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 3ac3e77f..93527d90 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -796,8 +796,6 @@ compatibility but it will be removed before a 1.0.0 release." } the parameters. transaction? can be omitted and defaults to true. The sql parameter can either be a SQL string or a PreparedStatement. Return a seq of update counts (one count for each param-group)." - {:arglists '([db-spec sql & param-groups] - [db-spec transaction? sql & param-groups])} ([db sql-param-groups] (db-do-prepared db true sql-param-groups)) ([db transaction? sql-param-groups] @@ -863,10 +861,10 @@ compatibility but it will be removed before a 1.0.0 release." } (let [^PreparedStatement stmt special] (run-query-with-params stmt)) (if-let [con (db-find-connection db)] - (with-open [^PreparedStatement stmt (apply prepare-statement con sql prepare-args)] + (with-open [^PreparedStatement stmt (prepare-statement con sql prepare-args)] (run-query-with-params stmt)) (with-open [con (get-connection db)] - (with-open [^PreparedStatement stmt (apply prepare-statement con sql prepare-args)] + (with-open [^PreparedStatement stmt (prepare-statement con sql prepare-args)] (run-query-with-params stmt))))))) ;; top-level API for actual SQL operations @@ -920,12 +918,14 @@ compatibility but it will be removed before a 1.0.0 release." } :or {transaction? true multi? false}}] (let [param-groups (rest sql-params) execute-helper - (^{:once true} fn* [db] + (^{:once true} fn* [db] (if multi? - (apply db-do-prepared db transaction? (first sql-params) param-groups) + ;; already in the correct form: [sql [params] [params]] + (db-do-prepared db transaction? sql-params) (if (seq param-groups) - (db-do-prepared db transaction? (first sql-params) param-groups) - (db-do-prepared db transaction? (first sql-params)))))] + ;; single param group: convert to correct form + (db-do-prepared db transaction? [(first sql-params) param-groups]) + (db-do-prepared db transaction? sql-params))))] (if-let [con (db-find-connection db)] (execute-helper db) (with-open [con (get-connection db)] @@ -1090,9 +1090,9 @@ compatibility but it will be removed before a 1.0.0 release." } [db table cols values opts] (let [sql-params (insert-multi-row-sql table cols values (:entities opts identity))] (if-let [con (db-find-connection db)] - (apply db-do-prepared db (:transaction? opts) sql-params) + (db-do-prepared db (:transaction? opts) sql-params) (with-open [con (get-connection db)] - (apply db-do-prepared (add-connection db con) (:transaction? opts) sql-params))))) + (db-do-prepared (add-connection db con) (:transaction? opts) sql-params))))) (defn- is-options-map? "Given a map, return true if it seems to be an options map." @@ -1159,9 +1159,9 @@ compatibility but it will be removed before a 1.0.0 release." } (let [stmts (insert-multi-row-sql table names values entities)] (if-let [con (db-find-connection db)] - (apply db-do-prepared db transaction? stmts) + (db-do-prepared db transaction? stmts) (with-open [con (get-connection db)] - (apply db-do-prepared (add-connection db con) transaction? stmts)))))))) + (db-do-prepared (add-connection db con) transaction? stmts)))))))) (defn insert-multi! "Given a database connection, a table name and either a sequence of maps (for @@ -1241,8 +1241,8 @@ compatibility but it will be removed before a 1.0.0 release." } entities (:entities opts identity) table-spec-str (or (and table-spec (str " " table-spec)) "") spec-to-string (fn [spec] - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))))] + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))))] (format "CREATE TABLE %s (%s)%s" (as-sql-name entities table) (str/join ", " (map spec-to-string specs)) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index e5f94dfe..4cb8ddb9 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -346,6 +346,7 @@ [4 "Orange" "juicy" 89 88.6]])] (is (= '(1 1 1 1) r))) (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 2 (sql/query db [{:max-rows 2} "SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first}))))) @@ -765,7 +766,15 @@ (let [new-keys (sql/insert! db :fruit {:name "Apple"}) new-keys (if (postgres? db) (map :id new-keys) new-keys)] (is (= [(returned-key db 1)] new-keys)) - (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db ["SELECT * FROM fruit"])))))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] + (sql/query db "SELECT * FROM fruit"))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] + (sql/query db ["SELECT * FROM fruit"]))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] + (with-open [con (sql/get-connection db)] + (sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")])))) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] + (sql/query db [{:max-rows 1} "SELECT * FROM fruit"])))))) (deftest insert-two-by-map-and-query (doseq [db (test-specs)] From 441e32a4440f572b64e8fb93b713a62525c5e610 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 11 Apr 2016 12:08:19 -0700 Subject: [PATCH 339/630] Allow param-group to be omitted in db-do-prepared-return-keys (Just as a convenience) --- src/main/clojure/clojure/java/jdbc.clj | 10 ++++++- src/test/clojure/clojure/java/test_jdbc.clj | 31 +++++++++++++++++---- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 93527d90..05533a51 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -762,8 +762,16 @@ compatibility but it will be removed before a 1.0.0 release." } Return the generated keys for the (single) update/insert. A PreparedStatement may be passed in, instead of a SQL string, in which case :return-keys MUST BE SET on that PreparedStatement!" + ([db sql] + (db-do-prepared-return-keys db true sql [])) ([db sql param-group] - (db-do-prepared-return-keys db true sql param-group)) + (cond (or (string? sql) + (instance? PreparedStatement sql)) + (db-do-prepared-return-keys db true sql param-group) + (or (string? param-group) + (instance? PreparedStatement param-group)) + (db-do-prepared-return-keys db sql param-group []) + :else (throw (IllegalArgumentException. "db-do-prepared-return-keys expects SQL string or PreparedStatement")))) ([db transaction? sql param-group] (if-let [con (db-find-connection db)] (if (instance? PreparedStatement sql) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 4cb8ddb9..13fc80f0 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -278,6 +278,7 @@ (deftest test-do-prepared1a (doseq [db (test-specs)] (create-test-table :fruit2 db) + ;; single string is acceptable (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) @@ -286,22 +287,42 @@ (create-test-table :fruit2 db) (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")] + ;; single PreparedStatement is acceptable (is (= [1] (sql/db-do-prepared db stmt))))) (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) -(deftest test-do-prepared1c +(deftest test-do-prepared1ci (doseq [db (test-specs)] (create-test-table :fruit2 db) - (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" []))) + (is (= (returned-key db 1) + (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"))) (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) -(deftest test-do-prepared1d +(deftest test-do-prepared1cii + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (is (= (returned-key db 1) + (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" []))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) + +(deftest test-do-prepared1di + (doseq [db (test-specs)] + (create-test-table :fruit db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" + {:return-keys true})] + (is (= (returned-key db 1) + (sql/db-do-prepared-return-keys db stmt []))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + +(deftest test-do-prepared1dii (doseq [db (test-specs)] (create-test-table :fruit db) (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys true})] - (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) + (is (= (returned-key db 1) + (sql/db-do-prepared-return-keys db stmt))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-do-prepared1e @@ -312,7 +333,7 @@ (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys ["id"]})] - (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))) (deftest test-do-prepared2 From 3f0f5b4e29f9455277bea82327424c4c55e80ea2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 11 Apr 2016 12:30:05 -0700 Subject: [PATCH 340/630] Better reflect next release version --- pom.xml | 2 +- project.clj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95806b9f..2ef09485 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.5.8-SNAPSHOT ${project.artifactId} diff --git a/project.clj b/project.clj index cc1dddb7..9bb7e02e 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.6-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.5.8-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 4fda95cf27fe7d186eecbf7fb3778a80fe9a7535 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 18:54:20 -0700 Subject: [PATCH 341/630] db-do-prepared* now take [sql param param] or multi? JDBC-122 `db-do-prepared` and `db-do-prepared-return-keys` now accept both the legacy style of arguments (db sql param-group param-group ...) and the new style (db [sql param param] {} or db [sql param-group] {:multi? true}) so they are compatible in style with the rest of the library. The 0.5.0 tests all still pass (and produce lots of DEPRECATED warnings. The 0.5.8 tests all pass (and produce NO deprecated warnings). I'm committing this as a functional milestone while I refactor and clean up the implementation of a few functions. --- src/main/clojure/clojure/java/jdbc.clj | 158 ++-- src/test/clojure/clojure/java/test_jdbc.clj | 16 +- src/test/clojure/clojure/java/test_legacy.clj | 888 ++++++++++++++++++ 3 files changed, 1001 insertions(+), 61 deletions(-) create mode 100644 src/test/clojure/clojure/java/test_legacy.clj diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 05533a51..62cc3442 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -755,6 +755,13 @@ compatibility but it will be removed before a 1.0.0 release." } (exec-and-return-keys)) (exec-and-return-keys)))) +(defn- sql-stmt? + "Given an expression, return true if it is either a string (SQL) or a + PreparedStatement. Used primarily to support legacy (deprecated) API + calls." + [expr] + (or (string? expr) (instance? PreparedStatement expr))) + (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the open database connection. The param-group is a seq of values for all of @@ -762,27 +769,46 @@ compatibility but it will be removed before a 1.0.0 release." } Return the generated keys for the (single) update/insert. A PreparedStatement may be passed in, instead of a SQL string, in which case :return-keys MUST BE SET on that PreparedStatement!" - ([db sql] - (db-do-prepared-return-keys db true sql [])) - ([db sql param-group] - (cond (or (string? sql) - (instance? PreparedStatement sql)) - (db-do-prepared-return-keys db true sql param-group) - (or (string? param-group) - (instance? PreparedStatement param-group)) - (db-do-prepared-return-keys db sql param-group []) - :else (throw (IllegalArgumentException. "db-do-prepared-return-keys expects SQL string or PreparedStatement")))) - ([db transaction? sql param-group] - (if-let [con (db-find-connection db)] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-return-keys db sql param-group transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] - (db-do-execute-prepared-return-keys db stmt param-group transaction?))) - (with-open [con (get-connection db)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql param-group))))) + ([db sql-params] + (cond (sql-stmt? sql-params) + ;; transaction? and options omitted; string or stmt acceptable + (db-do-prepared-return-keys db true [sql-params] {}) + :else ; transaction? and options omitted + (db-do-prepared-return-keys db true sql-params {}))) + ([db transaction? sql-params] + (cond (sql-stmt? transaction?) + (if (map? sql-params) + ;; transaction? omitted; string or stmt acceptable + (db-do-prepared-return-keys db true [transaction?] sql-params) + ;; legacy db sql param-group call + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") + (db-do-prepared-return-keys db true (into [transaction?] sql-params) {}))) + (sequential? transaction?) + ;; transaction? omitted + (db-do-prepared-return-keys db true transaction? sql-params) + :else (throw (IllegalArgumentException. "db-do-prepared-return-keys expects db transaction? [sql & params]")))) + ([db transaction? sql-params opts] + (cond (sql-stmt? sql-params) + (if (map? opts) + ;; string or stmt acceptable; should this be deprecated? + (db-do-prepared-return-keys db transaction? [sql-params] opts) + ;; legacy db transaction? sql param + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") + (db-do-prepared-return-keys db transaction? (into [sql-params] opts) {}))) + :else ; regular db transaction? [sql params] opts call + (let [[sql & params] sql-params] + (if-let [con (db-find-connection db)] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-return-keys db sql params transaction?) + (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] + (db-do-execute-prepared-return-keys db stmt params transaction?))) + (with-open [con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))))) (defn- db-do-execute-prepared-statement - "Execute a PreparedStatment, optionally in a transaction." + "Execute a PreparedStatement, optionally in a transaction." [db ^PreparedStatement stmt param-groups transaction?] (if (empty? param-groups) (if transaction? @@ -804,30 +830,57 @@ compatibility but it will be removed before a 1.0.0 release." } the parameters. transaction? can be omitted and defaults to true. The sql parameter can either be a SQL string or a PreparedStatement. Return a seq of update counts (one count for each param-group)." - ([db sql-param-groups] - (db-do-prepared db true sql-param-groups)) - ([db transaction? sql-param-groups] - (cond (string? transaction?) - ;; legacy deprecated - (db-do-prepared db true [transaction? sql-param-groups]) - (or (string? sql-param-groups) - (instance? PreparedStatement sql-param-groups)) - ;; string or stmt is acceptable, no param groups - (db-do-prepared db transaction? [sql-param-groups]) - :else - (let [[sql & param-groups] sql-param-groups] - (if-let [con (db-find-connection db)] + ([db sql-params] + (if (sql-stmt? sql-params) + ;; transaction? and opts omitted; string or stmt acceptable + (db-do-prepared db true [sql-params] {}) + ;; transaction? and opts omitted + (db-do-prepared db true sql-params {}))) + ([db sql-params opts] + (cond (sql-stmt? sql-params) + (if (map? opts) + ;; transaction? omitted, opts present; string or stmt acceptable + (db-do-prepared db true [sql-params] opts) + ;; legacy call db sql param-group + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") + (db-do-prepared db true (into [sql-params] opts) {}))) + (sql-stmt? opts) + ;; transaction? present, opts omitted; string or stmt acceptable + (db-do-prepared db sql-params [opts] {}) + (and (coll? sql-params) (map? opts)) + ;; transaction? omitted, [sql & params] and opts present + (db-do-prepared db true sql-params opts) + (coll? opts) + ;; transaction? present, opts omitted + (db-do-prepared db sql-params opts {}) + :else (throw (IllegalArgumentException. "db-do-prepared expects db transaction? [sql & params] opts")))) + ([db transaction? sql-params opts] + (cond (map? opts) + ;; string or stmt is acceptable, with param groups + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) [sql-params] sql-params) + params (if (or (:multi? opts) (empty? params)) params [params])] (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql param-groups transaction?) + (db-do-execute-prepared-statement db sql params transaction?) (with-open [^PreparedStatement stmt (prepare-statement con sql)] - (db-do-execute-prepared-statement db stmt param-groups transaction?))) - (with-open [con (get-connection db)] - (db-do-prepared (add-connection db con) transaction? sql-param-groups)))))) + (db-do-execute-prepared-statement db stmt params transaction?)))) + (with-open [con (get-connection db)] + (db-do-prepared (add-connection db con) transaction? sql-params opts))) + (sql-stmt? transaction?) + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") + (db-do-prepared db true [transaction? sql-params opts] {:multi? true})) + :else + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") + (db-do-prepared db transaction? [sql-params opts] {:multi? true})))) ([db t-or-sql-p-g sql-pg-1 pg-2 & pgs] ;; legacy deprecated - (if (string? t-or-sql-p-g) - (db-do-prepared db true (concat [t-or-sql-p-g sql-pg-1 pg-2] pgs)) - (db-do-prepared db t-or-sql-p-g (concat [sql-pg-1 pg-2] pgs))))) + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") + (if (sql-stmt? t-or-sql-p-g) + (db-do-prepared db true (concat [t-or-sql-p-g sql-pg-1 pg-2] pgs) {:multi? true}) + (db-do-prepared db t-or-sql-p-g (concat [sql-pg-1 pg-2] pgs) {:multi? true})))) (defn db-query-with-resultset "Executes a query, then evaluates func passing in the raw ResultSet as an @@ -924,16 +977,11 @@ compatibility but it will be removed before a 1.0.0 release." } ([db sql-params] (execute! db sql-params {})) ([db sql-params {:keys [transaction? multi?] :or {transaction? true multi? false}}] - (let [param-groups (rest sql-params) - execute-helper + (let [execute-helper (^{:once true} fn* [db] (if multi? - ;; already in the correct form: [sql [params] [params]] - (db-do-prepared db transaction? sql-params) - (if (seq param-groups) - ;; single param group: convert to correct form - (db-do-prepared db transaction? [(first sql-params) param-groups]) - (db-do-prepared db transaction? sql-params))))] + (db-do-prepared db transaction? sql-params {:multi? true}) + (db-do-prepared db transaction? sql-params {})))] (if-let [con (db-find-connection db)] (execute-helper db) (with-open [con (get-connection db)] @@ -984,9 +1032,7 @@ compatibility but it will be removed before a 1.0.0 release." } inserts), run a prepared statement on each and return any generated keys. Note: we are eager so an unrealized lazy-seq cannot escape from the connection." [db stmts] - (doall (map (fn [row] - (db-do-prepared-return-keys db false (first row) (rest row))) - stmts))) + (doall (map (fn [row] (db-do-prepared-return-keys db false row {})) stmts))) (defn- insert-helper "Given a (connected) database connection, a transaction flag and some SQL statements @@ -1013,7 +1059,7 @@ compatibility but it will be removed before a 1.0.0 release." } (let [nc (count columns) vcs (map count values)] (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) - (throw (IllegalArgumentException. "insert called with inconsistent number of columns / values")) + (throw (IllegalArgumentException. "insert! called with inconsistent number of columns / values")) (into [(str "INSERT INTO " (table-str table entities) (when (seq columns) (str " ( " @@ -1084,7 +1130,7 @@ compatibility but it will be removed before a 1.0.0 release." } (let [entities (:entities opts identity) sql-params (map (fn [row] (when-not (map? row) - (throw (IllegalArgumentException. "insert-row! called with a non-map row"))) + (throw (IllegalArgumentException. "insert! / insert-milti! called with a non-map row"))) (insert-single-row-sql table row entities)) rows)] (if-let [con (db-find-connection db)] (insert-helper db (:transaction? opts) sql-params) @@ -1098,9 +1144,9 @@ compatibility but it will be removed before a 1.0.0 release." } [db table cols values opts] (let [sql-params (insert-multi-row-sql table cols values (:entities opts identity))] (if-let [con (db-find-connection db)] - (db-do-prepared db (:transaction? opts) sql-params) + (db-do-prepared db (:transaction? opts) sql-params {:multi? true}) (with-open [con (get-connection db)] - (db-do-prepared (add-connection db con) (:transaction? opts) sql-params))))) + (db-do-prepared (add-connection db con) (:transaction? opts) sql-params {:multi? true}))))) (defn- is-options-map? "Given a map, return true if it seems to be an options map." @@ -1167,9 +1213,9 @@ compatibility but it will be removed before a 1.0.0 release." } (let [stmts (insert-multi-row-sql table names values entities)] (if-let [con (db-find-connection db)] - (db-do-prepared db transaction? stmts) + (db-do-prepared db transaction? stmts {:multi? true}) (with-open [con (get-connection db)] - (db-do-prepared (add-connection db con) transaction? stmts)))))))) + (db-do-prepared (add-connection db con) transaction? stmts {:multi? true})))))))) (defn insert-multi! "Given a database connection, a table name and either a sequence of maps (for diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 13fc80f0..e2e364bf 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -302,7 +302,7 @@ (doseq [db (test-specs)] (create-test-table :fruit2 db) (is (= (returned-key db 1) - (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" []))) + (sql/db-do-prepared-return-keys db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"]))) (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1di @@ -312,7 +312,7 @@ (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys true})] (is (= (returned-key db 1) - (sql/db-do-prepared-return-keys db stmt []))))) + (sql/db-do-prepared-return-keys db [stmt]))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-do-prepared1dii @@ -343,16 +343,22 @@ (is (thrown? java.sql.SQLException (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) -(deftest test-do-prepared3 +(deftest test-do-prepared3a (doseq [db (test-specs)] (create-test-table :fruit2 db) - (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) + (sql/db-do-prepared db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]] {:multi? true}) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) + +(deftest test-do-prepared3b + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-prepared db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" "test" "test" 1 1.0]) (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared4 (doseq [db (test-specs)] (create-test-table :fruit2 db) - (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) + (sql/db-do-prepared db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]] {:multi? true}) (is (= 2 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-insert-rows diff --git a/src/test/clojure/clojure/java/test_legacy.clj b/src/test/clojure/clojure/java/test_legacy.clj new file mode 100644 index 00000000..acbbb601 --- /dev/null +++ b/src/test/clojure/clojure/java/test_legacy.clj @@ -0,0 +1,888 @@ +;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and +;; distribution terms for this software are covered by the Eclipse Public +;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +;; be found in the file epl-v10.html at the root of this distribution. By +;; using this software in any fashion, you are agreeing to be bound by the +;; terms of this license. You must not remove this notice, or any other, +;; from this software. +;; +;; test_legacy.clj +;; +;; This namespace contains tests that exercise the JDBC portion of java.jdbc +;; 0.5.0 as a sanity check to make sure I don't break existing functionality +;; while I deprecate and reorganize various functions. +;; +;; scgilardi (gmail) +;; Created 13 September 2008 +;; +;; seancorfield (gmail) +;; Migrated from clojure.contrib.test-sql 17 April 2011 + +(ns clojure.java.test-legacy + (:use clojure.test) + (:require [clojure.java.jdbc :as sql])) + +;; Set test-databases according to whether you have the local database available: +;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] +;; Apache Derby and HSQLDB can run without an external setup. +(def test-databases + (if-let [dbs (System/getenv "TEST_DBS")] + (map keyword (.split dbs ",")) + ;; enable more by default once the build server is equipped? + [:derby :hsqldb :h2 :sqlite])) + +;; MS SQL Server requires more specialized configuration: +(def mssql-host + (if-let [host (System/getenv "TEST_MSSQL_HOST")] host "127.0.0.1\\SQLEXPRESS")) +(def mssql-port + (if-let [port (System/getenv "TEST_MSSQL_PORT")] port "1433")) +(def mssql-user + (if-let [user (System/getenv "TEST_MSSQL_USER")] user "sa")) +(def mssql-pass + (if-let [pass (System/getenv "TEST_MSSQL_PASS")] pass "")) +(def mssql-dbname + (if-let [name (System/getenv "TEST_MSSQL_NAME")] name "clojure_test")) +(def jtds-host + (if-let [host (System/getenv "TEST_JTDS_HOST")] host mssql-host)) +(def jtds-port + (if-let [port (System/getenv "TEST_JTDS_PORT")] port mssql-port)) +(def jtds-user + (if-let [user (System/getenv "TEST_JTDS_USER")] user mssql-user)) +(def jtds-pass + (if-let [pass (System/getenv "TEST_JTDS_PASS")] pass mssql-pass)) +(def jtds-dbname + (if-let [name (System/getenv "TEST_JTDS_NAME")] name mssql-dbname)) + +;; database connections used for testing: + +(def mysql-db {:subprotocol "mysql" + :subname "//127.0.0.1:3306/clojure_test" + :user "clojure_test" + :password "clojure_test"}) + +(def derby-db {:dbtype "derby" + :dbname "clojure_test_derby" + :create true}) + +(def hsqldb-db {:dbtype "hsqldb" + :dbname "clojure_test_hsqldb"}) + +(def h2-db {:dbtype "h2" + :dbname "./clojure_test_h2"}) + +(def sqlite-db {:dbtype "sqlite" + :dbname "clojure_test_sqlite"}) + +(def postgres-db {:subprotocol "postgresql" + :subname "clojure_test" + :user "clojure_test" + :password "clojure_test"}) + +(def mssql-db {:subprotocol "sqlserver" + :subname (str "//" mssql-host ":" mssql-port ";DATABASENAME=" mssql-dbname) + :user mssql-user + :password mssql-pass}) + +(def jtds-db {:subprotocol "jtds:sqlserver" + :subname (str "//" jtds-host ":" jtds-port "/" jtds-dbname) + :user jtds-user + :password jtds-pass}) + +;; To test against the stringified DB connection settings: +(def mysql-str-db + "mysql://clojure_test:clojure_test@localhost:3306/clojure_test") + +(def mysql-jdbc-str-db + "jdbc:mysql://clojure_test:clojure_test@localhost:3306/clojure_test") + +(def postgres-str-db + "postgres://clojure_test:clojure_test@localhost/clojure_test") + +(defn- test-specs + "Return a sequence of db-spec maps that should be used for tests" + [] + (for [db test-databases] + @(ns-resolve 'clojure.java.test-legacy (symbol (str (name db) "-db"))))) + +(defn- clean-up + "Attempt to drop any test tables before we start a test." + [t] + (doseq [db (test-specs)] + (sql/with-db-transaction [t-conn db] + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/db-do-commands t-conn (sql/drop-table-ddl table)) + (catch Exception _ + ;; ignore + ))))) + (t)) + +(use-fixtures + :each clean-up) + +;; We start with all tables dropped and each test has to create the tables +;; necessary for it to do its job, and populate it as needed... + +(defn- mysql? [db] + (if (string? db) + (re-find #"mysql:" db) + (= "mysql" (or (:subprotocol db) (:dbtype db))))) + +(defn- postgres? [db] + (if (string? db) + (re-find #"postgres" db) + (= "postgresql" (or (:subprotocol db) (:dbtype db))))) + +(defmulti create-test-table + "Create a standard test table. Uses db-do-commands. + For MySQL, ensure table uses an engine that supports transactions!" + (fn [table db] + (cond + (mysql? db) :mysql + (postgres? db) :postgres + :else :default))) + +(defmethod create-test-table :mysql + [table db] + (sql/db-do-commands + db (sql/create-table-ddl + table + [:id :int "PRIMARY KEY AUTO_INCREMENT"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec "ENGINE=InnoDB"))) + +(defmethod create-test-table :postgres + [table db] + (sql/db-do-commands + db (sql/create-table-ddl + table + [:id :serial "PRIMARY KEY"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec ""))) + +(defmethod create-test-table :default + [table db] + (sql/db-do-commands + db (sql/create-table-ddl + table + [:id :int "DEFAULT 0"] + [:name "VARCHAR(32)" "PRIMARY KEY"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real] + :table-spec ""))) + +(deftest test-uri-spec-parsing + (is (= {:advanced "false" :ssl "required" :password "clojure_test" + :user "clojure_test" :subname "//localhost/clojure_test" + :subprotocol "postgresql"} + (@#'sql/parse-properties-uri + (java.net.URI. + (str "postgres://clojure_test:clojure_test@localhost/clojure_test?" + "ssl=required&advanced=false"))))) + (is (= {:password "clojure_test" :user "clojure_test" + :subname "//localhost:3306/clojure_test", :subprotocol "mysql"} + (@#'sql/parse-properties-uri + (java.net.URI. + "mysql://clojure_test:clojure_test@localhost:3306/clojure_test"))))) + +(defn- returned-key [db k] + (condp = (or (:subprotocol db) (:dbtype db)) + "derby" {(keyword "1") nil} + "hsqldb" nil + "h2" nil + "mysql" {:generated_key k} + nil (if (mysql? db) ; string-based tests + {:generated_key k} + k) + "jtds:sqlserver" {:id nil} + "sqlserver" {:generated_keys nil} + "sqlite" {(keyword "last_insert_rowid()") k} + k)) + +(defn- generated-key [db k] + (condp = (or (:subprotocol db) (:dbtype db)) + "derby" 0 + "hsqldb" 0 + "h2" 0 + "jtds:sqlserver" 0 + "sqlserver" 0 + "sqlite" 0 + k)) + +(defn- float-or-double [db v] + (condp = (or (:subprotocol db) (:dbtype db)) + "derby" (Float. v) + "h2" (Float. v) + "jtds:sqlserver" (Float. v) + "sqlserver" (Float. v) + "postgresql" (Float. v) + v)) + +(deftest test-create-table + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-drop-table + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-commands db (sql/drop-table-ddl :fruit2)) + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-commands + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-commands db "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared1a + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )") + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared1b + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")] + (is (= [1] (sql/db-do-prepared db stmt))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared1c + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" []))) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared1d + (doseq [db (test-specs)] + (create-test-table :fruit db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" + :return-keys true)] + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-do-prepared1e + (doseq [db (test-specs)] + ;; Derby/SQL Server does not have auto-generated id column which we're testing here + (when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (create-test-table :fruit db) + (with-open [con (sql/get-connection db)] + (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" + :return-keys ["id"])] + (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt []))))) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))))) + +(deftest test-do-prepared2 + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-prepared db "DROP TABLE fruit2") + (is (thrown? java.sql.SQLException + (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared3 + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]) + (is (= 1 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-do-prepared4 + (doseq [db (test-specs)] + (create-test-table :fruit2 db) + (sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]) + (is (= 2 (sql/query db ["SELECT * FROM fruit2"] :result-set-fn count))))) + +(deftest test-insert-rows + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + nil + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])] + (is (= '(1 1 1 1) r))) + (is (= 4 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] :result-set-fn (comp :name first)))) + (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] :result-set-fn (comp :appearance first)))))) + +(deftest test-insert-values + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + [:name :cost] + ["Mango" 722] + ["Feijoa" 441])] + (is (= '(1 1) r))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Mango" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 722] :result-set-fn (comp :name first)))))) + +(deftest test-insert-records + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + {:name "Kiwifruit" :grade 93})] + (is (= (list (returned-key db 1) (returned-key db 2)) r))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] :result-set-fn (comp :name first)))))) + +(deftest test-insert-via-execute + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )") + "Apple" "Green" 75]) + (sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( 'Pear', 'Yellow', 99 )")]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + :result-set-fn (comp :name first)))))) + +(deftest execute-with-prepared-statement + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-connection [conn db] + (let [connection (:connection conn) + prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )"))] + + (sql/execute! db [prepared-statement "Apple" "Green" 75]) + (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + :result-set-fn (comp :name first)))))) + +(deftest execute-with-prepared-statement-return-keys + (doseq [db (test-specs)] + ;; Derby/SQL Server does not have auto-generated id column which we're testing here + (when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (create-test-table :fruit db) + (sql/with-db-connection [conn db] + (let [connection (:connection conn) + prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )") + :return-keys ["id"])] + ;; what is returned is affected row counts due to how execute! works + (is (= [1] (sql/execute! db [prepared-statement "Apple" "Green" 75]))) + (is (= [1] (sql/execute! db [prepared-statement "Pear" "Yellow" 99]))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + :result-set-fn (comp :name first))))))) + +(deftest test-update-values + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [r (sql/insert! + db + :fruit + nil + [1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6])] + (is (= '(1 1 1 1) r))) + (sql/update! db + :fruit + {:appearance "bruised" :cost 14} + ["name=?" "Banana"]) + (is (= 4 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] :result-set-fn (comp :name first)))) + (is (= "Banana" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "bruised"] :result-set-fn (comp :name first)))) + (is (= 14 (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Banana"] :result-set-fn (comp :cost first)))))) + +(defn update-or-insert-values + [db table row where] + (sql/with-db-transaction [t-conn db] + (let [result (sql/update! t-conn table row where)] + (if (zero? (first result)) + (sql/insert! t-conn table row) + result)))) + +(defn update-or-insert-values-with-isolation + [db table row where] + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (let [result (sql/update! t-conn table row where)] + (if (zero? (first result)) + (sql/insert! t-conn table row) + result)))) + +(deftest test-update-or-insert-values + (doseq [db (test-specs)] + (create-test-table :fruit db) + (update-or-insert-values db + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Pomegranate" :appearance "ripe" :cost 565} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Apple" :appearance "green" :cost 74} + ["name=?" "Apple"]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-update-or-insert-values-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (update-or-insert-values-with-isolation db + :fruit + {:name "Pomegranate" :appearance "fresh" :cost 585} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Pomegranate" :appearance "ripe" :cost 565} + ["name=?" "Pomegranate"]) + (is (= 1 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))) + (is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"] :result-set-fn (comp :cost first)))) + (update-or-insert-values db + :fruit + {:name "Apple" :appearance "green" :cost 74} + ["name=?" "Apple"]) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(defn- file-not-found-exception-via-reflection + "In Clojure 1.3.0 this caused a wrapped exception and we introduced throw-non-rte + to workaround that. This was fixed in 1.4.0 but we never removed the workaround. + Added this hack from the mailing list specifically to test the exception handling + so that we can verify only Clojure 1.3.0 fails the tests and drop support for it." + [f] + (java.io.FileReader. f)) + +(deftest test-partial-exception + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (file-not-found-exception-via-reflection "/etc/password_no_such_file")) + (catch java.io.FileNotFoundException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count)))) + (catch Exception _ + (is false "Unexpected exception encountered (not wrapped?)."))))) + +(deftest test-partial-exception-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db :isolation :serializable] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"]) + (is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count))) + (throw (Exception. "deliberate exception"))) + (catch Exception _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))))) + +(deftest test-sql-exception + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Apple" "strange" "whoops"])) + (catch IllegalArgumentException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-sql-exception-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Apple" "strange" "whoops"])) + (catch IllegalArgumentException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-insert-values-exception + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (thrown? IllegalArgumentException + (sql/with-db-transaction [t-conn db] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"])))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-insert-values-exception-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (thrown? IllegalArgumentException + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"])))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-rollback + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db] + (is (not (sql/db-is-rollback-only t-conn))) + (sql/db-set-rollback-only! t-conn) + (is (sql/db-is-rollback-only t-conn)) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (catch java.sql.SQLException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-rollback-with-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (try + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (is (not (sql/db-is-rollback-only t-conn))) + (sql/db-set-rollback-only! t-conn) + (is (sql/db-is-rollback-only t-conn)) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange"]) + (is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (catch java.sql.SQLException _ + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-transactions-with-possible-generated-keys-result-set + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-transaction [t-conn db] + (sql/db-set-rollback-only! t-conn) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-transactions-with-possible-generated-keys-result-set-and-isolation + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (sql/db-set-rollback-only! t-conn) + (sql/insert! t-conn + :fruit + [:name :appearance] + ["Grape" "yummy"]) + (is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] :result-set-fn count)))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-nested-transactions-check-transaction-isolation-level + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-transaction [t-conn db :isolation :read-uncommitted] + (is (thrown? IllegalStateException + (sql/with-db-transaction [t-conn' t-conn :isolation :serializable] + (sql/insert! t-conn' + :fruit + [:name :appearance] + ["Grape" "yummy"]))))) + (is (= 0 (sql/query db ["SELECT * FROM fruit"] :result-set-fn count))))) + +(deftest test-raw-metadata + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [table-info (with-open [conn (sql/get-connection db)] + (into [] + (sql/result-set-seq + (-> conn + (.getMetaData) + (.getTables nil nil nil + (into-array ["TABLE" "VIEW"]))))))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case)))))) + +(deftest test-metadata-managed + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-metadata [metadata db] + (let [table-info (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case))))))) + +(deftest test-metadata-managed-computed + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= "fruit" + (sql/with-db-metadata [metadata db] + (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])) + :row-fn (comp clojure.string/lower-case :table_name) + :result-set-fn first)))))) + +(deftest test-metadata + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-metadata [metadata db] + ;; make sure to close the ResultSet + (with-open [table-info-result (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"]))] + (let [table-info (sql/metadata-result table-info-result)] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case)))))))) + +(deftest empty-query + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= [] (sql/query db ["SELECT * FROM fruit"]))))) + +(deftest query-with-string + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= [] (sql/query db "SELECT * FROM fruit"))))) + +(deftest insert-one-row + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [(returned-key db 1)] new-keys))))) + +(deftest insert-query + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (is (= [(returned-key db 1)] new-keys)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db ["SELECT * FROM fruit"])))))) + +(deftest insert-two-by-map-and-query + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] + (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) + +(deftest insert-two-by-map-and-query-as-arrays + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:name "Pear"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] + :as-arrays? :cols-as-is)] + (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) + (is (= [[:id :name :appearance :cost :grade] + [(generated-key db 1) "Apple" nil nil nil] + [(generated-key db 2) "Pear" nil nil nil]] rows))))) + +(deftest insert-two-by-cols-and-query + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [update-counts (sql/insert! db :fruit [:name] ["Apple"] ["Pear"]) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] + (is (= [1 1] update-counts)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} + {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) + +(deftest insert-update-and-query + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) + update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} + ["id = ?" (generated-key db 1)]) + rows (sql/query db ["SELECT * FROM fruit"])] + (is (= [(returned-key db 1)] new-keys)) + (is (= [1] update-result)) + (is (= [{:id (generated-key db 1) + :name "Apple" :appearance "Green" + :grade (float-or-double db 1.2) + :cost 12}] rows))))) + +(deftest insert-delete-and-query + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"}) + new-keys (if (postgres? db) (map :id new-keys) new-keys) + delete-result (sql/delete! db :fruit + ["id = ?" (generated-key db 1)]) + rows (sql/query db ["SELECT * FROM fruit"])] + (is (= [(returned-key db 1)] new-keys)) + (is (= [1] delete-result)) + (is (= [] rows))))) + +(deftest insert-delete-and-query-in-connection + (doseq [db (test-specs)] + (sql/with-db-connection [con-db db] + (create-test-table :fruit con-db) + (let [new-keys (sql/insert! con-db :fruit {:name "Apple"}) + new-keys (if (postgres? con-db) (map :id new-keys) new-keys) + delete-result (sql/delete! con-db :fruit + ["id = ?" (generated-key con-db 1)]) + rows (sql/query con-db ["SELECT * FROM fruit"])] + (is (= [(returned-key con-db 1)] new-keys)) + (is (= [1] delete-result)) + (is (= [] rows)))))) + +(deftest illegal-insert-arguments + (doseq [db (test-specs)] + (is (thrown? IllegalArgumentException (sql/insert! db))) + (is (thrown? IllegalArgumentException (sql/insert! db :entities identity))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) + (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] :entities identity))) + (is (thrown? IllegalArgumentException (sql/insert! db [:name]))))) + +(deftest test-execute!-fails-with-multi-param-groups + (doseq [db (test-specs)] + (create-test-table :fruit db) + ;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException + (is (thrown? Exception + (sql/execute! + db + ["INSERT INTO fruit (name,appearance) VALUES (?,?)" + ["Apple" "rosy"] + ["Pear" "yellow"] + ["Orange" "round"]]))))) + +(deftest test-execute!-with-multi?-true-param-groups + (doseq [db (test-specs)] + (create-test-table :fruit db) + ;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException + (let [counts (sql/execute! + db + ["INSERT INTO fruit (name,appearance) VALUES (?,?)" + ["Apple" "rosy"] + ["Pear" "yellow"] + ["Orange" "round"]] + :multi? true) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] + (is (= [1 1 1] counts)) + (is (= [{:id (generated-key db 1) :name "Apple" :appearance "rosy" :cost nil :grade nil} + {:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil} + {:id (generated-key db 2) :name "Pear" :appearance "yellow" :cost nil :grade nil}] rows))))) + +(deftest test-resultset-read-column + (extend-protocol sql/IResultSetReadColumn + String + (result-set-read-column [s _ _] ::FOO)) + + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost :grade] + ["Crepes" 12 87.7] + ["Vegetables" -88 nil] + ["Teenage Mutant Ninja Turtles" 0 100.0]) + (is (= {:name ::FOO, :cost -88, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?" + "Vegetables"] + :result-set-fn first)))) + + ;; somewhat "undo" the first extension + (extend-protocol sql/IResultSetReadColumn + String + (result-set-read-column [s _ _] s))) + +(deftest test-sql-value + (extend-protocol sql/ISQLValue + clojure.lang.Keyword + (sql-value [_] "KW")) + + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost :grade] + [:test 12 nil]) + (is (= {:name "KW", :cost 12, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit"] + :result-set-fn first)))) + + ;; somewhat "undo" the first extension + (extend-protocol sql/ISQLValue + clojure.lang.Keyword + (sql-value [k] k))) + +(deftest test-sql-parameter + (extend-protocol sql/ISQLParameter + clojure.lang.Keyword + (set-parameter [v ^java.sql.PreparedStatement s ^long i] + (if (= :twelve v) + (.setLong s i 12) + (.setString s i (str (name v) i))))) + + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/insert! db + :fruit + [:name :cost :grade] + [:test :twelve nil]) + (is (= {:name "test1", :cost 12, :grade nil} + (sql/query db ["SELECT name, cost, grade FROM fruit"] + :result-set-fn first)))) + + ;; somewhat "undo" the first extension + (extend-protocol sql/ISQLParameter + clojure.lang.Keyword + (set-parameter [v ^java.sql.PreparedStatement s ^long i] + (.setObject s i (sql/sql-value v))))) From 86189b3ff039e5b40120415d0a8903993a3c3132 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 19:46:03 -0700 Subject: [PATCH 342/630] Refactor query/db-query-with-resultset; add tests JDBC-122 --- src/main/clojure/clojure/java/jdbc.clj | 22 ++++++++++----------- src/test/clojure/clojure/java/test_jdbc.clj | 4 ++++ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 62cc3442..8f27f543 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -905,22 +905,20 @@ compatibility but it will be removed before a 1.0.0 release." } (.getName sql-params-class) (pr-str sql-params))] (throw (IllegalArgumentException. msg)))) - (let [special (first sql-params) - sql-is-first (string? special) - options-are-first (map? special) - sql (cond sql-is-first special - options-are-first (second sql-params)) - params (vec (cond sql-is-first (rest sql-params) - options-are-first (rest (rest sql-params)) - :else (rest sql-params))) - prepare-args (when (map? special) special) + (let [[prepare-args sql & params] (if (map? (first sql-params)) + sql-params + (cons nil sql-params)) run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] ((or (:set-parameters db) set-parameters) stmt params) (with-open [rset (.executeQuery stmt)] (func rset)))] - (if (instance? PreparedStatement special) - (let [^PreparedStatement stmt special] + (if (instance? PreparedStatement sql) + + (let [^PreparedStatement stmt sql] + (when prepare-args + (throw (IllegalArgumentException. "query/db-query-with-resultset: options ignored when PreparedStatement provided"))) (run-query-with-params stmt)) + (if-let [con (db-find-connection db)] (with-open [^PreparedStatement stmt (prepare-statement con sql prepare-args)] (run-query-with-params stmt)) @@ -948,7 +946,7 @@ compatibility but it will be removed before a 1.0.0 release." } :or {row-fn identity identifiers str/lower-case}}] (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) - sql-params-vector (if (string? sql-params) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (db-query-with-resultset db sql-params-vector diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index e2e364bf..60364a06 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -373,7 +373,11 @@ [4 "Orange" "juicy" 89 88.6]])] (is (= '(1 1 1 1) r))) (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 4 (sql/with-db-connection [con db] + (sql/query con (sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit") {:result-set-fn count})))) (is (= 2 (sql/query db [{:max-rows 2} "SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 2 (sql/with-db-connection [con db] + (sql/query con [(sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit" {:max-rows 2})] {:result-set-fn count})))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first}))))) From 96ba89957b8a91cb1f271933f961682df3d9757c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 20:07:33 -0700 Subject: [PATCH 343/630] Refactor db-do-prepared* JDBC-122 --- src/main/clojure/clojure/java/jdbc.clj | 85 ++++++++++---------------- 1 file changed, 31 insertions(+), 54 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8f27f543..2ba6de72 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -770,42 +770,32 @@ compatibility but it will be removed before a 1.0.0 release." } A PreparedStatement may be passed in, instead of a SQL string, in which case :return-keys MUST BE SET on that PreparedStatement!" ([db sql-params] - (cond (sql-stmt? sql-params) - ;; transaction? and options omitted; string or stmt acceptable - (db-do-prepared-return-keys db true [sql-params] {}) - :else ; transaction? and options omitted - (db-do-prepared-return-keys db true sql-params {}))) + (db-do-prepared-return-keys db true sql-params {})) ([db transaction? sql-params] - (cond (sql-stmt? transaction?) - (if (map? sql-params) - ;; transaction? omitted; string or stmt acceptable - (db-do-prepared-return-keys db true [transaction?] sql-params) - ;; legacy db sql param-group call - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") - (db-do-prepared-return-keys db true (into [transaction?] sql-params) {}))) - (sequential? transaction?) + (cond (map? sql-params) ;; transaction? omitted (db-do-prepared-return-keys db true transaction? sql-params) - :else (throw (IllegalArgumentException. "db-do-prepared-return-keys expects db transaction? [sql & params]")))) + (sql-stmt? transaction?) + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") + (db-do-prepared-return-keys db true (into [transaction?] sql-params) {})) + :else + ;; opts? omitted + (db-do-prepared-return-keys db transaction? sql-params {}))) ([db transaction? sql-params opts] - (cond (sql-stmt? sql-params) - (if (map? opts) - ;; string or stmt acceptable; should this be deprecated? - (db-do-prepared-return-keys db transaction? [sql-params] opts) - ;; legacy db transaction? sql param - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") - (db-do-prepared-return-keys db transaction? (into [sql-params] opts) {}))) - :else ; regular db transaction? [sql params] opts call - (let [[sql & params] sql-params] - (if-let [con (db-find-connection db)] + (cond (map? opts) + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) [sql-params] sql-params)] (if (instance? PreparedStatement sql) (db-do-execute-prepared-return-keys db sql params transaction?) (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] - (db-do-execute-prepared-return-keys db stmt params transaction?))) - (with-open [con (get-connection db)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))))) + (db-do-execute-prepared-return-keys db stmt params transaction?)))) + (with-open [con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))) + :else + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") + (db-do-prepared-return-keys db transaction? (into [sql-params] opts) {}))))) (defn- db-do-execute-prepared-statement "Execute a PreparedStatement, optionally in a transaction." @@ -831,33 +821,20 @@ compatibility but it will be removed before a 1.0.0 release." } The sql parameter can either be a SQL string or a PreparedStatement. Return a seq of update counts (one count for each param-group)." ([db sql-params] - (if (sql-stmt? sql-params) - ;; transaction? and opts omitted; string or stmt acceptable - (db-do-prepared db true [sql-params] {}) - ;; transaction? and opts omitted - (db-do-prepared db true sql-params {}))) - ([db sql-params opts] - (cond (sql-stmt? sql-params) - (if (map? opts) - ;; transaction? omitted, opts present; string or stmt acceptable - (db-do-prepared db true [sql-params] opts) - ;; legacy call db sql param-group - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") - (db-do-prepared db true (into [sql-params] opts) {}))) - (sql-stmt? opts) - ;; transaction? present, opts omitted; string or stmt acceptable - (db-do-prepared db sql-params [opts] {}) - (and (coll? sql-params) (map? opts)) - ;; transaction? omitted, [sql & params] and opts present - (db-do-prepared db true sql-params opts) - (coll? opts) - ;; transaction? present, opts omitted - (db-do-prepared db sql-params opts {}) - :else (throw (IllegalArgumentException. "db-do-prepared expects db transaction? [sql & params] opts")))) + (db-do-prepared db true sql-params {})) + ([db transaction? sql-params] + (cond (map? sql-params) + ;; transaction? omitted + (db-do-prepared db true transaction? sql-params) + (sql-stmt? transaction?) + (do + (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") + (db-do-prepared db true (into [transaction?] sql-params) {})) + :else + ;; opts omitted + (db-do-prepared db transaction? sql-params {}))) ([db transaction? sql-params opts] (cond (map? opts) - ;; string or stmt is acceptable, with param groups (if-let [con (db-find-connection db)] (let [[sql & params] (if (sql-stmt? sql-params) [sql-params] sql-params) params (if (or (:multi? opts) (empty? params)) params [params])] From 5f00c4b4f41fb772853827431a00f779d6637de8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 21:23:17 -0700 Subject: [PATCH 344/630] Prep for 0.5.8 --- CHANGES.md | 4 ++-- README.md | 4 ++++ project.clj | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d7ee255b..7e869bc4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,7 @@ -Changes coming in 0.5.8 +Changes 0.5.8 * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. -* `db-do-prepared` now expects to receive a `db-spec`, an optional `transaction?` boolean, and a final argument that is either a `PreparedStatement`, a SQL string, or a vector containing a SQL string followed by parameter groups -- vectors of parameters values, like the `:multi? true` version of `execute!` [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with multiple arguments -- the SQL string / statement and the parameter groups unrolled is deprecated and will produce "DEPRECATED" warnings printed to the console. +* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. Changes in 0.5.7 diff --git a/README.md b/README.md index 10a47d99..4d486ff8 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,10 @@ Developer Information Change Log ==================== +* Release 0.5.8 on 2016-04-12 + * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. + * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. + * Release 0.5.7 on 2016-04-10 * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). diff --git a/project.clj b/project.clj index 9bb7e02e..dfd648bb 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.8-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.5.8" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 4ceff592df624329577976530ccd54a450e48efa Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 12 Apr 2016 23:25:47 -0500 Subject: [PATCH 345/630] [maven-release-plugin] prepare release java.jdbc-0.5.8 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2ef09485..75122000 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.8-SNAPSHOT + 0.5.8 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.5.8 From 40abf6811d9c2c09b5711aa7ed869e3f79906866 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 12 Apr 2016 23:25:47 -0500 Subject: [PATCH 346/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 75122000..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.5.8 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.5.8 + HEAD From a564adaf9a4864996747a9b3f78d95bb36c57aec Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 21:29:01 -0700 Subject: [PATCH 347/630] Reflect release of 0.5.8 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4d486ff8..aa3c0264 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.5.7 +Latest stable release: 0.5.8 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.5.7 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.5.7"] +[org.clojure/java.jdbc "0.5.8"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.5.7 + 0.5.8 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: From 43f76d385ac362bb5b97f974dc0b6c020e89c8ee Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 21:29:53 -0700 Subject: [PATCH 348/630] Update project.clj for 0.6.0-SNAPSHOT --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index dfd648bb..ab006a94 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.5.8" +(defproject org.clojure/java.jdbc "0.6.0-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 202850095f83d2eb1578da6d087c6fd73d89c928 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 12 Apr 2016 21:35:56 -0700 Subject: [PATCH 349/630] Reflect updated versions for migration --- CHANGES.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 71c2b813..4732028b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,8 +1,8 @@ Changes coming in 0.6.0 * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). - - See changes described in versions 0.5.5 and 0.5.6 for what was deprecated - - Use version 0.5.7 as a bridge to identify any deprecated API calls on which your code relies! + - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated + - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed - The `java.jdbc.deprecated` namespace has been removed From 16259b7d26abf7ad3cb0467d1e225027471e2674 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 13 Apr 2016 09:42:49 -0700 Subject: [PATCH 350/630] Prep for 0.6.0-alpha1 --- CHANGES.md | 2 +- README.md | 13 ++++++++++--- project.clj | 2 +- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 4732028b..039c74a8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.6.0 +Changes in 0.6.0 * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated diff --git a/README.md b/README.md index aa3c0264..30bdf82b 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.5.8 +Latest stable release: 0.6.0-alpha1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.5.8 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.5.8"] +[org.clojure/java.jdbc "0.6.0-alpha1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.5.8 + 0.6.0-alpha1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,13 @@ Developer Information Change Log ==================== +* Release 0.6.0-alpha1 on 2016-04-13 -- BREAKING RELEASE! + * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). + - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated + - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! + - `db-transaction` (deprecated in version 0.3.0) has been removed + - The `java.jdbc.deprecated` namespace has been removed + * Release 0.5.8 on 2016-04-12 * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. diff --git a/project.clj b/project.clj index ab006a94..b1ba559f 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.6.0-alpha1" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 1902a01a8154a598e9f3bdafcf4c2c2830957f19 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 13 Apr 2016 11:50:12 -0500 Subject: [PATCH 351/630] [maven-release-plugin] prepare release java.jdbc-0.6.0-alpha1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95806b9f..57be21b0 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.6.0-alpha1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.0-alpha1 From cae71ba9c145f205564c589b538607fc55cc20ae Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 13 Apr 2016 11:50:12 -0500 Subject: [PATCH 352/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 57be21b0..7a8d1434 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-alpha1 + 0.6.1-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.0-alpha1 + HEAD From 340033ac6af99859b4b73a428eb55e18454809a9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 16 Apr 2016 16:33:44 -0700 Subject: [PATCH 353/630] JDBC-123 fix typo in exception --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b1e86bb0..c9e350d5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1039,7 +1039,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (let [entities (:entities opts identity) sql-params (map (fn [row] (when-not (map? row) - (throw (IllegalArgumentException. "insert! / insert-milti! called with a non-map row"))) + (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) (insert-single-row-sql table row entities)) rows)] (if-let [con (db-find-connection db)] (insert-helper db (:transaction? opts) sql-params) From 30927dd8dde28233406d606db940632a2d3764a2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 Apr 2016 17:56:18 -0700 Subject: [PATCH 354/630] Fix JDBC-124 and prep for 0.6.0-alpha2 --- CHANGES.md | 11 ++- README.md | 16 +++- src/main/clojure/clojure/java/jdbc.clj | 125 ++++++++----------------- 3 files changed, 57 insertions(+), 95 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 039c74a8..c48e185e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,13 @@ -Changes in 0.6.0 +Changes in 0.6.0-alpha2 * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). + - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. +* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/JDBC-124). +* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/JDBC-123). + +Changes in 0.6.0-alpha1 + +* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed @@ -195,7 +202,7 @@ Major overhaul of the API and deprecation of most of the old API! * Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) Note: JDBC-40 has been reverted in 0.3.0-alpha2 because it introduced regressions for PostgreSQL -* db-do-command allows you to execute SQL without a transaction wrapping it +* db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies diff --git a/README.md b/README.md index 30bdf82b..ffdb7f84 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.0-alpha1 +Latest stable release: 0.6.0-alpha2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.0-alpha1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.0-alpha1"] +[org.clojure/java.jdbc "0.6.0-alpha2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.0-alpha1 + 0.6.0-alpha2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,8 +104,14 @@ Developer Information Change Log ==================== -* Release 0.6.0-alpha1 on 2016-04-13 -- BREAKING RELEASE! +* Release 0.6.0-alpha2 on 2016-04-18 -- BREAKING RELEASE! * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). + - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. + * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/JDBC-124). + * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/JDBC-123). + +* Release 0.6.0-alpha1 on 2016-04-13 -- BREAKING RELEASE! + * (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed @@ -255,7 +261,7 @@ Change Log * Add :as-arrays to query / result-set-seq [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) * Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) Note: JDBC-40 is being reverted in 0.3.0-alpha2 because it introduces regressions in PostgreSQL - * db-do-command allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) + * db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c9e350d5..52208152 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -684,36 +684,22 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "Executes SQL commands on the specified database connection. Wraps the commands in a transaction if transaction? is true. transaction? can be ommitted and it defaults to true. Accepts a single SQL command (string) or a vector of them. - For backward compatibility, also accepts multiple string arguments but that - is deprecated and will be removed in 0.6.0. Uses executeBatch. This may affect what SQL you can run via db-do-commands." ([db sql-commands] (db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands))) ([db transaction? sql-commands] - (cond (string? transaction?) - ;; legacy call with two commands - (do - (println "DEPRECATED: unrolled SQL string arguments in db-do-commands") - (db-do-commands db true [transaction? sql-commands])) - (string? sql-commands) - ;; (db-do-commands db bool-val "SQL string") is acceptable - (db-do-commands db transaction? [sql-commands]) - :else - (if-let [con (db-find-connection db)] - (with-open [^Statement stmt (.createStatement con)] - (doseq [^String cmd sql-commands] - (.addBatch stmt cmd)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt))) - (with-open [con (get-connection db)] - (db-do-commands (add-connection db con) transaction? sql-commands))))) - ([db t-or-cmd cmd-1 cmd-2 & cmds] - (println "DEPRECATED: unrolled SQL string arguments in db-do-commands") - (if (string? t-or-cmd) - (db-do-commands db true (concat [t-or-cmd cmd-1 cmd-2] cmds)) - (db-do-commands db t-or-cmd (concat [cmd-1 cmd-2] cmds))))) + (if (string? sql-commands) + (db-do-commands db transaction? [sql-commands]) + (if-let [con (db-find-connection db)] + (with-open [^Statement stmt (.createStatement con)] + (doseq [^String cmd sql-commands] + (.addBatch stmt cmd)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt))) + (with-open [con (get-connection db)] + (db-do-commands (add-connection db con) transaction? sql-commands)))))) (defn- db-do-execute-prepared-return-keys "Executes a PreparedStatement, optionally in a transaction, and (attempts to) @@ -740,8 +726,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- sql-stmt? "Given an expression, return true if it is either a string (SQL) or a - PreparedStatement. Used primarily to support legacy (deprecated) API - calls." + PreparedStatement." [expr] (or (string? expr) (instance? PreparedStatement expr))) @@ -755,30 +740,18 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } ([db sql-params] (db-do-prepared-return-keys db true sql-params {})) ([db transaction? sql-params] - (cond (map? sql-params) - ;; transaction? omitted - (db-do-prepared-return-keys db true transaction? sql-params) - (sql-stmt? transaction?) - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") - (db-do-prepared-return-keys db true (into [transaction?] sql-params) {})) - :else - ;; opts? omitted - (db-do-prepared-return-keys db transaction? sql-params {}))) + (if (map? sql-params) + (db-do-prepared-return-keys db true transaction? sql-params) + (db-do-prepared-return-keys db transaction? sql-params {}))) ([db transaction? sql-params opts] - (cond (map? opts) - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) [sql-params] sql-params)] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-return-keys db sql params transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] - (db-do-execute-prepared-return-keys db stmt params transaction?)))) - (with-open [con (get-connection db)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))) - :else - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared-return-keys") - (db-do-prepared-return-keys db transaction? (into [sql-params] opts) {}))))) + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-return-keys db sql params transaction?) + (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] + (db-do-execute-prepared-return-keys db stmt params transaction?)))) + (with-open [con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))) (defn- db-do-execute-prepared-statement "Execute a PreparedStatement, optionally in a transaction." @@ -806,41 +779,19 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } ([db sql-params] (db-do-prepared db true sql-params {})) ([db transaction? sql-params] - (cond (map? sql-params) - ;; transaction? omitted - (db-do-prepared db true transaction? sql-params) - (sql-stmt? transaction?) - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") - (db-do-prepared db true (into [transaction?] sql-params) {})) - :else - ;; opts omitted - (db-do-prepared db transaction? sql-params {}))) + (if (map? sql-params) + (db-do-prepared db true transaction? sql-params) + (db-do-prepared db transaction? sql-params {}))) ([db transaction? sql-params opts] - (cond (map? opts) - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) [sql-params] sql-params) - params (if (or (:multi? opts) (empty? params)) params [params])] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql params transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql)] - (db-do-execute-prepared-statement db stmt params transaction?)))) - (with-open [con (get-connection db)] - (db-do-prepared (add-connection db con) transaction? sql-params opts))) - (sql-stmt? transaction?) - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") - (db-do-prepared db true [transaction? sql-params opts] {:multi? true})) - :else - (do - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") - (db-do-prepared db transaction? [sql-params opts] {:multi? true})))) - ([db t-or-sql-p-g sql-pg-1 pg-2 & pgs] - ;; legacy deprecated - (println "DEPRECATED: unrolled sql / param groups in db-do-prepared") - (if (sql-stmt? t-or-sql-p-g) - (db-do-prepared db true (concat [t-or-sql-p-g sql-pg-1 pg-2] pgs) {:multi? true}) - (db-do-prepared db t-or-sql-p-g (concat [sql-pg-1 pg-2] pgs) {:multi? true})))) + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + params (if (or (:multi? opts) (empty? params)) params [params])] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-statement db sql params transaction?) + (with-open [^PreparedStatement stmt (prepare-statement con sql)] + (db-do-execute-prepared-statement db stmt params transaction?)))) + (with-open [con (get-connection db)] + (db-do-prepared (add-connection db con) transaction? sql-params opts))))) (defn db-query-with-resultset "Executes a query, then evaluates func passing in the raw ResultSet as an @@ -906,9 +857,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } :or {row-fn identity identifiers str/lower-case}}] (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) - sql-params-vector (if (sql-stmt? sql-params) - (vector sql-params) - (vec sql-params))] + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (db-query-with-resultset db sql-params-vector (^{:once true} fn* [rset] ((^{:once true} fn* [rs] From d4f32ed5de1b771497c00be7c96ffe1cede686de Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 18 Apr 2016 17:58:29 -0700 Subject: [PATCH 355/630] Update project.clj for testing --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index b1ba559f..94d59d33 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0-alpha1" +(defproject org.clojure/java.jdbc "0.6.0-alpha2" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 37206d75e39f58bc2b7ce7c89d51fbbd4c06ba0e Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 18 Apr 2016 19:58:58 -0500 Subject: [PATCH 356/630] [maven-release-plugin] prepare release java.jdbc-0.6.0-alpha2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7a8d1434..125e1160 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.1-SNAPSHOT + 0.6.0-alpha2 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.0-alpha2 From 7807d9c905964c50e679630dc0b1482d5d1957e0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 18 Apr 2016 19:58:58 -0500 Subject: [PATCH 357/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 125e1160..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-alpha2 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.0-alpha2 + HEAD From f802debd2c30492749fa4204aa49f7848f2f1ee6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 24 Apr 2016 22:24:05 -0700 Subject: [PATCH 358/630] Correct links in README / CHANGES --- CHANGES.md | 18 +++++++++--------- README.md | 20 ++++++++++---------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c48e185e..4d77e478 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,13 +1,13 @@ Changes in 0.6.0-alpha2 -* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). +* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. -* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/JDBC-124). -* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/JDBC-123). +* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). +* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). Changes in 0.6.0-alpha1 -* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). +* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed @@ -15,17 +15,17 @@ Changes in 0.6.0-alpha1 Changes in 0.5.8 -* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. -* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. +* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. +* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. Changes in 0.5.7 -* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). +* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/browse/JDBC-121). Changes in 0.5.6 -* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. -* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. +* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/browse/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. +* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/browse/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. * NOTE: all deprecated functionality will go away in version 0.6.0! Changes in 0.5.5 diff --git a/README.md b/README.md index ffdb7f84..b9ccfb89 100644 --- a/README.md +++ b/README.md @@ -105,29 +105,29 @@ Change Log ==================== * Release 0.6.0-alpha2 on 2016-04-18 -- BREAKING RELEASE! - * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). + * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. - * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/JDBC-124). - * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/JDBC-123). + * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). + * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). * Release 0.6.0-alpha1 on 2016-04-13 -- BREAKING RELEASE! - * (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/JDBC-118). + * (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed - The `java.jdbc.deprecated` namespace has been removed * Release 0.5.8 on 2016-04-12 - * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. - * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. + * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. + * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. * Release 0.5.7 on 2016-04-10 - * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/JDBC-121). + * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/browse/JDBC-121). * Release 0.5.6 on 2016-04-10 - * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/JDBC-120). + * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/browse/JDBC-120). - If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. - * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/JDBC-119). + * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/browse/JDBC-119). - If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. * NOTE: all deprecated functionality will go away in version 0.6.0! @@ -297,7 +297,7 @@ Change Log * Remove dependence on deprecated structmap [JDBC-15](http://dev.clojure.org/jira/browse/JDBC-15) * Release 0.0.7 on 2011-10-11 * Rename duplicate columns [JDBC-9](http://dev.clojure.org/jira/browse/JDBC-9) - * Ensure do-preared traps invalid SQL [JDBC-16](http://dev.clojure.org/jira/JDBC-16) + * Ensure do-preared traps invalid SQL [JDBC-16](http://dev.clojure.org/jira/browse/JDBC-16) * Release 0.0.6 on 2011-08-04 * Improve exception handling (unwrap RTE) * Don't use batch for update (causes exceptions on Apache Derby) [JDBC-12](http://dev.clojure.org/jire/JDBC-12) From f2d0aec8d9d90a7faf583ac8b21f726feef3607e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 1 May 2016 15:54:46 -0700 Subject: [PATCH 359/630] Adds get-by-id / find-by-keys for 0.6.0 RC 1 --- CHANGES.md | 6 ++ project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 66 ++++++++++++++++----- src/test/clojure/clojure/java/test_jdbc.clj | 6 +- 4 files changed, 63 insertions(+), 17 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 4d77e478..4d3af5bb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,9 @@ +Changes coming in 0.6.0-rc1 + +* Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). +* REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). + - See alpha2 / alpha1 below for more details. + Changes in 0.6.0-alpha2 * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). diff --git a/project.clj b/project.clj index 94d59d33..b7307728 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0-alpha2" +(defproject org.clojure/java.jdbc "0.6.0-rc1" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 52208152..d6d1b7a7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -81,6 +81,27 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (str (first q) x (last q)) (str q x q)))) +(defn- table-str + "Transform a table spec to an entity name for SQL. The table spec may be a + string, a keyword or a map with a single pair - table name and alias." + [table entities] + (let [entities (or entities identity)] + (if (map? table) + (let [[k v] (first table)] + (str (as-sql-name entities k) " " (as-sql-name entities v))) + (as-sql-name entities table)))) + +(defn- kv-sql + "Given a sequence of column name keys and a matching sequence of column + values, and an entities mapping function, return a sequence of SQL fragments + that can be joined for part of an UPDATE SET or a SELECT WHERE clause." + [ks vs entities] + (map (fn [k v] + (str (as-sql-name entities k) + " = " + (if (nil? v) "NULL" "?"))) + ks vs)) + (defn- ^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. Uses as-sql-name to convert both keys and values into strings." @@ -867,6 +888,35 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (map row-fn rs)))) (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?}))))))) +(defn find-by-keys + "Given a database connection, a table name, a map of column name/value + pairs, and an optional options map, return any matching rows." + ([db table columns] (find-by-keys db table columns {})) + ([db table columns opts] + (let [entities (:entities opts identity) + ks (keys columns) + vs (vals columns)] + (query db (into [(str "SELECT * FROM " (table-str table entities) + " WHERE " (str/join " AND " + (kv-sql ks vs entities)))] + (remove nil? vs)) + opts)))) + +(defn get-by-id + "Given a database connection, a table name, a primary key value, an + optional primary key column name, and an optional options map, return + a single matching row, or nil. + The primary key column name defaults to :id." + ([db table pk-value] (get-by-id db table pk-value :id {})) + ([db table pk-value pk-name-or-opts] + (if (map? pk-name-or-opts) + (get-by-id db table pk-value :id pk-name-or-opts) + (get-by-id db table pk-value pk-name-or-opts {}))) + ([db table pk-value pk-name opts] + (let [r-s-fn (or (:result-set-fn opts) identity)] + (find-by-keys db table {pk-name pk-value} + (assoc opts :result-set-fn (comp first r-s-fn)))))) + (defn execute! "Given a database connection and a vector containing SQL (or PreparedStatement) followed by optional parameters, perform a general (non-select) SQL operation. @@ -891,16 +941,6 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (with-open [con (get-connection db)] (execute-helper (add-connection db con))))))) -(defn- table-str - "Transform a table spec to an entity name for SQL. The table spec may be a - string, a keyword or a map with a single pair - table name and alias." - [table entities] - (let [entities (or entities identity)] - (if (map? table) - (let [[k v] (first table)] - (str (as-sql-name entities k) " " (as-sql-name entities v))) - (as-sql-name entities table)))) - (defn- delete-sql "Given a table name, a where class and its parameters and an optional entities spec, return a vector of the SQL for that delete operation followed by its parameters. The @@ -1051,11 +1091,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (cons (str "UPDATE " (table-str table entities) " SET " (str/join "," - (map (fn [k v] - (str (as-sql-name entities k) - " = " - (if (nil? v) "NULL" "?"))) - ks vs)) + (kv-sql ks vs entities)) (when where " WHERE ") where) (concat (remove nil? vs) params)))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 60364a06..b311fd97 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -379,7 +379,11 @@ (is (= 2 (sql/with-db-connection [con db] (sql/query con [(sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit" {:max-rows 2})] {:result-set-fn count})))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) - (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first}))))) + (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first}))) + (is (= "Apple" (:name (sql/get-by-id db :fruit 1)))) + (is (= ["Apple"] (map :name (sql/find-by-keys db :fruit {:appearance "red"})))) + (is (= "Peach" (:name (sql/get-by-id db :fruit 3 :id)))) + (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))))) (deftest test-insert-values (doseq [db (test-specs)] From d88d8a762192682bc16c383abf9d2b3c8752f53d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 4 May 2016 13:46:39 -0700 Subject: [PATCH 360/630] Prep for 0.6.0 RC 1 --- CHANGES.md | 2 +- README.md | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 4d3af5bb..f9986f9c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.6.0-rc1 +Changes in 0.6.0-rc1 * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). * REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). diff --git a/README.md b/README.md index b9ccfb89..7cbf5e84 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.0-alpha2 +Latest stable release: 0.6.0-rc1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.0-alpha2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.0-alpha2"] +[org.clojure/java.jdbc "0.6.0-rc1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.0-alpha2 + 0.6.0-rc1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,11 @@ Developer Information Change Log ==================== +* Release 0.6.0-rc1 on 2016-05-04 + * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). + * REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). + - See alpha2 / alpha1 below for more details. + * Release 0.6.0-alpha2 on 2016-04-18 -- BREAKING RELEASE! * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. From 88c2ed762cdca7ead09ef2d9748f75fc7b9e189a Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 4 May 2016 15:48:31 -0500 Subject: [PATCH 361/630] [maven-release-plugin] prepare release java.jdbc-0.6.0-rc1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95806b9f..a8b022ce 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.6.0-rc1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.0-rc1 From 1763bae6418fbc46b8942ad8b73e448bc09d0ba0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 4 May 2016 15:48:31 -0500 Subject: [PATCH 362/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a8b022ce..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-rc1 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.0-rc1 + HEAD From 586358abba2a3f66b5ee2cda25ddd75c411e65d5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 7 May 2016 19:05:26 -0700 Subject: [PATCH 363/630] JDBC-125 pass query opts through to prepare-statement This also adds an options map arguemnt to db-query-with-resultset and removes support for the old (undocumented) approach of supplying the prepare-statement options as the first element of the [sql & params] map. --- CHANGES.md | 5 ++ project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 75 ++++++++++----------- src/test/clojure/clojure/java/test_jdbc.clj | 4 +- 4 files changed, 43 insertions(+), 43 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f9986f9c..c9fe23a7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes coming in 0.6.0 + +* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement`. `query`'s options map is passed through `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). + - Passing the `prepare-statement` options as the first element of the `[sql & params]` vector is no longer supported (it was very poorly documented and almost never used). + Changes in 0.6.0-rc1 * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). diff --git a/project.clj b/project.clj index b7307728..4c488b96 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0-rc1" +(defproject org.clojure/java.jdbc "0.6.0" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d6d1b7a7..3645b016 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -769,7 +769,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (if (instance? PreparedStatement sql) (db-do-execute-prepared-return-keys db sql params transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql {:return-keys true})] + (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] (db-do-execute-prepared-return-keys db stmt params transaction?)))) (with-open [con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))) @@ -809,7 +809,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } params (if (or (:multi? opts) (empty? params)) params [params])] (if (instance? PreparedStatement sql) (db-do-execute-prepared-statement db sql params transaction?) - (with-open [^PreparedStatement stmt (prepare-statement con sql)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] (db-do-execute-prepared-statement db stmt params transaction?)))) (with-open [con (get-connection db)] (db-do-prepared (add-connection db con) transaction? sql-params opts))))) @@ -820,50 +820,43 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } [sql & params] - a SQL query, followed by any parameters it needs [stmt & params] - a PreparedStatement, followed by any parameters it needs (the PreparedStatement already contains the SQL query) - [options sql & params] - options and a SQL query for creating a - PreparedStatement, followed by any parameters it needs - See prepare-statement for supported options. + The opts map is passed to prepare-statement. Uses executeQuery. This may affect what SQL you can run via query." {:arglists '([db-spec [sql-string & params] func] [db-spec [stmt & params] func] [db-spec [options-map sql-string & params] func])} - [db sql-params func] - (when-not (vector? sql-params) - (let [^Class sql-params-class (class sql-params) - ^String msg (format "\"%s\" expected %s %s, found %s %s" - "sql-params" - "vector" - "[sql param*]" - (.getName sql-params-class) - (pr-str sql-params))] - (throw (IllegalArgumentException. msg)))) - (let [[prepare-args sql & params] (if (map? (first sql-params)) - sql-params - (cons nil sql-params)) - run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] - ((or (:set-parameters db) set-parameters) stmt params) - (with-open [rset (.executeQuery stmt)] - (func rset)))] - (if (instance? PreparedStatement sql) - - (let [^PreparedStatement stmt sql] - (when prepare-args - (throw (IllegalArgumentException. "query/db-query-with-resultset: options ignored when PreparedStatement provided"))) - (run-query-with-params stmt)) - - (if-let [con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql prepare-args)] - (run-query-with-params stmt)) - (with-open [con (get-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql prepare-args)] - (run-query-with-params stmt))))))) + ([db sql-params func] (db-query-with-resultset db sql-params func {})) + ([db sql-params func opts] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] + ((or (:set-parameters db) set-parameters) stmt params) + (with-open [rset (.executeQuery stmt)] + (func rset)))] + (when-not (sql-stmt? sql) + (let [^Class sql-class (class sql) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-class) + (pr-str sql))] + (throw (IllegalArgumentException. msg)))) + (if (instance? PreparedStatement sql) + (let [^PreparedStatement stmt sql] + (run-query-with-params stmt)) + (if-let [con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (run-query-with-params stmt)) + (with-open [con (get-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (run-query-with-params stmt)))))))) ;; top-level API for actual SQL operations (defn query "Given a database connection and a vector containing SQL and optional parameters, perform a simple database query. The options specify how to construct the result - set: + set (and are also passed to prepare-statement as needed): :result-set-fn - applied to the entire result set, default doall / vec if :as-arrays? true, :result-set-fn will default to vec if :as-arrays? false, :result-set-fn will default to doall @@ -871,12 +864,13 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } :identifiers - applied to each column name in the result set, default lower-case :as-arrays? - return the results as a set of arrays, default false. The second argument is a vector containing a SQL string or PreparedStatement, followed - by any parameters it needs. It may optionally include an options map before the SQL - string or PreparedStatement. See db-query-with-resultset for details." + by any parameters it needs. + See also prepare-statement for additional options." ([db sql-params] (query db sql-params {})) ([db sql-params {:keys [result-set-fn row-fn identifiers as-arrays?] :or {row-fn identity - identifiers str/lower-case}}] + identifiers str/lower-case} + :as opts}] (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (db-query-with-resultset db sql-params-vector @@ -886,7 +880,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (cons (first rs) (map row-fn (rest rs))) (map row-fn rs)))) - (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?}))))))) + (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?}))) + opts)))) (defn find-by-keys "Given a database connection, a table name, a map of column name/value diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index b311fd97..15d22ff7 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -375,7 +375,7 @@ (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 4 (sql/with-db-connection [con db] (sql/query con (sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit") {:result-set-fn count})))) - (is (= 2 (sql/query db [{:max-rows 2} "SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count :max-rows 2}))) (is (= 2 (sql/with-db-connection [con db] (sql/query con [(sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit" {:max-rows 2})] {:result-set-fn count})))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) @@ -809,7 +809,7 @@ (with-open [con (sql/get-connection db)] (sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")])))) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] - (sql/query db [{:max-rows 1} "SELECT * FROM fruit"])))))) + (sql/query db ["SELECT * FROM fruit"] {:max-rows 1})))))) (deftest insert-two-by-map-and-query (doseq [db (test-specs)] From 3d03e0bbc38e17a6f6e8ec6f6190335b230f0798 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 7 May 2016 19:48:59 -0700 Subject: [PATCH 364/630] find-by-keys :order-by option; prep for 0.6.0-rc2 --- CHANGES.md | 12 ++++++--- README.md | 30 ++++++++++----------- project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 30 ++++++++++++++++++++- src/test/clojure/clojure/java/test_jdbc.clj | 6 +++-- 5 files changed, 56 insertions(+), 24 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c9fe23a7..4b96245e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,11 @@ -Changes coming in 0.6.0 - -* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement`. `query`'s options map is passed through `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). - - Passing the `prepare-statement` options as the first element of the `[sql & params]` vector is no longer supported (it was very poorly documented and almost never used). +Changes in 0.6.0-rc2 + +* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). + - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. +* `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. +* `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. +* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). +* `find-by-keys` now accepts an `:order-by` option that specifies a sequence of orderings; an ordering is either a column (to sort ascending) or a map from column name to direct (`:asc` or `:desc`). Changes in 0.6.0-rc1 diff --git a/README.md b/README.md index 7cbf5e84..76eb0312 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.0-rc1 +Latest stable release: 0.6.0-rc2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.0-rc1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.0-rc1"] +[org.clojure/java.jdbc "0.6.0-rc2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.0-rc1 + 0.6.0-rc2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,19 +104,17 @@ Developer Information Change Log ==================== -* Release 0.6.0-rc1 on 2016-05-04 - * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). - * REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - - See alpha2 / alpha1 below for more details. - -* Release 0.6.0-alpha2 on 2016-04-18 -- BREAKING RELEASE! - * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). - - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. - * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). - * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). - -* Release 0.6.0-alpha1 on 2016-04-13 -- BREAKING RELEASE! - * (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). +* Release 0.6.0-rc2 on 2016-05-07 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** + * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. + - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. + * `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. 0.6.0-rc2 / 2016-05-07. + * `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. 0.6.0-rc2 / 2016-05-07. + * `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. + * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). 0.6.0-rc1 / 2016-05-04. + - `find-by-keys` accepts an `:order-by` option that expects a sequence of orderings; an ordering is a column name (keyword) or a map from column name (keyword) to direction (`:asc` or `:desc`). 0.6.0-rc2 / 2016-05-07. + * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). 0.6.0-alpha2 / 2016-04-18. + * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). 0.6.0-alpha2 / 2016-04-18. + * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). 0.6.0-alpha1 / 2016-04-13 - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed diff --git a/project.clj b/project.clj index 4c488b96..3c69ee98 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0" +(defproject org.clojure/java.jdbc "0.6.0-rc2" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 3645b016..8b8cbe89 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -883,17 +883,45 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?}))) opts)))) +(defn- direction + "Given an entities function, a column name, and a direction, + return the matching SQL column / order. + Throw an exception for an invalid direction." + [entities c d] + (str (as-sql-name entities c) " " + (if-let [dir (#{"ASC" "DESC"} (str/upper-case (name d)))] + dir + (throw (IllegalArgumentException. (str "expected :asc or :desc, found: " d)))))) + +(defn- order-by-sql + "Given a sequence of column specs and an entities function, return + a SQL fragment for the ORDER BY clause. A column spec may be a name + (either a string or keyword) or a map from column name to direction + (:asc or :desc)." + [order-by entities] + (str/join ", " (mapcat (fn [col] + (if (map? col) + (reduce-kv (fn [v c d] + (conj v (direction entities c d))) + [] + col) + [(direction entities col :asc)])) order-by))) + (defn find-by-keys "Given a database connection, a table name, a map of column name/value pairs, and an optional options map, return any matching rows." ([db table columns] (find-by-keys db table columns {})) ([db table columns opts] (let [entities (:entities opts identity) + order-by (:order-by opts) ks (keys columns) vs (vals columns)] (query db (into [(str "SELECT * FROM " (table-str table entities) " WHERE " (str/join " AND " - (kv-sql ks vs entities)))] + (kv-sql ks vs entities)) + (when order-by + (str " ORDER BY " + (order-by-sql order-by entities))))] (remove nil? vs)) opts)))) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 15d22ff7..70056237 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -370,7 +370,7 @@ [[1 "Apple" "red" 59 87] [2 "Banana" "yellow" 29 92.2] [3 "Peach" "fuzzy" 139 90.0] - [4 "Orange" "juicy" 89 88.6]])] + [4 "Orange" "juicy" 139 88.6]])] (is (= '(1 1 1 1) r))) (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 4 (sql/with-db-connection [con db] @@ -383,7 +383,9 @@ (is (= "Apple" (:name (sql/get-by-id db :fruit 1)))) (is (= ["Apple"] (map :name (sql/find-by-keys db :fruit {:appearance "red"})))) (is (= "Peach" (:name (sql/get-by-id db :fruit 3 :id)))) - (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))))) + (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))) + (is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]})))) + (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))))) (deftest test-insert-values (doseq [db (test-specs)] From 862180eaba44c08327728e2505bdefbbcdb4c6d2 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 7 May 2016 22:11:58 -0500 Subject: [PATCH 365/630] [maven-release-plugin] prepare release java.jdbc-0.6.0-rc2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95806b9f..9edbcd5e 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.6.0-rc2 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.0-rc2 From 1a503ba669c8fad29dcb36410ead352fd70ef7c9 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 7 May 2016 22:11:58 -0500 Subject: [PATCH 366/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9edbcd5e..95806b9f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-rc2 + 0.6.0-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.0-rc2 + HEAD From 190a8c7257c4de6e9859d7e5d0240d919c3788c2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 7 May 2016 20:34:25 -0700 Subject: [PATCH 367/630] Remove arglist, update docstrings --- src/main/clojure/clojure/java/jdbc.clj | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8b8cbe89..19a36f11 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -822,9 +822,6 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (the PreparedStatement already contains the SQL query) The opts map is passed to prepare-statement. Uses executeQuery. This may affect what SQL you can run via query." - {:arglists '([db-spec [sql-string & params] func] - [db-spec [stmt & params] func] - [db-spec [options-map sql-string & params] func])} ([db sql-params func] (db-query-with-resultset db sql-params func {})) ([db sql-params func opts] (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) @@ -909,7 +906,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn find-by-keys "Given a database connection, a table name, a map of column name/value - pairs, and an optional options map, return any matching rows." + pairs, and an optional options map, return any matching rows. + An :order-by option may be supplied to sort the rows by a sequence of + columns, e.g,. {:order-by [:name {:age :desc]}" ([db table columns] (find-by-keys db table columns {})) ([db table columns opts] (let [entities (:entities opts identity) From e9853e031bb1b6b84dbff22611fb0df4bc637c2a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 11 May 2016 11:45:21 -0700 Subject: [PATCH 368/630] If :order-by is [], no ORDER BY should be added. --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 19a36f11..6c3f3112 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -918,7 +918,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (query db (into [(str "SELECT * FROM " (table-str table entities) " WHERE " (str/join " AND " (kv-sql ks vs entities)) - (when order-by + (when (seq order-by) (str " ORDER BY " (order-by-sql order-by entities))))] (remove nil? vs)) From 0d4a46c5703079db6489d741f745b52a2253c9ef Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 11 May 2016 13:25:57 -0700 Subject: [PATCH 369/630] Fix JDBC-126 and prepare for 0.6.0 Gold release. --- CHANGES.md | 5 +++++ README.md | 10 ++++++---- project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 13 +++++++------ 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 4b96245e..b048b9b0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes in 0.6.0 + +* `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). +* `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. + Changes in 0.6.0-rc2 * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). diff --git a/README.md b/README.md index 76eb0312..db020c46 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.0-rc2 +Latest stable release: 0.6.0 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.0-rc2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.0-rc2"] +[org.clojure/java.jdbc "0.6.0"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.0-rc2 + 0.6.0 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,7 +104,9 @@ Developer Information Change Log ==================== -* Release 0.6.0-rc2 on 2016-05-07 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** +* Release 0.6.0 on 2016-05-07 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** + * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). 0.6.0 / 2016-05-11. + * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. 0.6.0 / 2016-05-11. * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. * `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. 0.6.0-rc2 / 2016-05-07. diff --git a/project.clj b/project.clj index 3c69ee98..4c488b96 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0-rc2" +(defproject org.clojure/java.jdbc "0.6.0" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6c3f3112..c6aff58f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -94,12 +94,13 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- kv-sql "Given a sequence of column name keys and a matching sequence of column values, and an entities mapping function, return a sequence of SQL fragments - that can be joined for part of an UPDATE SET or a SELECT WHERE clause." - [ks vs entities] + that can be joined for part of an UPDATE SET or a SELECT WHERE clause. + Note that we pass the appropriate operator for NULL since it is different + in each case." + [ks vs entities null-op] (map (fn [k v] (str (as-sql-name entities k) - " = " - (if (nil? v) "NULL" "?"))) + (if (nil? v) null-op " = ?"))) ks vs)) (defn- ^Properties as-properties @@ -917,7 +918,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } vs (vals columns)] (query db (into [(str "SELECT * FROM " (table-str table entities) " WHERE " (str/join " AND " - (kv-sql ks vs entities)) + (kv-sql ks vs entities " IS NULL")) (when (seq order-by) (str " ORDER BY " (order-by-sql order-by entities))))] @@ -1113,7 +1114,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (cons (str "UPDATE " (table-str table entities) " SET " (str/join "," - (kv-sql ks vs entities)) + (kv-sql ks vs entities " = NULL")) (when where " WHERE ") where) (concat (remove nil? vs) params)))) From 795c136436cc03f7e4d9ae2da16d280fcb8c5536 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 11 May 2016 15:28:37 -0500 Subject: [PATCH 370/630] [maven-release-plugin] prepare release java.jdbc-0.6.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95806b9f..81b55b1a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0-SNAPSHOT + 0.6.0 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.0 From 8c1e8be3df43edd5e60106f617764c61af8cf618 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 11 May 2016 15:28:37 -0500 Subject: [PATCH 371/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 81b55b1a..7a8d1434 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.0 + 0.6.1-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.0 + HEAD From fcb4fc4d8676cbbed463204e24a3011c0ca3b203 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 17:06:14 -0700 Subject: [PATCH 372/630] Remove transaction around DDL JDBC-127 --- src/test/clojure/clojure/java/test_jdbc.clj | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 70056237..dcab5ea9 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -110,13 +110,12 @@ "Attempt to drop any test tables before we start a test." [t] (doseq [db (test-specs)] - (sql/with-db-transaction [t-conn db] - (doseq [table [:fruit :fruit2 :veggies :veggies2]] - (try - (sql/db-do-commands t-conn (sql/drop-table-ddl table)) - (catch Exception _ - ;; ignore - ))))) + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/db-do-commands db (sql/drop-table-ddl table)) + (catch Exception _ + ;; ignore + )))) (t)) (use-fixtures From 925613bd522d8ba9d363298e2d3ee6f0a76d1869 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 17:34:32 -0700 Subject: [PATCH 373/630] Clarify insert rows/cols return values in docstrings JDBC-127 --- src/main/clojure/clojure/java/jdbc.clj | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c6aff58f..d57d8dfd 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1073,6 +1073,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "Given a database connection, a table name and either a map representing a rows, or a list of column names followed by a list of column values also representing a single row, perform an insert. + When inserting a row as a map, the result is the database-specific form of the + generated keys, if available (note: PostgreSQL returns the whole row). + When inserting a row as a list of column values, the result is the count of + rows affected (1), if available (from getUpdateCount after executeBatch). The row map or column value vector may be followed by a map of options: The :transaction? option specifies whether to run in a transaction or not. The default is true (use a transaction). The :entities option specifies how @@ -1090,6 +1094,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } rows) or a sequence of column names, followed by a sequence of vectors (for the values in each row), and possibly a map of options, insert that data into the database. + When inserting rows as a sequence of maps, the result is a sequence of the + generated keys, if available (note: PostgreSQL returns the whole rows). + When inserting rows as a sequence of lists of column values, the result is + a sequence of the counts of rows affected (a sequence of 1's), if available. + Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch! The :transaction? option specifies whether to run in a transaction or not. The default is true (use a transaction). The :entities option specifies how to convert the table name and column names to SQL entities." From 8985093aa8f8642201314261fcef65489e9f0b9d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 17:05:33 -0700 Subject: [PATCH 374/630] Fix tests for PostgreSQL JDBC-127 JDBC-129 Adds `select-key` helper to deal with most DBs returning just the generated key in some form but PostgreSQL helpfully returning the entire row (we should probably parameterize the key column name but all the tests use `:id` at the moment). This allowed me to remove all the conditional `map :id` calls. Cleaned up host/port handling; add PostgreSQL host/port support. My local test script sets `TEST_POSTGRES_HOST` based on my local Docker image's IP address. I also have postgres-up/-down scripts (ignored by Git) in case anyone is interested -- I could put them in the repo. Tested against sqlite, derby, hsqldb, h2, mysql, mssql (type 4), mssql (jtds), and postgres! --- .gitignore | 2 + src/test/clojure/clojure/java/test_jdbc.clj | 89 +++++++++------------ 2 files changed, 41 insertions(+), 50 deletions(-) diff --git a/.gitignore b/.gitignore index 75d90c3f..4c0fdbdb 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ derby.log settings.xml target test-all.sh +/postgres-down.sh +/postgres-up.sh diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index dcab5ea9..75926399 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -34,26 +34,20 @@ [:derby :hsqldb :h2 :sqlite])) ;; MS SQL Server requires more specialized configuration: -(def mssql-host - (if-let [host (System/getenv "TEST_MSSQL_HOST")] host "127.0.0.1\\SQLEXPRESS")) -(def mssql-port - (if-let [port (System/getenv "TEST_MSSQL_PORT")] port "1433")) -(def mssql-user - (if-let [user (System/getenv "TEST_MSSQL_USER")] user "sa")) -(def mssql-pass - (if-let [pass (System/getenv "TEST_MSSQL_PASS")] pass "")) -(def mssql-dbname - (if-let [name (System/getenv "TEST_MSSQL_NAME")] name "clojure_test")) -(def jtds-host - (if-let [host (System/getenv "TEST_JTDS_HOST")] host mssql-host)) -(def jtds-port - (if-let [port (System/getenv "TEST_JTDS_PORT")] port mssql-port)) -(def jtds-user - (if-let [user (System/getenv "TEST_JTDS_USER")] user mssql-user)) -(def jtds-pass - (if-let [pass (System/getenv "TEST_JTDS_PASS")] pass mssql-pass)) -(def jtds-dbname - (if-let [name (System/getenv "TEST_JTDS_NAME")] name mssql-dbname)) +(def mssql-host (or (System/getenv "TEST_MSSQL_HOST") "127.0.0.1\\SQLEXPRESS")) +(def mssql-port (or (System/getenv "TEST_MSSQL_PORT") "1433")) +(def mssql-user (or (System/getenv "TEST_MSSQL_USER") "sa")) +(def mssql-pass (or (System/getenv "TEST_MSSQL_PASS") "")) +(def mssql-dbname (or (System/getenv "TEST_MSSQL_NAME") "clojure_test")) +(def jtds-host (or (System/getenv "TEST_JTDS_HOST") mssql-host)) +(def jtds-port (or (System/getenv "TEST_JTDS_PORT") mssql-port)) +(def jtds-user (or (System/getenv "TEST_JTDS_USER") mssql-user)) +(def jtds-pass (or (System/getenv "TEST_JTDS_PASS") mssql-pass)) +(def jtds-dbname (or (System/getenv "TEST_JTDS_NAME") mssql-dbname)) + +;; PostgreSQL host/port +(def postgres-host (or (System/getenv "TEST_POSTGRES_HOST") "127.0.0.1")) +(def postgres-port (or (System/getenv "TEST_POSTGRES_PORT") "5432")) ;; database connections used for testing: @@ -76,7 +70,7 @@ :dbname "clojure_test_sqlite"}) (def postgres-db {:subprotocol "postgresql" - :subname "clojure_test" + :subname (str "//" postgres-host ":" postgres-port "/clojure_test") :user "clojure_test" :password "clojure_test"}) @@ -207,6 +201,11 @@ "sqlite" {(keyword "last_insert_rowid()") k} k)) +(defn- select-key [db] + (condp = (or (:subprotocol db) (:dbtype db)) + "postgresql" :id + identity)) + (defn- generated-key [db k] (condp = (or (:subprotocol db) (:dbtype db)) "derby" 0 @@ -294,14 +293,14 @@ (doseq [db (test-specs)] (create-test-table :fruit2 db) (is (= (returned-key db 1) - (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"))) + ((select-key db) (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")))) (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1cii (doseq [db (test-specs)] (create-test-table :fruit2 db) (is (= (returned-key db 1) - (sql/db-do-prepared-return-keys db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"]))) + ((select-key db) (sql/db-do-prepared-return-keys db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"])))) (is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) (deftest test-do-prepared1di @@ -311,7 +310,7 @@ (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys true})] (is (= (returned-key db 1) - (sql/db-do-prepared-return-keys db [stmt]))))) + ((select-key db) (sql/db-do-prepared-return-keys db [stmt])))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-do-prepared1dii @@ -321,7 +320,7 @@ (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys true})] (is (= (returned-key db 1) - (sql/db-do-prepared-return-keys db stmt))))) + ((select-key db) (sql/db-do-prepared-return-keys db stmt)))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-do-prepared1e @@ -332,7 +331,7 @@ (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys ["id"]})] - (is (= (returned-key db 1) (sql/db-do-prepared-return-keys db stmt))))) + (is (= (returned-key db 1) ((select-key db) (sql/db-do-prepared-return-keys db stmt)))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))) (deftest test-do-prepared2 @@ -401,10 +400,10 @@ (deftest test-insert-records (doseq [db (test-specs)] (create-test-table :fruit db) - (let [r (sql/insert-multi! db - :fruit - [{:name "Pomegranate" :appearance "fresh" :cost 585} - {:name "Kiwifruit" :grade 93}])] + (let [r (map (select-key db) (sql/insert-multi! db + :fruit + [{:name "Pomegranate" :appearance "fresh" :cost 585} + {:name "Kiwifruit" :grade 93}]))] (is (= (list (returned-key db 1) (returned-key db 2)) r))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] {:row-fn :name :result-set-fn first}))))) @@ -771,36 +770,31 @@ (deftest insert-one-row (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"}) - new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"}))] (is (= [(returned-key db 1)] new-keys))))) (deftest insert-one-row-opts (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"} {}) - new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"} {}))] (is (= [(returned-key db 1)] new-keys))))) (deftest insert-one-col-val (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit [:name] ["Apple"]) - new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (let [new-keys (sql/insert! db :fruit [:name] ["Apple"])] (is (= [1] new-keys))))) (deftest insert-one-col-val-opts (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit [:name] ["Apple"] {}) - new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (let [new-keys (sql/insert! db :fruit [:name] ["Apple"] {})] (is (= [1] new-keys))))) (deftest insert-query (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"}) - new-keys (if (postgres? db) (map :id new-keys) new-keys)] + (let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"}))] (is (= [(returned-key db 1)] new-keys)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db "SELECT * FROM fruit"))) @@ -815,8 +809,7 @@ (deftest insert-two-by-map-and-query (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}]) - new-keys (if (postgres? db) (map :id new-keys) new-keys) + (let [new-keys (map (select-key db) (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}])) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} @@ -825,8 +818,7 @@ (deftest insert-two-by-map-and-query-as-arrays (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}]) - new-keys (if (postgres? db) (map :id new-keys) new-keys) + (let [new-keys (map (select-key db) (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}])) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] {:as-arrays? :cols-as-is})] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) @@ -846,8 +838,7 @@ (deftest insert-update-and-query (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"}) - new-keys (if (postgres? db) (map :id new-keys) new-keys) + (let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"})) update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"} ["id = ?" (generated-key db 1)]) rows (sql/query db ["SELECT * FROM fruit"])] @@ -861,8 +852,7 @@ (deftest insert-delete-and-query (doseq [db (test-specs)] (create-test-table :fruit db) - (let [new-keys (sql/insert! db :fruit {:name "Apple"}) - new-keys (if (postgres? db) (map :id new-keys) new-keys) + (let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"})) delete-result (sql/delete! db :fruit ["id = ?" (generated-key db 1)]) rows (sql/query db ["SELECT * FROM fruit"])] @@ -874,8 +864,7 @@ (doseq [db (test-specs)] (sql/with-db-connection [con-db db] (create-test-table :fruit con-db) - (let [new-keys (sql/insert! con-db :fruit {:name "Apple"}) - new-keys (if (postgres? con-db) (map :id new-keys) new-keys) + (let [new-keys (map (select-key db) (sql/insert! con-db :fruit {:name "Apple"})) delete-result (sql/delete! con-db :fruit ["id = ?" (generated-key con-db 1)]) rows (sql/query con-db ["SELECT * FROM fruit"])] From 1d0cadf61920d2b3862f67ac916b7778f2a46ac6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 17:59:50 -0700 Subject: [PATCH 375/630] Fix JDBC-128 by defaulting `:transaction?` on inserts --- src/main/clojure/clojure/java/jdbc.clj | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d57d8dfd..e26b9dc9 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1047,27 +1047,28 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- insert-rows! "Given a database connection, a table name, a sequence of rows, and an options map, insert the rows into the database." - [db table rows opts] - (let [entities (:entities opts identity) - sql-params (map (fn [row] + [db table rows {:keys [entities transaction?] + :or {entities identity transaction? true}}] + (let [sql-params (map (fn [row] (when-not (map? row) (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) (insert-single-row-sql table row entities)) rows)] (if-let [con (db-find-connection db)] - (insert-helper db (:transaction? opts) sql-params) + (insert-helper db transaction? sql-params) (with-open [con (get-connection db)] - (insert-helper (add-connection db con) (:transaction? opts) sql-params))))) + (insert-helper (add-connection db con) transaction? sql-params))))) (defn- insert-cols! "Given a database connection, a table name, a sequence of columns names, a sequence of vectors of column values, one per row, and an options map, insert the rows into the database." - [db table cols values opts] - (let [sql-params (insert-multi-row-sql table cols values (:entities opts identity))] + [db table cols values {:keys [entities transaction?] + :or {entities identity transaction? true}}] + (let [sql-params (insert-multi-row-sql table cols values entities)] (if-let [con (db-find-connection db)] - (db-do-prepared db (:transaction? opts) sql-params {:multi? true}) + (db-do-prepared db transaction? sql-params {:multi? true}) (with-open [con (get-connection db)] - (db-do-prepared (add-connection db con) (:transaction? opts) sql-params {:multi? true}))))) + (db-do-prepared (add-connection db con) transaction? sql-params {:multi? true}))))) (defn insert! "Given a database connection, a table name and either a map representing a rows, From 988e5735eff36d05cb7705b5a4880089c90c0381 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 18:10:15 -0700 Subject: [PATCH 376/630] Prep for 0.6.1 release --- CHANGES.md | 5 +++++ README.md | 11 ++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b048b9b0..b36ba75d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes in 0.6.1 + +* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. +* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129). + Changes in 0.6.0 * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). diff --git a/README.md b/README.md index db020c46..a84361ef 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.0 +Latest stable release: 0.6.1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.0 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.0"] +[org.clojure/java.jdbc "0.6.1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.0 + 0.6.1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,11 @@ Developer Information Change Log ==================== +* Release 0.6.1 on 2016-05-12 -- **IMPORTANT BUG FIX!** + * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. + * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129). + + * Release 0.6.0 on 2016-05-07 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). 0.6.0 / 2016-05-11. * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. 0.6.0 / 2016-05-11. From 725fd74a818df24f22ada0f3e231cbe023b70169 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 18:13:20 -0700 Subject: [PATCH 377/630] Correct 0.6.0 release date --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a84361ef..8e78e622 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ Change Log * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129). -* Release 0.6.0 on 2016-05-07 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** +* Release 0.6.0 on 2016-05-11 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). 0.6.0 / 2016-05-11. * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. 0.6.0 / 2016-05-11. * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. From e1c3ce1a6b582467aee42d4b73ae0e63169091c8 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 12 May 2016 20:38:37 -0500 Subject: [PATCH 378/630] [maven-release-plugin] prepare release java.jdbc-0.6.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7a8d1434..ea18b251 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.1-SNAPSHOT + 0.6.1 ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.1 From 7e2607ab55a01e78e798321e3a2ffef3b113313b Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 12 May 2016 20:38:38 -0500 Subject: [PATCH 379/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ea18b251..87599953 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 java.jdbc - 0.6.1 + 0.6.2-SNAPSHOT ${project.artifactId} @@ -23,7 +23,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.1 + HEAD From 597650ef1e45b46b49144f87576c46d2b85982cf Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 12 May 2016 18:50:19 -0700 Subject: [PATCH 380/630] Update local testing versions --- project.clj | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/project.clj b/project.clj index 4c488b96..dbbcda33 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.0" +(defproject org.clojure/java.jdbc "0.6.2-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" @@ -17,13 +17,14 @@ ;; appropriate for you. Again, note that this project.clj ;; file exists for convenience -- the pom.xml file is the ;; "system of record" as far as dependencies go! - [org.apache.derby/derby "10.11.1.1"] + [org.apache.derby/derby "10.12.1.1"] [org.hsqldb/hsqldb "2.3.3"] - [com.h2database/h2 "1.4.188"] + [com.h2database/h2 "1.4.191"] [net.sourceforge.jtds/jtds "1.3.1"] - [mysql/mysql-connector-java "5.1.36"] - [org.postgresql/postgresql "9.4-1201-jdbc41"] - [org.xerial/sqlite-jdbc "3.8.11.1"] + ;; Tests fail with 6.0.2 driver: + [mysql/mysql-connector-java "5.1.39"] + [org.postgresql/postgresql "9.4.1208.jre7"] + [org.xerial/sqlite-jdbc "3.8.11.2"] ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"] ] From 94bc439cb926d7f3d7ace4f86eac5cc5733b382a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 May 2016 13:35:41 -0700 Subject: [PATCH 381/630] Add first cut of clojure.spec instrumentation Conditionally instruments all namespaces under Clojure 1.9.0 when running tests. Not all functions have a spec yet. --- project.clj | 3 +- src/main/clojure/clojure/java/jdbc/spec.clj | 169 ++++++++++++++++++++ src/test/clojure/clojure/java/test_jdbc.clj | 6 + 3 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 src/main/clojure/clojure/java/jdbc/spec.clj diff --git a/project.clj b/project.clj index dbbcda33..f564b9a2 100644 --- a/project.clj +++ b/project.clj @@ -11,7 +11,7 @@ :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :dependencies [[org.clojure/clojure "1.7.0"] + :dependencies [[org.clojure/clojure "1.9.0-alpha3"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj @@ -34,6 +34,7 @@ :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} + :dev {:dependencies [[org.clojure/test.check "0.9.0"]]} } :aliases {"test-all" ["with-profile" "test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:test,1.9" "test"] "check-all" ["with-profile" "1.4:1.5:1.6:1.7:1.8:1.9" "check"]} diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj new file mode 100644 index 00000000..05e45b7b --- /dev/null +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -0,0 +1,169 @@ +;; Copyright (c) 2016 Sean Corfield. All rights reserved. +;; The use and distribution terms for this software are covered by +;; the Eclipse Public License 1.0 +;; (http://opensource.org/licenses/eclipse-1.0.php) which can be +;; found in the file epl-v10.html at the root of this distribution. +;; By using this software in any fashion, you are agreeing to be +;; bound by the terms of this license. You must not remove this +;; notice, or any other, from this software. +;; +;; jdbc/spec.clj +;; +;; Optional specifications for clojure.java.jdbc + +(ns ^{:author "Sean Corfield" + :doc "Optional specifications for use with Clojure 1.9 or later."} + clojure.java.jdbc.spec + (:require [clojure.spec :as s] + [clojure.java.jdbc :refer :all])) + +;; basic java.sql types + +(s/def ::connection #(instance? java.sql.Connection %)) +(s/def ::prepared-statement #(instance? java.sql.PreparedStatement %)) + +;; database specification (connection description) + +(s/def ::db-spec-connection (s/keys :req-un [::connection])) +(s/def ::db-spec-factory (s/keys :req-un [::factory])) +(s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname] :opt-un [::classname])) +(s/def ::db-spec-driver-manager-alt (s/keys :req-un [::dbtype ::dbname] :opt-un [::host ::port])) +(s/def ::db-spec-data-source (s/keys :req-un [::datasource] :opt-un [::username ::user ::password])) +(s/def ::db-spec-jndi (s/keys :req-un [::name] :opt-un [::environment])) +(s/def ::db-spec-raw (s/keys :req-un [::connection-uri])) +(s/def ::db-spec-string string?) +(s/def ::db-spec (s/or :connection ::db-spec-connection + :factory ::db-spec-factory + :driver-mgr ::db-spec-driver-manager + :friendly ::db-spec-driver-manager-alt + :datasource ::db-spec-data-source + :jndi ::db-spec-jndi + :raw ::db-spec-raw + :uri ::db-spec-string)) + +;; naming + +(s/def ::entity string?) + +(s/def ::identifier (s/or :kw keyword? :str string?)) + +;; SQL and parameters + +(s/def ::sql-stmt (s/or :sql string? :stmt ::prepared-statement)) + +(s/def ::sql-value ::s/any) ;; for now + +(s/def ::sql-params (s/or :sql ::sql-stmt + :sql-params (s/cat :sql ::sql-stmt :params (s/* ::sql-value)))) + +(s/def ::where-clause (s/cat :where string? :params (s/* ::sql-value))) + +;; results + +(s/def ::execute-result (s/* integer?)) + +;; various types of options + +(s/def ::create-options (s/keys :req-un [] :opt-un [::table-spec ::entities])) + +(s/def ::exec-sql-options (s/keys :req-un [] :opt-un [::entities ::transaction?])) + +(s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?])) + +(s/def ::find-by-keys-options (s/keys :req-un [] :opt-un [::entities ::order-by ::result-set-fn ::row-fn ::identifiers ::as-arrays?])) + +(s/def ::prepare-options (s/keys :req-un [] :opt-un [::return-keys ::result-type ::concurrency ::cursors ::fetch-size ::max-rows ::timeout])) + +(s/def ::query-options (s/keys :req-un [] :opt-un [::result-set-fn ::row-fn ::identifiers ::as-arrays?])) + +;; the function API + +;; as-sql-name + +;; quoted + +(s/fdef get-connection + :args (s/cat :db-spec ::db-spec) + :ret ::connection) + +;; result-set-seq + +(s/fdef prepare-statement + :args (s/cat :con ::connection + :sql string? + :opts (s/? ::prepare-options)) + :ret ::prepared-statement) + +(s/fdef db-find-connection + :args (s/cat :db-spec ::db-spec) + :ret (s/nilable ::connection)) + +(s/fdef db-connection + :args (s/cat :db-spec ::db-spec) + :ret ::connection) + +;; transaction functions + +;; metadata-result + +;; db-do-commands + +;; db-do-prepared-return-keys + +;; db-do-prepared + +;; db-query-with-resultset + +(s/fdef query + :args (s/cat :db ::db-spec + :sql-params ::sql-params + :opts (s/? ::query-options)) + ;; because result-set-fn can return anything: + :ret ::s/any) + +(s/fdef find-by-keys + :args (s/cat :db ::db-spec + :table ::identifier + :columns (s/map-of ::identifier ::sql-value) + :opts (s/? ::find-by-keys-options)) + :ret ::s/any) + +;; get-by-id + +(s/fdef execute! + :args (s/cat :db ::db-spec + :sql-params ::sql-params + :opts (s/? ::execute-options)) + :ret ::execute-result) + +(s/fdef delete! + :args (s/cat :db ::db-spec + :table ::identifier + :where-clause (s/spec ::where-clause) + :opts (s/? ::exec-sql-options)) + :ret ::execute-result) + +;; insert! + +;; insert-multi! + +(s/fdef update! + :args (s/cat :db ::db-spec + :table ::identifier + :set-map (s/map-of ::identifier ::sql-value) + :where-clause (s/spec ::where-clause) + :opts (s/? ::exec-sql-options)) + :ret ::execute-result) + +(s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword? :str string?)))) + +(s/fdef create-table-ddl + :args (s/cat :table ::identifier + :specs (s/coll-of ::column-spec ()) + :opts (s/? ::create-options)) + :ret string?) + +(s/fdef drop-table-ddl + :args (s/cat :table ::identifier + :opts (s/? (s/keys :req-un [] :opt-un [::entities]))) + :ret string?) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 75926399..8302450d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -24,6 +24,12 @@ (:use clojure.test) (:require [clojure.java.jdbc :as sql])) +(try + (require 'clojure.java.jdbc.spec) + ((resolve 'clojure.spec/instrument-ns) 'clojure.java.jdbc) + (println "Instrumenting clojure.java.jdbc with clojure.spec") + (catch Exception _)) + ;; Set test-databases according to whether you have the local database available: ;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] ;; Apache Derby and HSQLDB can run without an external setup. From b224a3e86df8c00a33a16122e6fcc531c5f71e2e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 30 May 2016 19:47:40 -0700 Subject: [PATCH 382/630] Suppress compile phase; update driver dependencies --- pom.xml | 43 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 87599953..5406601a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 java.jdbc @@ -25,17 +26,49 @@ git@github.com:clojure/java.jdbc.git HEAD + + + + + + com.theoryinpractise + clojure-maven-plugin + 1.3.13 + true + + ${clojure.warnOnReflection} + true + + + + clojure-compile + none + + + clojure-test + test + + test + + + + + + + mysql mysql-connector-java - 5.1.36 + 5.1.39 test org.apache.derby derby - 10.8.1.2 + 10.12.1.1 test @@ -47,19 +80,19 @@ com.h2database h2 - 1.4.188 + 1.4.191 test org.postgresql postgresql - 9.4-1201-jdbc41 + 9.4.1208.jre7 test org.xerial sqlite-jdbc - 3.8.11.1 + 3.8.11.2 test From c46688d1dcffb352f848ba5f46358f7b6ec874bc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 1 Jun 2016 10:37:38 -0700 Subject: [PATCH 383/630] Fix JDBC-132 by providing better argument checking --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++-- .../clojure/clojure/java/test_utilities.clj | 25 ++++++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e26b9dc9..42455c3c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1156,8 +1156,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } entities (:entities opts identity) table-spec-str (or (and table-spec (str " " table-spec)) "") spec-to-string (fn [spec] - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))))] + (try + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))) + (catch Exception _ + (throw (IllegalArgumentException. + "column spec is not a sequence of keywords / strings")))))] (format "CREATE TABLE %s (%s)%s" (as-sql-name entities table) (str/join ", " (map spec-to-string specs)) diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index b4a0d557..a534e477 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -1,4 +1,5 @@ -;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and +;; Copyright (c) 2008-2016 Sean Corfield, Stephen C. Gilardi. +;; All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By @@ -64,3 +65,25 @@ (sql/create-table-ddl :thing [[:col1 "int"] ["col2" :int]] {:table-spec "ENGINE=MyISAM" :entities clojure.string/upper-case})))) + +;; since we have clojure.spec instrumentation enabled for Clojure 1.9.0 +;; we need to account for the fact that we'll get different exceptions +;; for Clojure < 1.9.0 since the spec will trigger first and obscure +;; our own argument checking on 1.9.0+ + +(defn argument-exception? + "Given a thunk, try to execute it and return true if it throws + either an IllegalArgumentException or a Clojure exception from + clojure.spec." + [thunk] + (try + (thunk) + false + (catch IllegalArgumentException _ true) + (catch clojure.lang.ExceptionInfo e + (re-find #"did not conform to spec" (.getMessage e))))) + +(deftest test-invalid-create-table-ddl + (is (argument-exception? (fn [] (sql/create-table-ddl :thing [[]])))) + (is (argument-exception? (fn [] (sql/create-table-ddl :thing [[:col1 "int"] []])))) + (is (argument-exception? (fn [] (sql/create-table-ddl :thing [:col1 "int"]))))) From c8e75cce0837a0bd652e6f12b2a1d51fa82b1981 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 1 Jun 2016 10:48:05 -0700 Subject: [PATCH 384/630] Fix JDBC-131 by ignoring clean up exceptions If the clean up fails after a transaction is complete (regardless of whether the transaction succeeded or failed), ignore those failures and continue with remaining cleanup. The downside of this is that a connection may silently get into an unexpected state if we can't clean it up (but the most likely cause is that the connection itself became corrupt or was closed so it is almost certainly unusable anyway and the next operation will probably fail too!). --- src/main/clojure/clojure/java/jdbc.clj | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 42455c3c..6db7e5da 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -620,11 +620,21 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (throw t)) (finally (db-unset-rollback-only! nested-db) - (.setAutoCommit con auto-commit) + ;; the following can throw SQLExceptions but we do not + ;; want those to replace any exception currently being + ;; handled -- and if the connection got closed, we just + ;; want to ignore exceptions here anyway + (try + (.setAutoCommit con auto-commit) + (catch Exception _)) (when isolation - (.setTransactionIsolation con old-isolation)) + (try + (.setTransactionIsolation con old-isolation) + (catch Exception _))) (when read-only? - (.setReadOnly con old-readonly)))))) + (try + (.setReadOnly con old-readonly) + (catch Exception _))))))) (with-open [con (get-connection db)] (db-transaction* (add-connection db con) func opts))) (do From 96850554e51a358df13c11a8b2056051df9cae44 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 3 Jun 2016 10:17:04 -0700 Subject: [PATCH 385/630] Clarify create-table-ddl docstring --- src/main/clojure/clojure/java/jdbc.clj | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6db7e5da..ed12057a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1156,8 +1156,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } {:transaction? transaction?}))) (defn create-table-ddl - "Given a table name and a vector of column specs return the DDL string for - creating that table. An options map may be provided that can contain: + "Given a table name and a vector of column specs, return the DDL string for + creating that table. Each column spec is, in turn, a vector of keywords or + strings that is converted to strings and concatenated with spaces to form + a single column description in DDL, e.g., + [:cost :int \"not null\"] + [:name \"varchar(32)\"] + The first element of a column spec is treated as a SQL entity (so if you + provide the :entities option, that will be used to transform it). The + remaining elements are left as-is when converting them to strings. + An options map may be provided that can contain: :table-spec -- a string that is appended to the DDL -- and/or :entities -- a function to specify how column names are transformed." ([table specs] (create-table-ddl table specs {})) From 6934d169cc2b4140138ccad8018c858e5c51ba8e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 14 Jun 2016 20:07:33 -0700 Subject: [PATCH 386/630] Fix JDBC-133 by adding :qualifier option --- CHANGES.md | 4 +++ src/main/clojure/clojure/java/jdbc.clj | 35 ++++++++++++--------- src/test/clojure/clojure/java/test_jdbc.clj | 10 ++++-- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b36ba75d..41d57ecb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.6.2 + +* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). + Changes in 0.6.1 * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ed12057a..6178a6e0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -387,9 +387,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } unless the :as-arrays? option is :cols-as-is, in which case the column names are untouched (the result set maintains column name/value order). The :identifiers option specifies how SQL column names are converted to Clojure - keywords. The default is to convert them to lower case." + keywords. The default is to convert them to lower case. + The :qualifier option specifies the namespace qualifier for those identifiers." ([rs] (result-set-seq rs {})) - ([^ResultSet rs {:keys [identifiers as-arrays?] + ([^ResultSet rs {:keys [as-arrays? identifiers qualifier] :or {identifiers str/lower-case}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) @@ -397,7 +398,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) col-name-fn - (map (comp keyword identifiers))) + (map (comp (partial keyword qualifier) identifiers))) row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As @@ -684,11 +685,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, else return it as-is. This makes working with metadata easier. - Also accepts an option map containing :identifiers, :as-arrays?, :row-fn, - and :result-set-fn to control how the ResultSet is transformed and returned. - See query for more details." + Also accepts an option map containing :identifiers, :qualifier, :as-arrays?, + :row-fn,and :result-set-fn to control how the ResultSet is transformed and + returned. See query for more details." ([rs-or-value] (metadata-result rs-or-value {})) - ([rs-or-value {:keys [identifiers as-arrays? row-fn result-set-fn] + ([rs-or-value {:keys [as-arrays? identifiers qualifier result-set-fn row-fn] :or {identifiers str/lower-case row-fn identity}}] (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] (if (instance? java.sql.ResultSet rs-or-value) @@ -697,7 +698,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (cons (first rs) (map row-fn (rest rs))) (map row-fn rs)))) - (result-set-seq rs-or-value {:identifiers identifiers :as-arrays? as-arrays?})) + (result-set-seq rs-or-value {:as-arrays? as-arrays? + :identifiers identifiers + :qualifier qualifier})) rs-or-value)))) (defmacro metadata-query @@ -865,19 +868,21 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "Given a database connection and a vector containing SQL and optional parameters, perform a simple database query. The options specify how to construct the result set (and are also passed to prepare-statement as needed): + :as-arrays? - return the results as a set of arrays, default false. + :identifiers - applied to each column name in the result set, default lower-case + :qualifier - optionally provides the namespace qualifier for identifiers :result-set-fn - applied to the entire result set, default doall / vec if :as-arrays? true, :result-set-fn will default to vec if :as-arrays? false, :result-set-fn will default to doall :row-fn - applied to each row as the result set is constructed, default identity - :identifiers - applied to each column name in the result set, default lower-case - :as-arrays? - return the results as a set of arrays, default false. The second argument is a vector containing a SQL string or PreparedStatement, followed by any parameters it needs. See also prepare-statement for additional options." ([db sql-params] (query db sql-params {})) - ([db sql-params {:keys [result-set-fn row-fn identifiers as-arrays?] - :or {row-fn identity - identifiers str/lower-case} + ([db sql-params {:keys [as-arrays? identifiers qualifier + result-set-fn row-fn] + :or {identifiers str/lower-case + row-fn identity} :as opts}] (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] @@ -888,7 +893,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (cons (first rs) (map row-fn (rest rs))) (map row-fn rs)))) - (result-set-seq rset {:identifiers identifiers :as-arrays? as-arrays?}))) + (result-set-seq rset {:as-arrays? as-arrays? + :identifiers identifiers + :qualifier qualifier}))) opts)))) (defn- direction diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 8302450d..232ad186 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -21,8 +21,9 @@ ;; Migrated from clojure.contrib.test-sql 17 April 2011 (ns clojure.java.test-jdbc - (:use clojure.test) - (:require [clojure.java.jdbc :as sql])) + (:require [clojure.test :refer :all] + [clojure.java.jdbc :as sql] + [clojure.string :as str])) (try (require 'clojure.java.jdbc.spec) @@ -806,6 +807,11 @@ (sql/query db "SELECT * FROM fruit"))) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (sql/query db ["SELECT * FROM fruit"]))) + (is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}] + (sql/query db ["SELECT * FROM fruit"] {:identifiers str/upper-case}))) + (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil + :fruit/grade nil :fruit/cost nil}] + (sql/query db ["SELECT * FROM fruit"] {:qualifier "fruit"}))) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (with-open [con (sql/get-connection db)] (sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")])))) From 1c4263f6c0f1376914918c2acf28f0cd25fc566f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 17 Jun 2016 14:03:48 -0700 Subject: [PATCH 387/630] Housekeeping: bump lein default to 1.9.0 Alpha 7 --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index f564b9a2..364b85bf 100644 --- a/project.clj +++ b/project.clj @@ -11,7 +11,7 @@ :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :dependencies [[org.clojure/clojure "1.9.0-alpha3"] + :dependencies [[org.clojure/clojure "1.9.0-alpha7"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj From c4b49957556120665afaef43763cf1ec33abe73b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 22 Jun 2016 19:59:36 -0700 Subject: [PATCH 388/630] Fix JDBC-134 by supporting identifiers/qualifier on inserts --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 36 ++++++++++++--------- src/test/clojure/clojure/java/test_jdbc.clj | 24 ++++++++++++++ 3 files changed, 45 insertions(+), 16 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 41d57ecb..dc9ca75f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.6.2 +* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). Changes in 0.6.1 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6178a6e0..d710033e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -739,14 +739,14 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- db-do-execute-prepared-return-keys "Executes a PreparedStatement, optionally in a transaction, and (attempts to) return any generated keys." - [db ^PreparedStatement stmt param-group transaction?] + [db ^PreparedStatement stmt param-group {:keys [transaction?] :as opts}] ((or (:set-parameters db) set-parameters) stmt param-group) (let [exec-and-return-keys (^{:once true} fn* [] (let [counts (.executeUpdate stmt)] (try (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs))] + result (first (result-set-seq rs opts))] ;; sqlite (and maybe others?) requires ;; record set to be closed (.close rs) @@ -782,15 +782,15 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (if-let [con (db-find-connection db)] (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (if (instance? PreparedStatement sql) - (db-do-execute-prepared-return-keys db sql params transaction?) + (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] - (db-do-execute-prepared-return-keys db stmt params transaction?)))) + (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) (with-open [con (get-connection db)] (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))) (defn- db-do-execute-prepared-statement "Execute a PreparedStatement, optionally in a transaction." - [db ^PreparedStatement stmt param-groups transaction?] + [db ^PreparedStatement stmt param-groups {:keys [transaction?]}] (if (empty? param-groups) (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] @@ -822,9 +822,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) params (if (or (:multi? opts) (empty? params)) params [params])] (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql params transaction?) + (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (db-do-execute-prepared-statement db stmt params transaction?)))) + (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) (with-open [con (get-connection db)] (db-do-prepared (add-connection db con) transaction? sql-params opts))))) @@ -1009,16 +1009,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "Given a (connected) database connection and some SQL statements (for multiple inserts), run a prepared statement on each and return any generated keys. Note: we are eager so an unrealized lazy-seq cannot escape from the connection." - [db stmts] - (doall (map (fn [row] (db-do-prepared-return-keys db false row {})) stmts))) + [db stmts opts] + (doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts))) (defn- insert-helper "Given a (connected) database connection, a transaction flag and some SQL statements (for one or more inserts), run a prepared statement or a sequence of them." - [db transaction? stmts] + [db transaction? stmts opts] (if transaction? - (with-db-transaction [t-db db] (multi-insert-helper t-db stmts)) - (multi-insert-helper db stmts))) + (with-db-transaction [t-db db] (multi-insert-helper t-db stmts opts)) + (multi-insert-helper db stmts opts))) (defn- col-str "Transform a column spec to an entity name for SQL. The column spec may be a @@ -1064,16 +1064,20 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- insert-rows! "Given a database connection, a table name, a sequence of rows, and an options map, insert the rows into the database." - [db table rows {:keys [entities transaction?] - :or {entities identity transaction? true}}] + [db table rows {:keys [entities identifiers qualifier transaction?] + :or {entities identity + identifiers str/lower-case + transaction? true}}] (let [sql-params (map (fn [row] (when-not (map? row) (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) (insert-single-row-sql table row entities)) rows)] (if-let [con (db-find-connection db)] - (insert-helper db transaction? sql-params) + (insert-helper db transaction? sql-params + {:identifiers identifiers :qualifier qualifier}) (with-open [con (get-connection db)] - (insert-helper (add-connection db con) transaction? sql-params))))) + (insert-helper (add-connection db con) transaction? sql-params + {:identifiers identifiers :qualifier qualifier}))))) (defn- insert-cols! "Given a database connection, a table name, a sequence of columns names, a diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 232ad186..4d1d7627 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -827,6 +827,30 @@ (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) +(deftest insert-identifiers-respected-1 + (doseq [db (filter postgres? (test-specs))] + (create-test-table :fruit db) + (let [inserted (sql/insert! db + :fruit + {:name "Apple"} + {:identifiers clojure.string/upper-case + :qualifier "foo"}) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] + {:identifiers clojure.string/upper-case + :qualifier "foo"})] + (is (= rows inserted))))) + +(deftest insert-identifiers-respected-2 + (doseq [db (filter postgres? (test-specs))] + (create-test-table :fruit db) + (let [inserted (sql/insert-multi! db + :fruit + [{:name "Apple"} {:name "Pear"}] + {:identifiers clojure.string/upper-case}) + rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] + {:identifiers clojure.string/upper-case})] + (is (= rows inserted))))) + (deftest insert-two-by-map-and-query-as-arrays (doseq [db (test-specs)] (create-test-table :fruit db) From ab12a9dd77611700924aae67b99e2b8d7185ced0 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Jun 2016 18:10:35 -0700 Subject: [PATCH 389/630] Update for Clojure 1.9 Alpha 8 Signature of coll-of, location of instrument(-ns). --- project.clj | 4 ++-- src/main/clojure/clojure/java/jdbc/spec.clj | 2 +- src/test/clojure/clojure/java/test_jdbc.clj | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/project.clj b/project.clj index 364b85bf..f494555f 100644 --- a/project.clj +++ b/project.clj @@ -10,8 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :dependencies [[org.clojure/clojure "1.9.0-alpha7"] + :dependencies [[org.clojure/clojure "1.9.0-alpha8"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj @@ -36,6 +35,7 @@ :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} :dev {:dependencies [[org.clojure/test.check "0.9.0"]]} } + :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} :aliases {"test-all" ["with-profile" "test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:test,1.9" "test"] "check-all" ["with-profile" "1.4:1.5:1.6:1.7:1.8:1.9" "check"]} :min-lein-version "2.0.0") diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 05e45b7b..94cb6b26 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -159,7 +159,7 @@ (s/fdef create-table-ddl :args (s/cat :table ::identifier - :specs (s/coll-of ::column-spec ()) + :specs (s/coll-of ::column-spec) :opts (s/? ::create-options)) :ret string?) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 4d1d7627..bab19153 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -27,7 +27,8 @@ (try (require 'clojure.java.jdbc.spec) - ((resolve 'clojure.spec/instrument-ns) 'clojure.java.jdbc) + (require 'clojure.spec.test) + ((resolve 'clojure.spec.test/instrument) 'clojure.java.jdbc) (println "Instrumenting clojure.java.jdbc with clojure.spec") (catch Exception _)) From 87d68da13bef61c78e25682da228d99eb50571ee Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 28 Jun 2016 18:13:29 -0700 Subject: [PATCH 390/630] Note experimental spec support coming in 0.6.2 --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index dc9ca75f..1b4cbc0e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.6.2 +* Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). From b556b82909d6425a62c530d0e6b3cb6ad9a1e615 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 2 Jul 2016 19:43:42 -0700 Subject: [PATCH 391/630] Fix JDBC-136 by using db-spec as default for opts --- CHANGES.md | 7 +- src/main/clojure/clojure/java/jdbc.clj | 203 +++++++++++--------- src/test/clojure/clojure/java/test_jdbc.clj | 5 + 3 files changed, 117 insertions(+), 98 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1b4cbc0e..5742f943 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.6.2 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). +* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). @@ -43,7 +44,7 @@ Changes in 0.6.0-alpha1 - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed - The `java.jdbc.deprecated` namespace has been removed - + Changes in 0.5.8 * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. @@ -279,7 +280,7 @@ Changes in 0.1.2: Changes in 0.1.1: -* Fix JDBC-21 by adding support for db-spec as URI (Phil Hagelberg). +* Fix JDBC-21 by adding support for db-spec as URI (Phil Hagelberg). * Fix JDBC-22 by deducing driver class name from subprotocol (Phil Hagelberg). * Add Postgres dependency so tests can be automcated (Phil Hagelberg). * Add ability to specify test databases via TEST_DBS environment variable (Phil Hagelberg). @@ -319,7 +320,7 @@ Changes in 0.0.5: * Add support for databases that cannot return generated keys (e.g., HSQLDB) - insert operations silently return the insert counts instead of generated keys - it is the user's responsibility to handle this if you're using such a database! - + Changes in 0.0.4: * Fix JDBC-2 by allowing :table-spec {string} at the end of create-table arguments: diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index d710033e..5a4e0a4c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -597,55 +597,57 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } substitute another isolation level. The read-only? option puts the transaction in readonly mode (if supported)." ([db func] (db-transaction* db func {})) - ([db func {:keys [isolation read-only?] :as opts}] - (if (zero? (get-level db)) - (if-let [con (db-find-connection db)] - (let [nested-db (inc-level db) - auto-commit (.getAutoCommit con) - old-isolation (.getTransactionIsolation con) - old-readonly (.isReadOnly con)] - (io! - (when isolation - (.setTransactionIsolation con (isolation isolation-levels))) - (when read-only? - (.setReadOnly con true)) - (.setAutoCommit con false) - (try - (let [result (func nested-db)] - (if (db-is-rollback-only nested-db) + ([db func opts] + (let [{:keys [isolation read-only?] :as opts} + (merge (when (map? db) db) opts)] + (if (zero? (get-level db)) + (if-let [con (db-find-connection db)] + (let [nested-db (inc-level db) + auto-commit (.getAutoCommit con) + old-isolation (.getTransactionIsolation con) + old-readonly (.isReadOnly con)] + (io! + (when isolation + (.setTransactionIsolation con (isolation isolation-levels))) + (when read-only? + (.setReadOnly con true)) + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-is-rollback-only nested-db) + (.rollback con) + (.commit con)) + result) + (catch Throwable t (.rollback con) - (.commit con)) - result) - (catch Throwable t - (.rollback con) - (throw t)) - (finally - (db-unset-rollback-only! nested-db) - ;; the following can throw SQLExceptions but we do not - ;; want those to replace any exception currently being - ;; handled -- and if the connection got closed, we just - ;; want to ignore exceptions here anyway - (try - (.setAutoCommit con auto-commit) - (catch Exception _)) - (when isolation - (try - (.setTransactionIsolation con old-isolation) - (catch Exception _))) - (when read-only? + (throw t)) + (finally + (db-unset-rollback-only! nested-db) + ;; the following can throw SQLExceptions but we do not + ;; want those to replace any exception currently being + ;; handled -- and if the connection got closed, we just + ;; want to ignore exceptions here anyway (try - (.setReadOnly con old-readonly) - (catch Exception _))))))) - (with-open [con (get-connection db)] - (db-transaction* (add-connection db con) func opts))) - (do - (when (and isolation - (let [con (db-find-connection db)] - (not= (isolation isolation-levels) - (.getTransactionIsolation con)))) - (let [msg "Nested transactions may not have different isolation levels"] - (throw (IllegalStateException. msg)))) - (func (inc-level db)))))) + (.setAutoCommit con auto-commit) + (catch Exception _)) + (when isolation + (try + (.setTransactionIsolation con old-isolation) + (catch Exception _))) + (when read-only? + (try + (.setReadOnly con old-readonly) + (catch Exception _))))))) + (with-open [con (get-connection db)] + (db-transaction* (add-connection db con) func opts))) + (do + (when (and isolation + (let [con (db-find-connection db)] + (not= (isolation isolation-levels) + (.getTransactionIsolation con)))) + (let [msg "Nested transactions may not have different isolation levels"] + (throw (IllegalStateException. msg)))) + (func (inc-level db))))))) (defmacro with-db-transaction "Evaluates body in the context of a transaction on the specified database connection. @@ -779,14 +781,15 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (db-do-prepared-return-keys db true transaction? sql-params) (db-do-prepared-return-keys db transaction? sql-params {}))) ([db transaction? sql-params opts] - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] - (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))) + (let [opts (merge (when (map? db) db) opts)] + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) + (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] + (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) + (with-open [con (get-connection db)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) (defn- db-do-execute-prepared-statement "Execute a PreparedStatement, optionally in a transaction." @@ -818,15 +821,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (db-do-prepared db true transaction? sql-params) (db-do-prepared db transaction? sql-params {}))) ([db transaction? sql-params opts] - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - params (if (or (:multi? opts) (empty? params)) params [params])] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db)] - (db-do-prepared (add-connection db con) transaction? sql-params opts))))) + (let [opts (merge (when (map? db) db) opts)] + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + params (if (or (:multi? opts) (empty? params)) params [params])] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) + (with-open [con (get-connection db)] + (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) (defn db-query-with-resultset "Executes a query, then evaluates func passing in the raw ResultSet as an @@ -838,7 +842,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } Uses executeQuery. This may affect what SQL you can run via query." ([db sql-params func] (db-query-with-resultset db sql-params func {})) ([db sql-params func opts] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + (let [opts (merge (when (map? db) db) opts) + [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] ((or (:set-parameters db) set-parameters) stmt params) (with-open [rset (.executeQuery stmt)] @@ -879,12 +884,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } by any parameters it needs. See also prepare-statement for additional options." ([db sql-params] (query db sql-params {})) - ([db sql-params {:keys [as-arrays? identifiers qualifier - result-set-fn row-fn] - :or {identifiers str/lower-case - row-fn identity} - :as opts}] - (let [result-set-fn (or result-set-fn (if as-arrays? vec doall)) + ([db sql-params opts] + (let [{:keys [as-arrays? identifiers qualifier result-set-fn row-fn] :as opts} + (merge {:identifiers str/lower-case :row-fn identity} + (when (map? db) db) + opts) + result-set-fn (or result-set-fn (if as-arrays? vec doall)) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (db-query-with-resultset db sql-params-vector (^{:once true} fn* [rset] @@ -929,8 +934,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } columns, e.g,. {:order-by [:name {:age :desc]}" ([db table columns] (find-by-keys db table columns {})) ([db table columns opts] - (let [entities (:entities opts identity) - order-by (:order-by opts) + (let [{:keys [entities order-by] :as opts} + (merge {:entities identity} + (when (map? db) db) + opts) ks (keys columns) vs (vals columns)] (query db (into [(str "SELECT * FROM " (table-str table entities) @@ -953,7 +960,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (get-by-id db table pk-value :id pk-name-or-opts) (get-by-id db table pk-value pk-name-or-opts {}))) ([db table pk-value pk-name opts] - (let [r-s-fn (or (:result-set-fn opts) identity)] + (let [opts (merge (when (map? db) db) opts) + r-s-fn (or (:result-set-fn opts) identity)] (find-by-keys db table {pk-name pk-value} (assoc opts :result-set-fn (comp first r-s-fn)))))) @@ -969,9 +977,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } If there are no parameters specified, executeUpdate will be used, otherwise executeBatch will be used. This may affect what SQL you can run via execute!" ([db sql-params] (execute! db sql-params {})) - ([db sql-params {:keys [transaction? multi?] - :or {transaction? true multi? false}}] - (let [execute-helper + ([db sql-params opts] + (let [{:keys [transaction? multi?]} + (merge {:transaction? true :multi? false} (when (map? db) db) opts) + execute-helper (^{:once true} fn* [db] (if multi? (db-do-prepared db transaction? sql-params {:multi? true}) @@ -999,11 +1008,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } is equivalent to: (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" ([db table where-clause] (delete! db table where-clause {})) - ([db table where-clause {:keys [entities transaction?] - :or {entities identity transaction? true}}] - (execute! db - (delete-sql table where-clause entities) - {:transaction? transaction?}))) + ([db table where-clause opts] + (let [{:keys [entities transaction?]} + (merge {:entities identity :transaction? true} (when (map? db) db) opts)] + (execute! db + (delete-sql table where-clause entities) + {:transaction? transaction?})))) (defn- multi-insert-helper "Given a (connected) database connection and some SQL statements (for multiple @@ -1064,11 +1074,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- insert-rows! "Given a database connection, a table name, a sequence of rows, and an options map, insert the rows into the database." - [db table rows {:keys [entities identifiers qualifier transaction?] - :or {entities identity - identifiers str/lower-case - transaction? true}}] - (let [sql-params (map (fn [row] + [db table rows opts] + (let [{:keys [entities identifiers qualifier transaction?]} + (merge {:entities identity :identifiers str/lower-case :transaction? true} + (when (map? db) db) + opts) + sql-params (map (fn [row] (when-not (map? row) (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) (insert-single-row-sql table row entities)) rows)] @@ -1083,9 +1094,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "Given a database connection, a table name, a sequence of columns names, a sequence of vectors of column values, one per row, and an options map, insert the rows into the database." - [db table cols values {:keys [entities transaction?] - :or {entities identity transaction? true}}] - (let [sql-params (insert-multi-row-sql table cols values entities)] + [db table cols values opts] + (let [{:keys [entities transaction?]} + (merge {:entities identity :transaction? true} (when (map? db) db) opts) + sql-params (insert-multi-row-sql table cols values entities)] (if-let [con (db-find-connection db)] (db-do-prepared db transaction? sql-params {:multi? true}) (with-open [con (get-connection db)] @@ -1160,11 +1172,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } is equivalent to: (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" ([db table set-map where-clause] (update! db table set-map where-clause {})) - ([db table set-map where-clause {:keys [entities transaction?] - :or {entities identity transaction? true}}] - (execute! db - (update-sql table set-map where-clause entities) - {:transaction? transaction?}))) + ([db table set-map where-clause opts] + (let [{:keys [entities transaction?]} + (merge {:entities identity :transaction? true} (when (map? db) db) opts)] + (execute! db + (update-sql table set-map where-clause entities) + {:transaction? transaction?})))) (defn create-table-ddl "Given a table name and a vector of column specs, return the DDL string for diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index bab19153..a62cda9c 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -810,9 +810,14 @@ (sql/query db ["SELECT * FROM fruit"]))) (is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}] (sql/query db ["SELECT * FROM fruit"] {:identifiers str/upper-case}))) + (is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}] + (sql/query (assoc db :identifiers str/upper-case) ["SELECT * FROM fruit"]))) (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil :fruit/grade nil :fruit/cost nil}] (sql/query db ["SELECT * FROM fruit"] {:qualifier "fruit"}))) + (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil + :fruit/grade nil :fruit/cost nil}] + (sql/query (assoc db :qualifier "fruit") ["SELECT * FROM fruit"]))) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (with-open [con (sql/get-connection db)] (sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")])))) From f9fe3dde5b4bc5f1a5b5a79ffb5374fad3377b0b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 3 Jul 2016 16:08:33 -0700 Subject: [PATCH 392/630] Fix JDBC-135 by adding basic EXPLAIN support --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 13 ++++++-- src/test/clojure/clojure/java/test_jdbc.clj | 37 +++++++++++++++++---- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 5742f943..b8fbf715 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,7 @@ Changes coming in 0.6.2 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). +* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://dev.clojure.org/jira/browse/JDBC-135). * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5a4e0a4c..84fc61b0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -885,12 +885,21 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } See also prepare-statement for additional options." ([db sql-params] (query db sql-params {})) ([db sql-params opts] - (let [{:keys [as-arrays? identifiers qualifier result-set-fn row-fn] :as opts} - (merge {:identifiers str/lower-case :row-fn identity} + (let [{:keys [as-arrays? explain? explain-fn identifiers qualifier + result-set-fn row-fn] :as opts} + (merge {:explain-fn println :identifiers str/lower-case :row-fn identity} (when (map? db) db) opts) result-set-fn (or result-set-fn (if as-arrays? vec doall)) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (when (and explain? (string? (first sql-params-vector))) + (query db (into [(str (if (string? explain?) explain? "EXPLAIN") + " " + (first sql-params-vector))] + (rest sql-params-vector)) + (-> opts + (dissoc :explain? :result-set-fn :row-fn) + (assoc :result-set-fn explain-fn)))) (db-query-with-resultset db sql-params-vector (^{:once true} fn* [rset] ((^{:once true} fn* [rs] diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index a62cda9c..38604f8a 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -126,6 +126,21 @@ ;; We start with all tables dropped and each test has to create the tables ;; necessary for it to do its job, and populate it as needed... +(defn- derby? [db] + (if (string? db) + (re-find #"derby:" db) + (= "derby" (or (:subprotocol db) (:dbtype db))))) + +(defn- hsqldb? [db] + (if (string? db) + (re-find #"hsqldb:" db) + (= "hsqldb" (or (:subprotocol db) (:dbtype db))))) + +(defn- mssql? [db] + (if (string? db) + (re-find #"sqlserver" db) + (re-find #"sqlserver" (or (:subprotocol db) (:dbtype db))))) + (defn- mysql? [db] (if (string? db) (re-find #"mysql:" db) @@ -263,9 +278,9 @@ (doseq [db (test-specs)] (sql/db-do-commands db [(sql/create-table-ddl :fruit3 - [[:name "VARCHAR(32)"] - [:appearance "VARCHAR(32)"] - [:cost :int]]) + [[:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int]]) "DROP TABLE fruit3"]) (is (thrown? java.sql.SQLException (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) @@ -274,9 +289,9 @@ (doseq [db (test-specs)] (sql/db-do-commands db true [(sql/create-table-ddl :fruit3 - [[:name "VARCHAR(32)"] - [:appearance "VARCHAR(32)"] - [:cost :int]]) + [[:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int]]) "DROP TABLE fruit3"]) (is (thrown? java.sql.SQLException (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count}))))) @@ -822,7 +837,15 @@ (with-open [con (sql/get-connection db)] (sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")])))) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] - (sql/query db ["SELECT * FROM fruit"] {:max-rows 1})))))) + (sql/query db ["SELECT * FROM fruit"] {:max-rows 1}))) + (cond (derby? db) nil + (hsqldb? db) (is (seq (with-out-str + (sql/query db ["SELECT * FROM fruit"] + {:explain? "EXPLAIN PLAN FOR"})))) + (mssql? db) nil + :else (is (seq (with-out-str + (sql/query db ["SELECT * FROM fruit"] + {:explain? true})))))))) (deftest insert-two-by-map-and-query (doseq [db (test-specs)] From 7eaa5c8aedb6632d817d92e09605c13f35b19e99 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 5 Jul 2016 17:08:27 -0700 Subject: [PATCH 393/630] Prep for 0.6.2-alpha1 --- CHANGES.md | 2 +- README.md | 13 ++++++++++--- project.clj | 2 +- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b8fbf715..7e02b61b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.6.2 +Changes in 0.6.2-alpha1 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). diff --git a/README.md b/README.md index 8e78e622..42edc413 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.1 +Latest stable release: 0.6.2-alpha1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.1"] +[org.clojure/java.jdbc "0.6.2-alpha1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.1 + 0.6.2-alpha1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,13 @@ Developer Information Change Log ==================== +* Release 0.6.2-alpha1 on 2016-07-05 + * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). + * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). + * `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://dev.clojure.org/jira/browse/JDBC-135). + * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). + * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). + * Release 0.6.1 on 2016-05-12 -- **IMPORTANT BUG FIX!** * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129). diff --git a/project.clj b/project.clj index f494555f..f64afdc4 100644 --- a/project.clj +++ b/project.clj @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-alpha8"] + :dependencies [[org.clojure/clojure "1.9.0-alpha9"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj From 820f4c9834cd8f49761b4fbc504405a8357ca47d Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 5 Jul 2016 20:53:44 -0500 Subject: [PATCH 394/630] [maven-release-plugin] prepare release java.jdbc-0.6.2-alpha1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5406601a..a507f002 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-SNAPSHOT + 0.6.2-alpha1 ${project.artifactId} @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.2-alpha1 From 2dd8131a0b7dabcac3dc73acfa8da44af921fd90 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 5 Jul 2016 20:53:45 -0500 Subject: [PATCH 395/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a507f002..5406601a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-alpha1 + 0.6.2-SNAPSHOT ${project.artifactId} @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.2-alpha1 + HEAD From 38971fcb1bed1e689de4e0e239ece66860d4ccbf Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 11 Jul 2016 10:28:50 -0700 Subject: [PATCH 396/630] Clojure 1.9.0 Alpha 10 "any" changes `clojure.spec/any` has been replaced by `clojure.core/any?`. --- project.clj | 2 +- src/main/clojure/clojure/java/jdbc/spec.clj | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/project.clj b/project.clj index f64afdc4..cac98765 100644 --- a/project.clj +++ b/project.clj @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-alpha9"] + :dependencies [[org.clojure/clojure "1.9.0-alpha10"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 94cb6b26..4b898af8 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -51,7 +51,7 @@ (s/def ::sql-stmt (s/or :sql string? :stmt ::prepared-statement)) -(s/def ::sql-value ::s/any) ;; for now +(s/def ::sql-value any?) ;; for now (s/def ::sql-params (s/or :sql ::sql-stmt :sql-params (s/cat :sql ::sql-stmt :params (s/* ::sql-value)))) @@ -119,14 +119,14 @@ :sql-params ::sql-params :opts (s/? ::query-options)) ;; because result-set-fn can return anything: - :ret ::s/any) + :ret any?) (s/fdef find-by-keys :args (s/cat :db ::db-spec :table ::identifier :columns (s/map-of ::identifier ::sql-value) :opts (s/? ::find-by-keys-options)) - :ret ::s/any) + :ret any?) ;; get-by-id From 11b7cbef6734e8ba75306394ff72d7b449472e94 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 21 Jul 2016 10:25:11 -0700 Subject: [PATCH 397/630] 0.6.2 Alpha 2 with updated clojure.spec support --- CHANGES.md | 4 ++++ README.md | 9 +++++--- src/main/clojure/clojure/java/jdbc/spec.clj | 24 ++++++++++----------- src/test/clojure/clojure/java/test_jdbc.clj | 8 +++++-- 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 7e02b61b..f6723d01 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.6.2-alpha2 + +* Updates to `clojure.spec` support to work properly with Clojure 1.9.0 Alpha 10. + Changes in 0.6.2-alpha1 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). diff --git a/README.md b/README.md index 42edc413..d472a904 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.2-alpha1 +Latest stable release: 0.6.2-alpha2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.2-alpha1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.2-alpha1"] +[org.clojure/java.jdbc "0.6.2-alpha2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.2-alpha1 + 0.6.2-alpha2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -104,6 +104,9 @@ Developer Information Change Log ==================== +* Release 0.6.2-alpha2 on 2016-07-21 + * Update `clojure.spec` support to work with Clojure 1.9.0 Alpha 10. + * Release 0.6.2-alpha1 on 2016-07-05 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 4b898af8..ce7e0cd9 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -15,7 +15,7 @@ :doc "Optional specifications for use with Clojure 1.9 or later."} clojure.java.jdbc.spec (:require [clojure.spec :as s] - [clojure.java.jdbc :refer :all])) + [clojure.java.jdbc :as sql])) ;; basic java.sql types @@ -82,23 +82,23 @@ ;; quoted -(s/fdef get-connection +(s/fdef sql/get-connection :args (s/cat :db-spec ::db-spec) :ret ::connection) ;; result-set-seq -(s/fdef prepare-statement +(s/fdef sql/prepare-statement :args (s/cat :con ::connection :sql string? :opts (s/? ::prepare-options)) :ret ::prepared-statement) -(s/fdef db-find-connection +(s/fdef sql/db-find-connection :args (s/cat :db-spec ::db-spec) :ret (s/nilable ::connection)) -(s/fdef db-connection +(s/fdef sql/db-connection :args (s/cat :db-spec ::db-spec) :ret ::connection) @@ -114,14 +114,14 @@ ;; db-query-with-resultset -(s/fdef query +(s/fdef sql/query :args (s/cat :db ::db-spec :sql-params ::sql-params :opts (s/? ::query-options)) ;; because result-set-fn can return anything: :ret any?) -(s/fdef find-by-keys +(s/fdef sql/find-by-keys :args (s/cat :db ::db-spec :table ::identifier :columns (s/map-of ::identifier ::sql-value) @@ -130,13 +130,13 @@ ;; get-by-id -(s/fdef execute! +(s/fdef sql/execute! :args (s/cat :db ::db-spec :sql-params ::sql-params :opts (s/? ::execute-options)) :ret ::execute-result) -(s/fdef delete! +(s/fdef sql/delete! :args (s/cat :db ::db-spec :table ::identifier :where-clause (s/spec ::where-clause) @@ -147,7 +147,7 @@ ;; insert-multi! -(s/fdef update! +(s/fdef sql/update! :args (s/cat :db ::db-spec :table ::identifier :set-map (s/map-of ::identifier ::sql-value) @@ -157,13 +157,13 @@ (s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword? :str string?)))) -(s/fdef create-table-ddl +(s/fdef sql/create-table-ddl :args (s/cat :table ::identifier :specs (s/coll-of ::column-spec) :opts (s/? ::create-options)) :ret string?) -(s/fdef drop-table-ddl +(s/fdef sql/drop-table-ddl :args (s/cat :table ::identifier :opts (s/? (s/keys :req-un [] :opt-un [::entities]))) :ret string?) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 38604f8a..cc44d558 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -28,7 +28,8 @@ (try (require 'clojure.java.jdbc.spec) (require 'clojure.spec.test) - ((resolve 'clojure.spec.test/instrument) 'clojure.java.jdbc) + (let [syms ((resolve 'clojure.spec.test/enumerate-namespace) 'clojure.java.jdbc)] + ((resolve 'clojure.spec.test/instrument) syms)) (println "Instrumenting clojure.java.jdbc with clojure.spec") (catch Exception _)) @@ -115,7 +116,7 @@ (doseq [table [:fruit :fruit2 :veggies :veggies2]] (try (sql/db-do-commands db (sql/drop-table-ddl table)) - (catch Exception _ + (catch java.sql.SQLException _ ;; ignore )))) (t)) @@ -196,6 +197,9 @@ [:grade :real]] {:table-spec ""}))) +(deftest test-drop-table-ddl + (is (= "DROP TABLE something" (sql/drop-table-ddl :something)))) + (deftest test-uri-spec-parsing (is (= {:advanced "false" :ssl "required" :password "clojure_test" :user "clojure_test" :subname "//localhost/clojure_test" From 7690250b8f9a06015d595391c2a4a869cdfb0626 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 21 Jul 2016 12:38:29 -0500 Subject: [PATCH 398/630] [maven-release-plugin] prepare release java.jdbc-0.6.2-alpha2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5406601a..28230a02 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-SNAPSHOT + 0.6.2-alpha2 ${project.artifactId} @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.2-alpha2 From 140e32c063c7faa5d758b0609bd88ad86012c611 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 21 Jul 2016 12:38:29 -0500 Subject: [PATCH 399/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 28230a02..5406601a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-alpha2 + 0.6.2-SNAPSHOT ${project.artifactId} @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.2-alpha2 + HEAD From 491db24efdda81dc196b5830c2e8a8550b66e49a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 15 Aug 2016 17:30:13 -0700 Subject: [PATCH 400/630] JDBC-138 improve dbtype / subprotocol aliasing --- CHANGES.md | 5 +++++ src/main/clojure/clojure/java/jdbc.clj | 13 ++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f6723d01..69035c40 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes coming in 0.6.2-alpha3 + +* Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138). + This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). + Changes in 0.6.2-alpha2 * Updates to `clojure.spec` support to work properly with Clojure 1.9.0 Alpha 10. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 84fc61b0..8ce89b00 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -155,7 +155,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "sqlite" "org.sqlite.JDBC"}) (def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols - {"postgres" "postgresql"}) + {"postgres" "postgresql" + "mssql" "sqlserver" + "jtds" "jtds:sqlserver" + "oracle" "oracle:thin" + "hsql" "hsqldb"}) (defn- parse-properties-uri [^URI uri] (let [host (.getHost uri) @@ -265,14 +269,17 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (DriverManager/getConnection connection-uri) (and subprotocol subname) - (let [url (format "jdbc:%s:%s" subprotocol subname) + (let [;; allow aliases for subprotocols + subprotocol (subprotocols subprotocol subprotocol) + url (format "jdbc:%s:%s" subprotocol subname) etc (dissoc db-spec :classname :subprotocol :subname) classname (or classname (classnames subprotocol))] (clojure.lang.RT/loadClassForName classname) (DriverManager/getConnection url (as-properties etc))) (and dbtype dbname) - (let [subprotocol dbtype + (let [;; alias aliases for dbtype + subprotocol (subprotocols dbtype dbtype) host (or host "127.0.0.1") port (or port (condp = subprotocol "mysql" 3306 From c64f716768ae003b306d4ecd0024422ec703de79 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 15 Aug 2016 17:46:43 -0700 Subject: [PATCH 401/630] JDBC-139 documentation update for :dbtype etc --- CHANGES.md | 1 + README.md | 20 ++++++++++-- src/main/clojure/clojure/java/jdbc.clj | 42 ++++++++++++++------------ 3 files changed, 41 insertions(+), 22 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 69035c40..fe0d6648 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.6.2-alpha3 +* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139). * Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138). This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). diff --git a/README.md b/README.md index d472a904..e0fc6f23 100644 --- a/README.md +++ b/README.md @@ -55,11 +55,27 @@ Example Usage ```clojure (require '[clojure.java.jdbc :as j]) -(def mysql-db {:subprotocol "mysql" - :subname "//127.0.0.1:3306/clojure_test" +;; there are many ways to write a db-spec but the easiest way is to +;; use :dbtype and then provide the :dbname and any of :user, :password, +;; :host, :port, and other options as needed: +(def mysql-db {:dbtype "mysql" + :dbname "clojure_test" :user "clojure_test" :password "clojure_test"}) +(def pg-db {:dbtype "postgresql" + :dbname "mypgdatabase" + :host "mydb.server.com" + :user "myuser" + :password "secret" + :ssl true + :sslfactory "org.postgresql.ssl.NonValidatingFactory"}) + +;; you can also specify a full connection string if you'd prefer: +(def pg-uri + {:connection-uri (str "postgresql://myuser:secret@mydb.server.com:5432/mypgdatabase" + "?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory")}) + (j/insert! mysql-db :fruit {:name "Apple" :appearance "rosy" :cost 24} {:name "Orange" :appearance "round" :cost 49}) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8ce89b00..40edbbf5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -199,28 +199,34 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } parameters but can also be a URI or a String. The various possibilities are described below: + DriverManager (preferred): + :dbtype (required) a String, the type of the database (the jdbc subprotocol) + :dbname (required) a String, the name of the database + :host (optional) a String, the host name/IP of the database + (defaults to 127.0.0.1) + :port (optional) a Long, the port of the database + (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) + (others) (optional) passed to the driver as properties. + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + + Other formats accepted: + Existing Connection: :connection (required) an existing open connection that can be used but cannot be closed (only the parent connection can be closed) - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DriverManager: + DriverManager (alternative / legacy style): :subprotocol (required) a String, the jdbc subprotocol :subname (required) a String, the jdbc subname :classname (optional) a String, the jdbc driver class name (others) (optional) passed to the driver as properties. - DriverManager (alternative): - :dbtype (required) a String, the type of the database (the jdbc subprotocol) - :dbname (required) a String, the name of the database - :host (optional) a String, the host name/IP of the database - (defaults to 127.0.0.1) - :port (optional) a Long, the port of the database - (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) - (others) (optional) passed to the driver as properties. + Factory: + :factory (required) a function of one argument, a map of params + (others) (optional) passed to the factory function in a map DataSource: :datasource (required) a javax.sql.DataSource @@ -233,14 +239,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } :name (required) a String or javax.naming.Name :environment (optional) a java.util.Map - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - - URI: - Parsed JDBC connection string - see below + java.net.URI: + Parsed JDBC connection string (see java.lang.String format next) - String: + java.lang.String: subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." ^java.sql.Connection From 5f48e1194181fcf636f7992d12893f49a92a57e0 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 25 Aug 2016 12:40:08 -0700 Subject: [PATCH 402/630] Fix JDBC-140 and release 0.6.2-alpha3 --- CHANGES.md | 3 ++- README.md | 12 +++++++++--- src/main/clojure/clojure/java/jdbc.clj | 5 ++++- src/test/clojure/clojure/java/test_jdbc.clj | 6 ++++++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index fe0d6648..8da1460f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ -Changes coming in 0.6.2-alpha3 +Changes in 0.6.2-alpha3 +* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140). * Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139). * Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138). This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). diff --git a/README.md b/README.md index e0fc6f23..1dfb5351 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.6.2-alpha2 +Latest stable release: 0.6.2-alpha3 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.6.2-alpha2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.6.2-alpha2"] +[org.clojure/java.jdbc "0.6.2-alpha3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.6.2-alpha2 + 0.6.2-alpha3 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -120,6 +120,12 @@ Developer Information Change Log ==================== +* Release 0.6.2-alpha3 on 2016-08-25 + * Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140). + * Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139). + * Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138). + This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). + * Release 0.6.2-alpha2 on 2016-07-21 * Update `clojure.spec` support to work with Clojure 1.9.0 Alpha 10. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 40edbbf5..8f2df325 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -404,10 +404,13 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) + identifier-fn (if qualifier + (comp (partial keyword qualifier) identifiers) + (comp keyword identifiers)) keys (->> idxs (map (fn [^Integer i] (.getColumnLabel rsmeta i))) col-name-fn - (map (comp (partial keyword qualifier) identifiers))) + (map identifier-fn)) row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index cc44d558..55ba33b6 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -834,6 +834,12 @@ (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil :fruit/grade nil :fruit/cost nil}] (sql/query db ["SELECT * FROM fruit"] {:qualifier "fruit"}))) + (is (= [{:fruit/name "Apple"}] + (sql/query db ["SELECT name FROM fruit"] + {:identifiers (comp (partial str "fruit/") str/lower-case)}))) + (is (= [{:name "Apple"}] + (sql/query db ["SELECT name FROM fruit"] + {:identifiers (comp keyword str/lower-case)}))) (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil :fruit/grade nil :fruit/cost nil}] (sql/query (assoc db :qualifier "fruit") ["SELECT * FROM fruit"]))) From d314d738a3ee17d23a3e4e291f9dfa35abf20240 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 25 Aug 2016 14:42:18 -0500 Subject: [PATCH 403/630] [maven-release-plugin] prepare release java.jdbc-0.6.2-alpha3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5406601a..9d26bc3a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-SNAPSHOT + 0.6.2-alpha3 ${project.artifactId} @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.6.2-alpha3 From a357e73f0311e657dec0046be598fad165f06b19 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 25 Aug 2016 14:42:19 -0500 Subject: [PATCH 404/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9d26bc3a..5406601a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-alpha3 + 0.6.2-SNAPSHOT ${project.artifactId} @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.6.2-alpha3 + HEAD From 944e800584eb6032cd45285af9aa1b54549fa4d5 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 31 Aug 2016 10:29:52 -0700 Subject: [PATCH 405/630] Fix JDBC-141 by adding get-isolation-level --- CHANGES.md | 4 ++++ src/main/clojure/clojure/java/jdbc.clj | 16 +++++++++++++++- src/main/clojure/clojure/java/jdbc/spec.clj | 4 ++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 8da1460f..c2864908 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.6.2-alpha4 + +* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141). + Changes in 0.6.2-alpha3 * Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 8f2df325..88e17997 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -587,14 +587,28 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } [db] (deref (:rollback db))) -(def ^{:private true :doc "Transaction isolation levels."} +(def ^:private isolation-levels + "Transaction isolation levels." {:none java.sql.Connection/TRANSACTION_NONE :read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED :read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED :repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ :serializable java.sql.Connection/TRANSACTION_SERIALIZABLE}) +(def ^:private isolation-kws + "Map transaction isolation constants to our keywords." + (clojure.set/map-invert isolation-levels)) + +(defn get-isolation-level + "Given a db-spec (with an optional connection), return the current + transaction isolation level, if known. Return nil if there is no + active connection in the db-spec. Return :unknown if we do not + recognize the isolation level." + [db] + (when-let [con (db-find-connection db)] + (isolation-kws (.getTransactionIsolation con) :unknown))) + (defn db-transaction* "Evaluates func as a transaction on the open database connection. Any nested transactions are absorbed into the outermost transaction. By diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index ce7e0cd9..423d18b6 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -104,6 +104,10 @@ ;; transaction functions +(s/fdef sql/get-isolation-level + :args (s/cat :db ::db-spec) + :ret (s/nilable keyword?)) + ;; metadata-result ;; db-do-commands From dc1954ff0abcec63cfc2307eb0a3cb85e74f46cb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 31 Aug 2016 10:33:37 -0700 Subject: [PATCH 406/630] Clean up ns form --- src/main/clojure/clojure/java/jdbc.clj | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 88e17997..60db70b3 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -40,13 +40,14 @@ For more documentation, see: http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } clojure.java.jdbc - (:import [java.net URI] - [java.sql BatchUpdateException DriverManager - PreparedStatement ResultSet SQLException Statement Types] - [java.util Hashtable Map Properties] - [javax.sql DataSource]) - (:require [clojure.string :as str] - [clojure.walk :as walk])) + (:require [clojure.set :as set] + [clojure.string :as str] + [clojure.walk :as walk]) + (:import (java.net URI) + (java.sql BatchUpdateException DriverManager + PreparedStatement ResultSet SQLException Statement Types) + (java.util Hashtable Map Properties) + (javax.sql DataSource))) (defn as-sql-name "Given a naming strategy function and a keyword or string, return @@ -598,7 +599,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (def ^:private isolation-kws "Map transaction isolation constants to our keywords." - (clojure.set/map-invert isolation-levels)) + (set/map-invert isolation-levels)) (defn get-isolation-level "Given a db-spec (with an optional connection), return the current From 191bdcabebe296510a4267a62868ace1ef97482b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 31 Aug 2016 18:12:46 -0700 Subject: [PATCH 407/630] JDBC-137 add read-columns support Also cleans up set-parameters logic and allows it to be passed in the options rather than just in the db-spec itself. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 81 +++++++++++++++----------- 2 files changed, 49 insertions(+), 33 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c2864908..013b9a7a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.6.2-alpha4 * Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141). +* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://dev.clojure.org/jira/browse/JDBC-137). Changes in 0.6.2-alpha3 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 60db70b3..61fd8263 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -371,6 +371,13 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (set-parameter [_ ^PreparedStatement s ^long i] (.setObject s i (sql-value nil)))) +(defn- dft-set-parameters + "Default implementation of parameter setting for the given statement." + [stmt params] + (dorun (map-indexed (fn [ix value] + (set-parameter value stmt (inc ix))) + params))) + (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default implementations (for Object and nil) return the argument, and the @@ -389,6 +396,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } nil (result-set-read-column [_1 _2 _3] nil)) +(defn- dft-read-columns + "Default implementation of reading row values from result set, given the + result set metadata and the indices." + [rs rsmeta idxs] + (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) + (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it @@ -400,8 +413,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } keywords. The default is to convert them to lower case. The :qualifier option specifies the namespace qualifier for those identifiers." ([rs] (result-set-seq rs {})) - ([^ResultSet rs {:keys [as-arrays? identifiers qualifier] - :or {identifiers str/lower-case}}] + ([^ResultSet rs {:keys [as-arrays? identifiers qualifier read-columns] + :or {identifiers str/lower-case + read-columns dft-read-columns}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) @@ -409,10 +423,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (comp (partial keyword qualifier) identifiers) (comp keyword identifiers)) keys (->> idxs - (map (fn [^Integer i] (.getColumnLabel rsmeta i))) + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) col-name-fn - (map identifier-fn)) - row-values (fn [] (map (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) + (mapv identifier-fn)) + row-values (fn [] (read-columns rs rsmeta idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't @@ -512,13 +526,6 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (when timeout (.setQueryTimeout stmt timeout)) stmt))) -(defn- set-parameters - "Add the parameters to the given statement." - [stmt params] - (dorun (map-indexed (fn [ix value] - (set-parameter value stmt (inc ix))) - params))) - (defn print-sql-exception "Prints the contents of an SQLException to *out*" [^SQLException exception] @@ -718,8 +725,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } :row-fn,and :result-set-fn to control how the ResultSet is transformed and returned. See query for more details." ([rs-or-value] (metadata-result rs-or-value {})) - ([rs-or-value {:keys [as-arrays? identifiers qualifier result-set-fn row-fn] - :or {identifiers str/lower-case row-fn identity}}] + ([rs-or-value {:keys [as-arrays? identifiers qualifier read-columns + result-set-fn row-fn] + :or {identifiers str/lower-case + read-columns dft-read-columns + row-fn identity}}] (let [result-set-fn (or result-set-fn (if as-arrays? vec doall))] (if (instance? java.sql.ResultSet rs-or-value) ((^{:once true} fn* [rs] @@ -729,7 +739,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (map row-fn rs)))) (result-set-seq rs-or-value {:as-arrays? as-arrays? :identifiers identifiers - :qualifier qualifier})) + :qualifier qualifier + :read-columns read-columns})) rs-or-value)))) (defmacro metadata-query @@ -769,8 +780,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "Executes a PreparedStatement, optionally in a transaction, and (attempts to) return any generated keys." [db ^PreparedStatement stmt param-group {:keys [transaction?] :as opts}] - ((or (:set-parameters db) set-parameters) stmt param-group) - (let [exec-and-return-keys + (let [opts (merge (when (map? db) db) opts) + exec-and-return-keys (^{:once true} fn* [] (let [counts (.executeUpdate stmt)] (try @@ -783,6 +794,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (catch Exception _ ;; assume generated keys is unsupported and return counts instead: counts))))] + ((:set-parameters opts dft-set-parameters) stmt param-group) (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (exec-and-return-keys)) @@ -820,20 +832,21 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- db-do-execute-prepared-statement "Execute a PreparedStatement, optionally in a transaction." - [db ^PreparedStatement stmt param-groups {:keys [transaction?]}] - (if (empty? param-groups) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) - (vector (.executeUpdate stmt))) - (do - (doseq [param-group param-groups] - ((or (:set-parameters db) set-parameters) stmt param-group) - (.addBatch stmt)) + [db ^PreparedStatement stmt param-groups {:keys [transaction?] :as opts}] + (let [opts (merge (when (map? db) db) opts)] + (if (empty? param-groups) (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt))))) + (vector (.executeUpdate stmt))) + (vector (.executeUpdate stmt))) + (do + (doseq [param-group param-groups] + ((:set-parameters opts dft-set-parameters) stmt param-group) + (.addBatch stmt)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt)))))) (defn db-do-prepared "Executes an (optionally parameterized) SQL prepared statement on the @@ -872,7 +885,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (let [opts (merge (when (map? db) db) opts) [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] - ((or (:set-parameters db) set-parameters) stmt params) + ((:set-parameters opts dft-set-parameters) stmt params) (with-open [rset (.executeQuery stmt)] (func rset)))] (when-not (sql-stmt? sql) @@ -913,8 +926,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } ([db sql-params] (query db sql-params {})) ([db sql-params opts] (let [{:keys [as-arrays? explain? explain-fn identifiers qualifier - result-set-fn row-fn] :as opts} - (merge {:explain-fn println :identifiers str/lower-case :row-fn identity} + read-columns result-set-fn row-fn] :as opts} + (merge {:explain-fn println :identifiers str/lower-case + :read-columns dft-read-columns :row-fn identity} (when (map? db) db) opts) result-set-fn (or result-set-fn (if as-arrays? vec doall)) @@ -936,7 +950,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (map row-fn rs)))) (result-set-seq rset {:as-arrays? as-arrays? :identifiers identifiers - :qualifier qualifier}))) + :qualifier qualifier + :read-columns read-columns}))) opts)))) (defn- direction From 78b35e0320f143f7f8118ff63a5d8b73c8cee118 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 00:19:26 -0700 Subject: [PATCH 408/630] Add type hint to remove reflection --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 61fd8263..de4f197d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -399,7 +399,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (defn- dft-read-columns "Default implementation of reading row values from result set, given the result set metadata and the indices." - [rs rsmeta idxs] + [^ResultSet rs rsmeta idxs] (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) (defn result-set-seq From a21b47a15459ae5a1cb1321787d7ed164351d4e7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 00:19:42 -0700 Subject: [PATCH 409/630] Continue to expand clojure.spec coverage --- src/main/clojure/clojure/java/jdbc/spec.clj | 112 +++++++++++++++++--- 1 file changed, 100 insertions(+), 12 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 423d18b6..09909042 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -21,31 +21,33 @@ (s/def ::connection #(instance? java.sql.Connection %)) (s/def ::prepared-statement #(instance? java.sql.PreparedStatement %)) +(s/def ::result-set #(instance? java.sql.ResultSet %)) +(s/def ::result-set-metadata #(instance? java.sql.ResultSetMetaData %)) ;; database specification (connection description) (s/def ::db-spec-connection (s/keys :req-un [::connection])) -(s/def ::db-spec-factory (s/keys :req-un [::factory])) +(s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname] :opt-un [::host ::port])) +(s/def ::db-spec-raw (s/keys :req-un [::connection-uri])) (s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname] :opt-un [::classname])) -(s/def ::db-spec-driver-manager-alt (s/keys :req-un [::dbtype ::dbname] :opt-un [::host ::port])) +(s/def ::db-spec-factory (s/keys :req-un [::factory])) (s/def ::db-spec-data-source (s/keys :req-un [::datasource] :opt-un [::username ::user ::password])) (s/def ::db-spec-jndi (s/keys :req-un [::name] :opt-un [::environment])) -(s/def ::db-spec-raw (s/keys :req-un [::connection-uri])) (s/def ::db-spec-string string?) (s/def ::db-spec (s/or :connection ::db-spec-connection - :factory ::db-spec-factory + :friendly ::db-spec-friendly + :raw ::db-spec-raw :driver-mgr ::db-spec-driver-manager - :friendly ::db-spec-driver-manager-alt + :factory ::db-spec-factory :datasource ::db-spec-data-source :jndi ::db-spec-jndi - :raw ::db-spec-raw :uri ::db-spec-string)) ;; naming (s/def ::entity string?) -(s/def ::identifier (s/or :kw keyword? :str string?)) +(s/def ::identifier (s/or :kw keyword? :s string?)) ;; SQL and parameters @@ -62,6 +64,56 @@ (s/def ::execute-result (s/* integer?)) +;; specific options that can be passed +;; a few of them are nilable, where the functions either pass a possibly nil +;; version of the option to a called function, but most are not nilable because +;; the corresponding options must either be omitted or given valid values + +(s/def ::as-arrays? (s/nilable #{:cols-as-is true false})) +(s/def ::concurrency (set (keys @#'sql/result-set-concurrency))) +(s/def ::cursors (set (keys @#'sql/result-set-holdability))) +(s/def ::fetch-size nat-int?) +;; note the asymmetry here: the identifiers function converts a SQL entity to +;; an identifier (a symbol or a string), whereas the entities function converts +;; a string (not an identifier) to a SQL entity; SQL entities are always strings +;; but whilst java.jdbc lets you produce a keyword from identifiers, it does not +;; assume that entities can accept keywords! +(s/def ::identifiers (s/fspec :args (s/cat :s ::entity) + :ret ::identifier)) +(s/def ::entities (s/fspec :args (s/cat :s string?) + :ret ::entity)) +(s/def ::max-size nat-int?) +(s/def ::multi? boolean?) +;; strictly speaking we accept any keyword or string whose upper case name +;; is either ASC or DESC so this spec is overly restrictive; the :id-dir +;; can actually be an empty map although that is not very useful +(s/def ::direction #{:asc :desc "asc" "desc" "ASC" "DESC"}) +(s/def ::column-direction (s/or :id ::identifier + :id-dir (s/map-of ::identifier ::direction))) +(s/def ::order-by (s/coll-of ::column-direction)) +(s/def ::qualifier (s/nilable string?)) +;; cannot generate a result set so we can't specify this yet +#_(s/def ::read-columns (s/fspec :args (s/cat :rs ::result-set + :rsmeta ::result-set-metadata + :idxs (s/coll-of pos-int?)) + :ret (s/coll-of any?))) +;; there's not much we can say about result-set-fn -- it accepts a collection of +;; transformed rows (from row-fn), and it produces whatever it wants +(s/def ::result-set-fn (s/fspec :args (s/cat :rs (s/coll-of any?)) + :ret any?)) +(s/def ::result-type (set (keys @#'sql/result-set-type))) +;; there's not much we can say about row-fn -- it accepts a row from a ResultSet +;; which is a map of keywords to any values, and it produces whatever it wants +;; (comp clojure.string/lower-case :table_name) does not satisfy this +#_(s/def ::row-fn (s/fspec :args (s/cat :row (s/map-of keyword? any?)) + :ret any?)) +(s/def ::row-fn ifn?) +(s/def ::return-keys (s/or :columns (s/coll-of ::entity :kind vector?) + :boolean boolean?)) +;; ::table-spec +(s/def ::timeout nat-int?) +(s/def ::transaction? boolean?) + ;; various types of options (s/def ::create-options (s/keys :req-un [] :opt-un [::table-spec ::entities])) @@ -70,11 +122,21 @@ (s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?])) -(s/def ::find-by-keys-options (s/keys :req-un [] :opt-un [::entities ::order-by ::result-set-fn ::row-fn ::identifiers ::as-arrays?])) +(s/def ::find-by-keys-options (s/keys :req-un [] + :opt-un [::entities ::order-by + ::result-set-fn ::row-fn + ::identifiers ::qualifier + ::as-arrays?])) -(s/def ::prepare-options (s/keys :req-un [] :opt-un [::return-keys ::result-type ::concurrency ::cursors ::fetch-size ::max-rows ::timeout])) +(s/def ::prepare-options (s/keys :req-un [] + :opt-un [::return-keys ::result-type + ::concurrency ::cursors ::fetch-size + ::max-rows ::timeout])) -(s/def ::query-options (s/keys :req-un [] :opt-un [::result-set-fn ::row-fn ::identifiers ::as-arrays?])) +(s/def ::query-options (s/keys :req-un [] + :opt-un [::result-set-fn ::row-fn + ::identifiers ::qualifier + ::as-arrays? ::read-columns])) ;; the function API @@ -86,7 +148,10 @@ :args (s/cat :db-spec ::db-spec) :ret ::connection) -;; result-set-seq +(s/fdef sql/result-set-seq + :args (s/cat :rs ::result-set + :opts (s/? ::query-options)) + :ret any?) (s/fdef sql/prepare-statement :args (s/cat :con ::connection @@ -104,11 +169,34 @@ ;; transaction functions +(s/fdef sql/db-set-rollback-only! + :args (s/cat :db ::db-spec)) + +(s/fdef sql/db-unset-rollback-only! + :args (s/cat :db ::db-spec)) + +(s/fdef sql/db-is-rollback-only + :args (s/cat :db ::db-spec) + :ret boolean?) + (s/fdef sql/get-isolation-level :args (s/cat :db ::db-spec) :ret (s/nilable keyword?)) -;; metadata-result +;; db-transaction* + +;; with-db-transaction macro + +;; with-db-connection macro + +;; with-db-metadata macro + +(s/fdef sql/metadata-result + :args (s/cat :rs-or-value any? + :opts (s/? ::query-options)) + :ret any?) + +;; metadata-query macro ;; db-do-commands From 154574d9f13ec7e546069b551aa58fe5a5576ae2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 10:14:52 -0700 Subject: [PATCH 410/630] Correct ::as-arrays? spec Can't have a set with `false` in it as a predicate (duh!) so either the keyword (:cols-as-is) or a `nilable boolean?` is more accurate (although still overly restrictive since `as-arrays?` can technically be `any?` -- but that doesn't indicate the intended use). --- src/main/clojure/clojure/java/jdbc/spec.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 09909042..b3e99977 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -69,7 +69,7 @@ ;; version of the option to a called function, but most are not nilable because ;; the corresponding options must either be omitted or given valid values -(s/def ::as-arrays? (s/nilable #{:cols-as-is true false})) +(s/def ::as-arrays? (s/or :as-is #{:cols-as-is} :truthy (s/nilable boolean?))) (s/def ::concurrency (set (keys @#'sql/result-set-concurrency))) (s/def ::cursors (set (keys @#'sql/result-set-holdability))) (s/def ::fetch-size nat-int?) From 6298bbc1c3bd75611fcb4c2da4a3a524082d2322 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 10:56:07 -0700 Subject: [PATCH 411/630] Clean up some specs; fix a test Code that "assumes" a SQL value has a particular shape is going to fail the spec for `row-fn` if it doesn't guard for the type (e.g., calling str/lower-case on a column, without calling str first). This may prove to be way too restrictive for users of `java.jdbc` however... --- src/main/clojure/clojure/java/jdbc/spec.clj | 19 +++++++++---------- src/test/clojure/clojure/java/test_jdbc.clj | 2 +- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index b3e99977..794219aa 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -97,20 +97,19 @@ :rsmeta ::result-set-metadata :idxs (s/coll-of pos-int?)) :ret (s/coll-of any?))) +(s/def ::read-columns fn?) ;; there's not much we can say about result-set-fn -- it accepts a collection of ;; transformed rows (from row-fn), and it produces whatever it wants (s/def ::result-set-fn (s/fspec :args (s/cat :rs (s/coll-of any?)) :ret any?)) (s/def ::result-type (set (keys @#'sql/result-set-type))) ;; there's not much we can say about row-fn -- it accepts a row from a ResultSet -;; which is a map of keywords to any values, and it produces whatever it wants -;; (comp clojure.string/lower-case :table_name) does not satisfy this -#_(s/def ::row-fn (s/fspec :args (s/cat :row (s/map-of keyword? any?)) - :ret any?)) -(s/def ::row-fn ifn?) +;; which is a map of keywords to SQL values, and it produces whatever it wants +(s/def ::row-fn (s/fspec :args (s/cat :row (s/map-of keyword? ::sql-value)) + :ret any?)) (s/def ::return-keys (s/or :columns (s/coll-of ::entity :kind vector?) :boolean boolean?)) -;; ::table-spec +(s/def ::table-spec string?) (s/def ::timeout nat-int?) (s/def ::transaction? boolean?) @@ -126,7 +125,7 @@ :opt-un [::entities ::order-by ::result-set-fn ::row-fn ::identifiers ::qualifier - ::as-arrays?])) + ::as-arrays? ::read-columns])) (s/def ::prepare-options (s/keys :req-un [] :opt-un [::return-keys ::result-type @@ -200,7 +199,7 @@ ;; db-do-commands -;; db-do-prepared-return-keys +;; db-do-prepared-return-keys -- can have both execute options and query options! ;; db-do-prepared @@ -235,9 +234,9 @@ :opts (s/? ::exec-sql-options)) :ret ::execute-result) -;; insert! +;; insert! -- can have both execute options and query options! -;; insert-multi! +;; insert-multi! -- can have both execute options and query options! (s/fdef sql/update! :args (s/cat :db ::db-spec diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 55ba33b6..9151400f 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -766,7 +766,7 @@ (sql/metadata-query (.getTables metadata nil nil nil (into-array ["TABLE" "VIEW"])) - {:row-fn (comp clojure.string/lower-case :table_name) + {:row-fn (comp clojure.string/lower-case str :table_name) :result-set-fn first})))))) (deftest test-metadata From b07b72ce7c95666b9000a35d08f1a9ea3603a218 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 12:25:40 -0700 Subject: [PATCH 412/630] Spec get-by-id --- src/main/clojure/clojure/java/jdbc/spec.clj | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 794219aa..c59ac131 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -209,7 +209,6 @@ :args (s/cat :db ::db-spec :sql-params ::sql-params :opts (s/? ::query-options)) - ;; because result-set-fn can return anything: :ret any?) (s/fdef sql/find-by-keys @@ -219,7 +218,13 @@ :opts (s/? ::find-by-keys-options)) :ret any?) -;; get-by-id +(s/fdef sql/get-by-id + :args (s/cat :db ::db-spec + :table ::identifier + :pk-value ::sql-value + :opt-args (s/cat :pk-name (s/? ::identifier) + :opts (s/? ::find-by-keys-options))) + :ret any?) (s/fdef sql/execute! :args (s/cat :db ::db-spec From f51d5379324a346cacec41fabf473c3a529535ac Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 12:27:58 -0700 Subject: [PATCH 413/630] Skip to 0.7.0 as we'll make breaking changes --- CHANGES.md | 2 +- pom.xml | 2 +- project.clj | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 013b9a7a..01da4e14 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.6.2-alpha4 +Changes coming in 0.7.0-alpha1 * Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141). * Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://dev.clojure.org/jira/browse/JDBC-137). diff --git a/pom.xml b/pom.xml index 5406601a..dc0a6966 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.6.2-SNAPSHOT + 0.7.0-SNAPSHOT ${project.artifactId} diff --git a/project.clj b/project.clj index cac98765..f3afa8fe 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.6.2-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.7.0-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" @@ -27,6 +27,7 @@ ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"] ] + :monkeypatch-clojure-test false :profiles {:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} From ee7ce8c78e76bc2014733a1a14c74f85505a9780 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 17:05:12 -0700 Subject: [PATCH 414/630] Breaking change! as-sql-name / quoted Changing these so both are single arity: `as-sql-name` is now only a 2-arity function; if you were previously using the 1-arity form (curried), then you will need to use `partial`. `quoted` is now only a 1-arity function; if you were previously using the 2-arity form, you'll need to add extra (). Also some minor (Leiningen) local dev/test tweaks (bump default Clojure to 1.9.0 Alpha 11, add dev profile to test,1.9 to bring in test.check now that testing involves generative specs / higher-order functions). --- project.clj | 6 ++- src/main/clojure/clojure/java/jdbc.clj | 41 +++++++++------------ src/main/clojure/clojure/java/jdbc/spec.clj | 16 ++++++-- src/test/clojure/clojure/java/test_jdbc.clj | 20 ++++++---- 4 files changed, 47 insertions(+), 36 deletions(-) diff --git a/project.clj b/project.clj index f3afa8fe..0d7015a9 100644 --- a/project.clj +++ b/project.clj @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-alpha10"] + :dependencies [[org.clojure/clojure "1.9.0-alpha11"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj @@ -27,6 +27,7 @@ ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"] ] + ;; prevent Leiningen from breaking test.check :monkeypatch-clojure-test false :profiles {:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} @@ -37,6 +38,7 @@ :dev {:dependencies [[org.clojure/test.check "0.9.0"]]} } :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - :aliases {"test-all" ["with-profile" "test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:test,1.9" "test"] + ;; include dev profile with 1.9 to pull in test.check + :aliases {"test-all" ["with-profile" "test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:dev,test,1.9" "test"] "check-all" ["with-profile" "1.4:1.5:1.6:1.7:1.8:1.9" "check"]} :min-lein-version "2.0.0") diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index de4f197d..70074b28 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -56,31 +56,26 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } and each are turned into strings via the naming strategy and then joined back together so x.y might become `x`.`y` if the naming strategy quotes identifiers with `." - ([f] - (fn [x] - (as-sql-name f x))) - ([f x] - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\."))))))) + [f x] + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\.")))))) (defn quoted - "With a single argument, returns a naming strategy function that quotes - names. The single argument can either be a single character or a vector - pair of characters. - Can also be called with two arguments - a quoting argument and a name - - and returns the fully quoted string: - (quoted \\` \"foo\") will return \"`foo`\" - (quoted [\\[ \\]] \"foo\") will return \"[foo]\"" - ([q] - (fn [x] - (quoted q x))) - ([q x] - (if (vector? q) - (str (first q) x (last q)) - (str q x q)))) + "Given a (vector) pair of delimiters (characters or strings), return a naming + strategy function that will quote SQL entities with them. + Given a single delimiter, treat it as a (vector) pair of that delimiter. + ((quoted [\\[ \\]]) \"foo\") will return \"[foo]\" -- for MS SQL Server + ((quoted \\`') \"foo\") will return \"`foo`\" -- for MySQL + Intended to be used with :entities to provide a quoting (naming) strategy that + is appropriate for your database." + [q] + (if (vector? q) + (fn [x] + (str (first q) x (last q))) + (quoted [q q]))) (defn- table-str "Transform a table spec to an entity name for SQL. The table spec may be a diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index c59ac131..156f3aeb 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -139,9 +139,19 @@ ;; the function API -;; as-sql-name - -;; quoted +(s/def ::naming-strategy (s/fspec :args (s/cat :x ::identifier) + :ret ::identifier)) + +(s/fdef sql/as-sql-name + :args (s/cat :f ::naming-strategy :x ::identifier) + :ret ::identifier) + +(s/def ::delimiter (s/or :s string? :c char?)) +(s/fdef sql/quoted + :args (s/cat :q (s/or :pair (s/coll-of ::delimiter + :kind vector? :count 2) + :delimiter ::delimiter)) + :ret ::naming-strategy) (s/fdef sql/get-connection :args (s/cat :db-spec ::db-spec) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9151400f..170f267b 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -25,13 +25,15 @@ [clojure.java.jdbc :as sql] [clojure.string :as str])) -(try - (require 'clojure.java.jdbc.spec) - (require 'clojure.spec.test) - (let [syms ((resolve 'clojure.spec.test/enumerate-namespace) 'clojure.java.jdbc)] - ((resolve 'clojure.spec.test/instrument) syms)) - (println "Instrumenting clojure.java.jdbc with clojure.spec") - (catch Exception _)) +(def with-spec? (try + (require 'clojure.java.jdbc.spec) + (require 'clojure.spec.test) + (let [syms ((resolve 'clojure.spec.test/enumerate-namespace) 'clojure.java.jdbc)] + ((resolve 'clojure.spec.test/instrument) syms)) + (println "Instrumenting clojure.java.jdbc with clojure.spec") + true + (catch Exception _ + false))) ;; Set test-databases according to whether you have the local database available: ;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str] @@ -953,7 +955,9 @@ (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] {:entities identity}))) (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) - (is (thrown? ClassCastException (sql/insert! db [:name] {:entities identity}))))) + (if with-spec? ; clojure.spec catches this differently + (is (thrown? clojure.lang.ExceptionInfo (sql/insert! db [:name] {:entities identity}))) + (is (thrown? ClassCastException (sql/insert! db [:name] {:entities identity})))))) (deftest test-execute!-fails-with-multi-param-groups (doseq [db (test-specs)] From 354af1cc79a5c38c9de6b58e805411936fe795e9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 1 Sep 2016 17:13:22 -0700 Subject: [PATCH 415/630] Add test.check to pom.xml (test scope) --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index dc0a6966..c9509ce6 100644 --- a/pom.xml +++ b/pom.xml @@ -101,6 +101,12 @@ 1.3.1 test + + org.clojure + test.check + 0.9.0 + test + com.theoryinpractise clojure-maven-plugin - 1.3.13 + 1.7.1 true ${clojure.warnOnReflection} From cc52492b4e9e3e02d493b7d33263b3d3ca2de4bb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 1 Mar 2017 10:45:04 -0800 Subject: [PATCH 441/630] JDBC-150 add pgsql support; improve error msg on bad dbtype/subprotocol Also bumps driver versions for tests. --- CHANGES.md | 1 + project.clj | 23 +++++------ src/main/clojure/clojure/java/jdbc.clj | 42 ++++++++++++--------- src/main/clojure/clojure/java/jdbc/spec.clj | 4 +- src/test/clojure/clojure/java/test_jdbc.clj | 33 +++++++++++----- 5 files changed, 65 insertions(+), 38 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 85f01643..37d41b25 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.0-alpha2 +* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149). * Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://dev.clojure.org/jira/browse/JDBC-148). * Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://dev.clojure.org/jira/browse/JDBC-145). diff --git a/project.clj b/project.clj index 92e57d22..966cec3f 100644 --- a/project.clj +++ b/project.clj @@ -10,31 +10,32 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-alpha11"] + :dependencies [[org.clojure/clojure "1.9.0-alpha14"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj ;; file exists for convenience -- the pom.xml file is the ;; "system of record" as far as dependencies go! - [org.apache.derby/derby "10.12.1.1"] - [org.hsqldb/hsqldb "2.3.3"] - [com.h2database/h2 "1.4.191"] + [org.apache.derby/derby "10.13.1.1"] + [org.hsqldb/hsqldb "2.3.4"] + [com.h2database/h2 "1.4.193"] [net.sourceforge.jtds/jtds "1.3.1"] ;; Tests fail with 6.0.2 driver: - [mysql/mysql-connector-java "5.1.39"] - [org.postgresql/postgresql "9.4.1210.jre7"] - [org.xerial/sqlite-jdbc "3.8.11.2"] + [mysql/mysql-connector-java "5.1.41"] + [org.postgresql/postgresql "9.4.1212.jre7"] + [com.impossibl.pgjdbc-ng/pgjdbc-ng "0.7.1"] + [org.xerial/sqlite-jdbc "3.16.1"] ;; if you have the MS driver in your local repo - [sqljdbc4 "4.0"] - ] + [sqljdbc4 "4.0"]] + :profiles {:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} - :dev {:dependencies [[org.clojure/test.check "0.9.0"]]} - } + :dev {:dependencies [[org.clojure/test.check "0.9.0"]]}} + :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/" "ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"} ;; include dev profile with 1.9 to pull in test.check diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e6a34ede..1f813cfd 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2016 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be @@ -38,7 +38,7 @@ generated keys are returned (as a map). For more documentation, see: -http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } +http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} clojure.java.jdbc (:require [clojure.set :as set] [clojure.string :as str] @@ -154,6 +154,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } "oracle:oci" "oracle.jdbc.OracleDriver" "oracle:thin" "oracle.jdbc.OracleDriver" "postgresql" "org.postgresql.Driver" + "pgsql" "com.impossibl.postgres.jdbc.PGDriver" "sqlite" "org.sqlite.JDBC" "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) @@ -296,30 +297,37 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html" } (str "jdbc:" subprotocol "://" host (when port (str ":" port)) db-sep dbname)) - etc (dissoc db-spec :dbtype :dbname) - ; force DriverManager to be loaded - _ (DriverManager/getLoginTimeout)] - (clojure.lang.RT/loadClassForName (classnames subprotocol)) + etc (dissoc db-spec :dbtype :dbname)] + (if-let [class-name (classnames subprotocol)] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) (DriverManager/getConnection url (as-properties etc))) (and subprotocol subname) (let [;; allow aliases for subprotocols subprotocol (subprotocols subprotocol subprotocol) url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname) - classname (or classname (classnames subprotocol)) - ; force DriverManager to be loaded - _ (DriverManager/getLoginTimeout)] - (clojure.lang.RT/loadClassForName classname) + etc (dissoc db-spec :classname :subprotocol :subname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) (DriverManager/getConnection url (as-properties etc))) name - (when-available - javax.naming.InitialContext - (let [env (and environment (Hashtable. ^Map environment)) - context (javax.naming.InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (.getConnection datasource))) + (or (when-available javax.naming.InitialContext + (let [env (and environment (Hashtable. ^Map environment)) + context (javax.naming.InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (.getConnection datasource))) + (throw (ex-info (str "javax.naming.InitialContext is not available for: " + name) + db-spec))) :else (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 29ac5971..c751aa65 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -28,7 +28,9 @@ ;; database specification (connection description) -(s/def ::subprotocol-base #{"derby" "h2" "hsqldb" "jtds:sqlserver" "mysql" "oracle:oci" "oracle:thin" "postgresql" "sqlite" "sqlserver"}) +(s/def ::subprotocol-base #{"derby" "h2" "hsqldb" "jtds:sqlserver" "mysql" + "oracle:oci" "oracle:thin" "pgsql" "postgresql" + "sqlite" "sqlserver"}) (s/def ::subprotocol-alias #{"hsql" "jtds" "mssql" "oracle" "postgres"}) ;; technically :subprotocol can be any string... (s/def ::subprotocol string?) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9ef15082..d14755b6 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -89,6 +89,13 @@ :user "clojure_test" :password "clojure_test"}) +(def pgsql-db {:dbtype "pgsql" + :dbname "clojure_test" + :host postgres-host + :port postgres-port + :user "clojure_test" + :password "clojure_test"}) + (def mssql-db {:dbtype "mssql" :dbname mssql-dbname :host mssql-host @@ -126,9 +133,9 @@ (doseq [table [:fruit :fruit2 :veggies :veggies2]] (try (sql/db-do-commands db (sql/drop-table-ddl table)) - (catch java.sql.SQLException _ + (catch java.sql.SQLException _)))) ;; ignore - )))) + (t)) (use-fixtures @@ -160,8 +167,14 @@ (defn- postgres? [db] (if (string? db) - (re-find #"postgres" db) - (re-find #"postgres" (or (:subprotocol db) (:dbtype db))))) + (or (re-find #"postgres" db) (re-find #"pgsql")) + (or (re-find #"postgres" (or (:subprotocol db) (:dbtype db))) + (re-find #"pgsql" (or (:subprotocol db) (:dbtype db)))))) + +(defn- pgsql? [db] + (if (string? db) + (re-find #"pgsql") + (re-find #"pgsql" (or (:subprotocol db) (:dbtype db))))) (defmulti create-test-table "Create a standard test table. Uses db-do-commands. @@ -241,7 +254,7 @@ (defn- select-key [db] (case (or (:subprotocol db) (:dbtype db)) - ("postgres" "postgresql") :id + ("postgres" "postgresql" "pgsql") :id identity)) (defn- generated-key [db k] @@ -260,7 +273,7 @@ "h2" (Float. v) ("jtds" "jtds:sqlserver") (Float. v) ("mssql" "sqlserver") (Float. v) - ("postgres" "postgresql") (Float. v) + ("postgres" "postgresql" "pgsql") (Float. v) v)) (deftest test-create-table @@ -411,9 +424,11 @@ (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= 4 (sql/with-db-connection [con db] (sql/query con (sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit") {:result-set-fn count})))) - (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count :max-rows 2}))) - (is (= 2 (sql/with-db-connection [con db] - (sql/query con [(sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit" {:max-rows 2})] {:result-set-fn count})))) + (when-not (pgsql? db) + ;; maxRows does not appear to be supported on Impossibl pgsql? + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count :max-rows 2}))) + (is (= 2 (sql/with-db-connection [con db] + (sql/query con [(sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit" {:max-rows 2})] {:result-set-fn count}))))) (is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first}))) (is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first}))) (is (= "Apple" (:name (sql/get-by-id db :fruit 1)))) From 7fce4e1a489a7d2ce953a1ab379378d032960caa Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 1 Mar 2017 10:49:39 -0800 Subject: [PATCH 442/630] 0.7.0 Alpha 2 --- CHANGES.md | 2 +- README.md | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 37d41b25..35e045a0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.0-alpha2 +Changes in 0.7.0-alpha2 * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149). diff --git a/README.md b/README.md index 8461df16..9462d8ff 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-alpha1 +Latest stable release: 0.7.0-alpha2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-alpha1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-alpha1"] +[org.clojure/java.jdbc "0.7.0-alpha2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-alpha1 + 0.7.0-alpha2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -120,6 +120,12 @@ Developer Information Change Log ==================== +* Release 0.7.0-alpha2 on 2017-03-01 + * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). + * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149). + * Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://dev.clojure.org/jira/browse/JDBC-148). + * Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://dev.clojure.org/jira/browse/JDBC-145). + * Release 0.7.0-alpha1 on 2016-11-12 -- potentially breaking changes * The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting). * Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://dev.clojure.org/jira/browse/JDBC-147). From 5fe24d4f83dfbdae76e7ddbd7fdb266d740f987c Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 1 Mar 2017 12:51:22 -0600 Subject: [PATCH 443/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-alpha2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b6c91a10..002332b0 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-alpha2 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-alpha2 From 983ce39ac3eb2f158c75dac56aa880c138287763 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 1 Mar 2017 12:51:22 -0600 Subject: [PATCH 444/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 002332b0..b6c91a10 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-alpha2 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-alpha2 + HEAD From c2502ffe24ceb39172a4392ba39e10d1d1aec1b2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 1 Mar 2017 10:53:37 -0800 Subject: [PATCH 445/630] Bump JDBC driver versions in POM to match actual, tested versions. --- pom.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index b6c91a10..9788fed8 100644 --- a/pom.xml +++ b/pom.xml @@ -62,37 +62,37 @@ mysql mysql-connector-java - 5.1.39 + 5.1.41 test org.apache.derby derby - 10.12.1.1 + 10.13.1.1 test org.hsqldb hsqldb - 2.3.3 + 2.3.4 test com.h2database h2 - 1.4.191 + 1.4.193 test org.postgresql postgresql - 9.4.1210.jre7 + 9.4.1212.jre7 test org.xerial sqlite-jdbc - 3.8.11.2 + 3.16.1 test From 829cba979db9ec3dea91ffa66e1cfb4924dabdad Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 14 Mar 2017 19:47:15 -0700 Subject: [PATCH 446/630] Roll back Derby to 1.12.1.1 Looks like 1.13.1.1 requires Java 8 but we build/test on Java 7. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9788fed8..12206d2a 100644 --- a/pom.xml +++ b/pom.xml @@ -68,7 +68,7 @@ org.apache.derby derby - 10.13.1.1 + 10.12.1.1 test From 8cd7600c58d92e8985b4316209f2fd50e292dc60 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 14 Mar 2017 19:54:43 -0700 Subject: [PATCH 447/630] Roll back H2 version Newer version seems to require Java 7. --- pom.xml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 12206d2a..4447c2e6 100644 --- a/pom.xml +++ b/pom.xml @@ -41,8 +41,7 @@ ${clojure.warnOnReflection} true - - + 1 clojure-compile none @@ -80,7 +79,7 @@ com.h2database h2 - 1.4.193 + 1.4.191 test From 268626a225cf18b3109d0f7783d8342396b7b521 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 14 Mar 2017 19:56:39 -0700 Subject: [PATCH 448/630] Fix typo introduced by previous edit Editing via GitHub on Edge / Win 10 is fussy :) --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4447c2e6..b67fe01e 100644 --- a/pom.xml +++ b/pom.xml @@ -41,7 +41,8 @@ ${clojure.warnOnReflection} true - 1 + + clojure-compile none From c1259840f54503d20cedfa01e37fb03df9ca5d0b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 14 Mar 2017 20:44:25 -0700 Subject: [PATCH 449/630] Note DB driver versions and Java 6/7 compatibility `project.clj` uses more recent database driver versions because I only test locally on Java 8; build.clojure.org uses Java 6 and Java 7 for matrix builds so Derby and H2 must remain at versions that are compatible with pre-Java 8 versions. --- project.clj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/project.clj b/project.clj index 966cec3f..4f813347 100644 --- a/project.clj +++ b/project.clj @@ -16,8 +16,10 @@ ;; appropriate for you. Again, note that this project.clj ;; file exists for convenience -- the pom.xml file is the ;; "system of record" as far as dependencies go! + ;; Note: 1.12.1.1 is used in pom.xml for Java 6/7 compat [org.apache.derby/derby "10.13.1.1"] [org.hsqldb/hsqldb "2.3.4"] + ;; Note: 1.4.191 is used in pom.xml for Java 6 compat [com.h2database/h2 "1.4.193"] [net.sourceforge.jtds/jtds "1.3.1"] ;; Tests fail with 6.0.2 driver: From 461fa0f3a1e79a4c7061f0e8eff112f9aee6838c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 14 Mar 2017 20:55:04 -0700 Subject: [PATCH 450/630] Added H2; note about DB drivers/JDK versions Added H2 link to Maven amongst example drivers. Added note about Apache Derby and H2 requiring Java 7/8 in recent versions but testing matrix covering Java 6 as well using earlier driver versions. --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 9462d8ff..69d9b47b 100644 --- a/README.md +++ b/README.md @@ -37,12 +37,15 @@ Latest stable release: 0.7.0-alpha2 You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: * [Apache Derby](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.derby%22%20AND%20a%3A%22derby%22) +* [H2](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.h2database%22%20AND%20a%3A%22h2%22) * [HSQLDB](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22hsqldb%22%20AND%20a%3A%22hsqldb%22) * [Microsoft SQL Server jTDS](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.jtds%22%20AND%20a%3A%22jtds%22) * [MySQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22mysql%22%20AND%20a%3A%22mysql-connector-java%22) * [PostgreSQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.postgresql%22%20AND%20a%3A%22postgresql%22) * [SQLite](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.xerial%22%20AND%20a%3A%22sqlite-jdbc%22) +Note: different versions of various database drivers have different Java/JVM version requirements. In particular, recent versions of Apache Derby require at least Java 8 and recent versions of H2 require at least Java 7. Clojure's Continuous Integration system uses older versions so tests can be run on Java 6 (see `pom.xml`); local testing is done with more recent versions on Java 8. + clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 4.0 but that has to be [downloaded manually](https://www.microsoft.com/en-us/download/details.aspx?id=11774) and placed in a Maven repository accessible to your system. For testing, it was installed locally as: ```clojure From 8510c073c331d88056607add77df5b12ac4bd079 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Tue, 21 Mar 2017 22:04:16 -0500 Subject: [PATCH 451/630] Update parent pom --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b67fe01e..664273ce 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ org.clojure pom.contrib - 0.2.0 + 0.2.2 From 4f8b7f784859da85c090fef29e599bff53f4f1ee Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 23 Mar 2017 12:17:04 -0700 Subject: [PATCH 452/630] Add RedShift as a built-in subprotocol --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1f813cfd..fc7477d5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -145,7 +145,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (add-connection [_ connection] {:connection connection :level 0 :legacy true}) (get-level [_] 0)) -(def ^{:private true :doc "Map of classnames to subprotocols"} classnames +(def ^:private classnames + "Map of subprotocols to classnames. dbtype specifies one of these keys. + The subprotocols map below provides aliases for dbtype." {"derby" "org.apache.derby.jdbc.EmbeddedDriver" "h2" "org.h2.Driver" "hsqldb" "org.hsqldb.jdbcDriver" @@ -155,10 +157,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "oracle:thin" "oracle.jdbc.OracleDriver" "postgresql" "org.postgresql.Driver" "pgsql" "com.impossibl.postgres.jdbc.PGDriver" + "redshift" "com.redshift.jdbc.Driver" "sqlite" "org.sqlite.JDBC" "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) -(def ^{:private true :doc "Map of schemes to subprotocols"} subprotocols +(def ^:private subprotocols + "Map of schemes to subprotocols. Used to provide aliases for dbtype." {"hsql" "hsqldb" "jtds" "jtds:sqlserver" "mssql" "sqlserver" From de41a11c72a0c74430f69e339926d6ae9e09cba0 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 23 Mar 2017 12:43:00 -0700 Subject: [PATCH 453/630] 0.7.0-alpha3 with JDBC-151 added --- CHANGES.md | 5 +++++ README.md | 19 ++++++++++++++++--- src/main/clojure/clojure/java/jdbc.clj | 5 +++-- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 35e045a0..35f412db 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes in 0.7.0-alpha3 + +* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). +* `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. + Changes in 0.7.0-alpha2 * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). diff --git a/README.md b/README.md index 69d9b47b..d714cef2 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-alpha2 +Latest stable release: 0.7.0-alpha3 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-alpha2 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-alpha2"] +[org.clojure/java.jdbc "0.7.0-alpha3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-alpha2 + 0.7.0-alpha3 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -74,6 +74,15 @@ Example Usage :ssl true :sslfactory "org.postgresql.ssl.NonValidatingFactory"}) +;; if the dbtype is not known to clojure.java.jdbc, or you want to override the +;; default choice of JDBC driver class name, you can provide :classname and the +;; name of the class to use: + +(def redshift42 {:dbtype "redshift" + :dbname "myredstore" + :classname "com.amazon.redshift.jdbc42.Driver" + ...}) + ;; you can also specify a full connection string if you'd prefer: (def pg-uri {:connection-uri (str "postgresql://myuser:secret@mydb.server.com:5432/mypgdatabase" @@ -123,6 +132,10 @@ Developer Information Change Log ==================== +Release 0.7.0-alpha3 on 2017-03-23 + * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). + * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. + * Release 0.7.0-alpha2 on 2017-03-01 * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index fc7477d5..9fa735a9 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -157,7 +157,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "oracle:thin" "oracle.jdbc.OracleDriver" "postgresql" "org.postgresql.Driver" "pgsql" "com.impossibl.postgres.jdbc.PGDriver" - "redshift" "com.redshift.jdbc.Driver" + "redshift" "com.amazon.redshift.jdbc.Driver" "sqlite" "org.sqlite.JDBC" "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) @@ -210,6 +210,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} DriverManager (preferred): :dbtype (required) a String, the type of the database (the jdbc subprotocol) :dbname (required) a String, the name of the database + :classname (optional) a String, the jdbc driver class name :host (optional) a String, the host name/IP of the database (defaults to 127.0.0.1) :port (optional) a Long, the port of the database @@ -302,7 +303,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (when port (str ":" port)) db-sep dbname)) etc (dissoc db-spec :dbtype :dbname)] - (if-let [class-name (classnames subprotocol)] + (if-let [class-name (or classname (classnames subprotocol))] (do ;; force DriverManager to be loaded (DriverManager/getLoginTimeout) From 6fdc344582eed736f6d5f0af08663ddf7944778d Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 23 Mar 2017 14:46:04 -0500 Subject: [PATCH 454/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-alpha3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 664273ce..5e47d8e3 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-alpha3 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-alpha3 From 651d655a0cedfebbcba73d0ac4da0665ca185caa Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 23 Mar 2017 14:46:04 -0500 Subject: [PATCH 455/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5e47d8e3..664273ce 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-alpha3 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-alpha3 + HEAD From 0b54d58d1c9a41ae2a55f4c7af827a5f6cd12abc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 28 Jun 2017 23:10:46 -0700 Subject: [PATCH 456/630] Add reducible queries JDBC-99 for 0.7.0-beta1 (need to drop 1.4) --- CHANGES.md | 4 ++ src/main/clojure/clojure/java/jdbc.clj | 48 +++++++++++++++++++++ src/test/clojure/clojure/java/test_jdbc.clj | 7 ++- 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 35f412db..3eb41597 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.0-beta1 + +* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce`): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) + Changes in 0.7.0-alpha3 * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9fa735a9..0e6e0d6f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -965,6 +965,54 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (result-set-seq rset opts))) opts)))) +(defn reducible-result-set + "Given a java.sql.ResultSet return a reducible collection. + Note: :as-arrays? is not accepted here." + [^ResultSet rs {:keys [identifiers qualifier read-columns] + :or {identifiers str/lower-case + read-columns dft-read-columns}}] + (reify clojure.core.protocols.CollReduce + (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) + (coll-reduce [this f init] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + identifier-fn (if qualifier + (comp (partial keyword qualifier) identifiers) + (comp keyword identifiers)) + keys (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + (make-cols-unique) + (mapv identifier-fn))] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init')))))) + +(defn reducible-query + "Given a database connection, a vector containing SQL and optional parameters, + return a reducible collection. When reduced, it will start the database query + and reduce the result set, and then close the connection. The following options + from query etc are not accepted here: + :as-arrays? :explain :explain-fn :result-set-fn :row-fn + See also prepare-statement for additional options." + ([db sql-params] (reducible-query db sql-params {})) + ([db sql-params opts] + (let [{:keys [reducing-fn] :as opts} + (merge {:identifiers str/lower-case :read-columns dft-read-columns} + (when (map? db) db) + opts) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (reify clojure.core.protocols.CollReduce + (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) + (coll-reduce [this f init] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f init (reducible-result-set rset opts))))))))) + (defn- direction "Given an entities function, a column name, and a direction, return the matching SQL column / order. diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index d14755b6..75628336 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -436,7 +436,12 @@ (is (= "Peach" (:name (sql/get-by-id db :fruit 3 :id)))) (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))) (is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]})))) - (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))))) + (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))) + (is (= 366 (reduce (fn [n r] (+ n (:cost r))) 0 + (sql/reducible-query db "SELECT * FROM fruit")))) + (when-let [transduce-fn (resolve 'clojure.core/transduce)] + (is (= 366 (transduce-fn (map :cost) + + (sql/reducible-query db "SELECT * FROM fruit"))))))) (deftest test-insert-values (doseq [db (test-specs)] From 2c5274b7758fba7de366541fdcadeabe38a61f2d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 28 Jun 2017 23:13:56 -0700 Subject: [PATCH 457/630] Drop 1.4 locally; bump 1.9 to Alpha 17 --- project.clj | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/project.clj b/project.clj index 4f813347..0da34570 100644 --- a/project.clj +++ b/project.clj @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-alpha14"] + :dependencies [[org.clojure/clojure "1.9.0-alpha17"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj @@ -30,8 +30,7 @@ ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"]] - :profiles {:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} - :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} + :profiles {:1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} @@ -41,6 +40,6 @@ :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/" "ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"} ;; include dev profile with 1.9 to pull in test.check - :aliases {"test-all" ["with-profile" "test,1.4:test,1.5:test,1.6:test,1.7:test,1.8:dev,test,1.9" "test"] - "check-all" ["with-profile" "1.4:1.5:1.6:1.7:1.8:1.9" "check"]} + :aliases {"test-all" ["with-profile" "test,1.5:test,1.6:test,1.7:test,1.8:dev,test,1.9" "test"] + "check-all" ["with-profile" "1.5:1.6:1.7:1.8:1.9" "check"]} :min-lein-version "2.0.0") From 04bdeb5f339a7e1af18d17b516ddbd977d0c2f90 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 28 Jun 2017 23:18:26 -0700 Subject: [PATCH 458/630] Note that Clojure 1.4.0 is no longer supported --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 3eb41597..18072d26 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.0-beta1 +* Support for Clojure 1.4.0 has been dropped -- breaking change. * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce`): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) Changes in 0.7.0-alpha3 From c924876e9fa0ece9631657831fd965dc980bf830 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 28 Jun 2017 23:42:20 -0700 Subject: [PATCH 459/630] 0.7.0 Beta 1 -- still need to update specs for reducible functions --- CHANGES.md | 2 +- README.md | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 18072d26..c8a28adc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.0-beta1 +Changes in 0.7.0-beta1 * Support for Clojure 1.4.0 has been dropped -- breaking change. * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce`): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) diff --git a/README.md b/README.md index d714cef2..40df7a6d 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-alpha3 +Latest stable release: 0.7.0-beta1 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-alpha3 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-alpha3"] +[org.clojure/java.jdbc "0.7.0-beta1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-alpha3 + 0.7.0-beta1 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -132,6 +132,10 @@ Developer Information Change Log ==================== +Release 0.7.0-beta1 on 2017-06-28 + * Support for Clojure 1.4.0 has been dropped -- breaking change. + * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce`): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) + Release 0.7.0-alpha3 on 2017-03-23 * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. From 5605da2fca366af1499ddb87e9884179a998c51b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 29 Jun 2017 00:02:12 -0700 Subject: [PATCH 460/630] Fix tests for spec.alpha --- src/main/clojure/clojure/java/jdbc/spec.clj | 19 +++++++++++++++++-- src/test/clojure/clojure/java/test_jdbc.clj | 6 +++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index c751aa65..70ba78f5 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2016 Sean Corfield. All rights reserved. +;; Copyright (c) 2016-2017 Sean Corfield. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be @@ -14,7 +14,7 @@ (ns ^{:author "Sean Corfield" :doc "Optional specifications for use with Clojure 1.9 or later."} clojure.java.jdbc.spec - (:require [clojure.spec :as s] + (:require [clojure.spec.alpha :as s] [clojure.java.jdbc :as sql])) ;; basic java.sql types -- cannot be generated! @@ -172,6 +172,10 @@ ::identifiers ::qualifier ::as-arrays? ::read-columns])) +(s/def ::reducible-query-options (s/keys :req-un [] + :opt-un [::identifiers ::qualifier + ::read-columns])) + ;; the function API (s/def ::naming-strategy (s/fspec :args (s/cat :x ::identifier) @@ -279,6 +283,17 @@ :opts (s/? ::query-options)) :ret any?) +(s/fdef sql/reducible-result-set + :args (s/cat :rs ::result-set + :opts (s/? ::reducible-query-options)) + :ret any?) + +(s/fdef sql/reducible-query + :args (s/cat :db ::db-spec + :sql-params ::sql-params + :opts (s/? ::reducible-query-options)) + :ret any?) + (s/fdef sql/find-by-keys :args (s/cat :db ::db-spec :table ::identifier diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 75628336..1b60d7b3 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -27,11 +27,11 @@ (def with-spec? (try (require 'clojure.java.jdbc.spec) - (require 'clojure.spec.test) + (require 'clojure.spec.test.alpha) ;; require this to workaround rebinding of report multi-fn (require 'clojure.test.check.clojure-test) - (let [syms ((resolve 'clojure.spec.test/enumerate-namespace) 'clojure.java.jdbc)] - ((resolve 'clojure.spec.test/instrument) syms)) + (let [syms ((resolve 'clojure.spec.test.alpha/enumerate-namespace) 'clojure.java.jdbc)] + ((resolve 'clojure.spec.test.alpha/instrument) syms)) (println "Instrumenting clojure.java.jdbc with clojure.spec") true (catch Exception _ From 74249d8899a3b270aeded15f105ce5bc9c317c0e Mon Sep 17 00:00:00 2001 From: puredanger Date: Thu, 29 Jun 2017 11:31:31 -0500 Subject: [PATCH 461/630] set clojure build level --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index 664273ce..9db5bdf5 100644 --- a/pom.xml +++ b/pom.xml @@ -27,6 +27,10 @@ HEAD + + 1.5.1 + + From d63e1db19825612c4d3414456f8bbc4df1c23e3b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 29 Jun 2017 09:36:54 -0700 Subject: [PATCH 462/630] For 1.7+ use clojure.lang.IReduce; else use CollReduce --- src/main/clojure/clojure/java/jdbc.clj | 151 ++++++++++++++------ src/test/clojure/clojure/java/test_jdbc.clj | 13 ++ 2 files changed, 117 insertions(+), 47 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 0e6e0d6f..a9fcfcd4 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -965,53 +965,110 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (result-set-seq rset opts))) opts)))) -(defn reducible-result-set - "Given a java.sql.ResultSet return a reducible collection. - Note: :as-arrays? is not accepted here." - [^ResultSet rs {:keys [identifiers qualifier read-columns] - :or {identifiers str/lower-case - read-columns dft-read-columns}}] - (reify clojure.core.protocols.CollReduce - (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) - (coll-reduce [this f init] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - identifier-fn (if qualifier - (comp (partial keyword qualifier) identifiers) - (comp keyword identifiers)) - keys (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - (make-cols-unique) - (mapv identifier-fn))] - (loop [init' init] - (if (.next rs) - (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] - (if (reduced? result) - @result - (recur result))) - init')))))) - -(defn reducible-query - "Given a database connection, a vector containing SQL and optional parameters, - return a reducible collection. When reduced, it will start the database query - and reduce the result set, and then close the connection. The following options - from query etc are not accepted here: - :as-arrays? :explain :explain-fn :result-set-fn :row-fn - See also prepare-statement for additional options." - ([db sql-params] (reducible-query db sql-params {})) - ([db sql-params opts] - (let [{:keys [reducing-fn] :as opts} - (merge {:identifiers str/lower-case :read-columns dft-read-columns} - (when (map? db) db) - opts) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (reify clojure.core.protocols.CollReduce - (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) - (coll-reduce [this f init] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts))))))))) +(if (and (>= (:major *clojure-version*) 1) (>= (:minor *clojure-version*) 7)) + (do + (defn reducible-result-set + "Given a java.sql.ResultSet return a reducible collection. + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + Note: :as-arrays? is not accepted here." + [^ResultSet rs {:keys [identifiers qualifier read-columns] + :or {identifiers str/lower-case + read-columns dft-read-columns}}] + (reify clojure.lang.IReduce + (reduce [this f] (.reduce this f (f))) + (reduce [this f init] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + identifier-fn (if qualifier + (comp (partial keyword qualifier) identifiers) + (comp keyword identifiers)) + keys (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + (make-cols-unique) + (mapv identifier-fn))] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init')))))) + + (defn reducible-query + "Given a database connection, a vector containing SQL and optional parameters, + return a reducible collection. When reduced, it will start the database query + and reduce the result set, and then close the connection: + (transduce (map :cost) + (reducible-query db sql-params)) + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + The following options from query etc are not accepted here: + :as-arrays? :explain :explain-fn :result-set-fn :row-fn + See also prepare-statement for additional options." + ([db sql-params] (reducible-query db sql-params {})) + ([db sql-params opts] + (let [{:keys [reducing-fn] :as opts} + (merge {:identifiers str/lower-case :read-columns dft-read-columns} + (when (map? db) db) + opts) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (reify clojure.lang.IReduce + (reduce [this f] (.reduce this f (f))) + (reduce [this f init] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f init (reducible-result-set rset opts)))))))))) + + (do ;; for backward compatibility thru 1.5.1 use CollReduce + (defn reducible-result-set + "Given a java.sql.ResultSet return a reducible collection. + Compiled with Clojure 1.5 or 1.6 -- uses clojure.core.protocols.CollReduce + Note: :as-arrays? is not accepted here." + [^ResultSet rs {:keys [identifiers qualifier read-columns] + :or {identifiers str/lower-case + read-columns dft-read-columns}}] + (reify clojure.core.protocols.CollReduce + (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) + (coll-reduce [this f init] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + identifier-fn (if qualifier + (comp (partial keyword qualifier) identifiers) + (comp keyword identifiers)) + keys (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + (make-cols-unique) + (mapv identifier-fn))] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init')))))) + + (defn reducible-query + "Given a database connection, a vector containing SQL and optional parameters, + return a reducible collection. When reduced, it will start the database query + and reduce the result set, and then close the connection: + (transduce (map :cost) + (reducible-query db sql-params)) + Compiled with Clojure 1.5 or 1.6 -- uses clojure.core.protocols.CollReduce + The following options from query etc are not accepted here: + :as-arrays? :explain :explain-fn :result-set-fn :row-fn + See also prepare-statement for additional options." + ([db sql-params] (reducible-query db sql-params {})) + ([db sql-params opts] + (let [{:keys [reducing-fn] :as opts} + (merge {:identifiers str/lower-case :read-columns dft-read-columns} + (when (map? db) db) + opts) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (reify clojure.core.protocols.CollReduce + (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) + (coll-reduce [this f init] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f init (reducible-result-set rset opts))))))))))) (defn- direction "Given an entities function, a column name, and a direction, diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 1b60d7b3..9b22dbae 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -437,9 +437,22 @@ (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))) (is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]})))) (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))) + ;; reduce with init (is (= 366 (reduce (fn [n r] (+ n (:cost r))) 0 (sql/reducible-query db "SELECT * FROM fruit")))) + ;; reduce without init + (is (= 366 (reduce (fn ([] 0) ([n r] (+ n (:cost r)))) + (sql/reducible-query db "SELECT * FROM fruit")))) + ;; plain old into + (is (= 4 (count (into [] (sql/reducible-query db "SELECT * FROM fruit"))))) (when-let [transduce-fn (resolve 'clojure.core/transduce)] + ;; transducing into + (is (= [29 59 139 139] + (into [] (map :cost) (sql/reducible-query + db + (str "SELECT * FROM fruit" + " ORDER BY cost"))))) + ;; transduce without init (is (= 366 (transduce-fn (map :cost) + (sql/reducible-query db "SELECT * FROM fruit"))))))) From fd6724ffb17ca0969eb2f46ec642268088cbfc0e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 29 Jun 2017 09:39:21 -0700 Subject: [PATCH 463/630] Update changes for IReduce/CollReduce split --- CHANGES.md | 2 +- README.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c8a28adc..8a263a46 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,7 @@ Changes in 0.7.0-beta1 * Support for Clojure 1.4.0 has been dropped -- breaking change. -* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce`): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) +* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) Changes in 0.7.0-alpha3 diff --git a/README.md b/README.md index 40df7a6d..1ea5d978 100644 --- a/README.md +++ b/README.md @@ -132,9 +132,9 @@ Developer Information Change Log ==================== -Release 0.7.0-beta1 on 2017-06-28 +Release 0.7.0-beta1 on 2017-06-29 * Support for Clojure 1.4.0 has been dropped -- breaking change. - * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce`): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) + * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) Release 0.7.0-alpha3 on 2017-03-23 * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). From 27ce33ee98fa5898e0427bf1f18150e361decacf Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 29 Jun 2017 11:58:48 -0500 Subject: [PATCH 464/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-beta1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9db5bdf5..24ccb747 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-beta1 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-beta1 From 464cd8d56d65e3fb5cbc59f6e4524722b707b931 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 29 Jun 2017 11:58:48 -0500 Subject: [PATCH 465/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 24ccb747..9db5bdf5 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-beta1 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-beta1 + HEAD From 43923b58352e9c32489dc7463c8da54ec3a66deb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 29 Jun 2017 16:58:41 -0700 Subject: [PATCH 466/630] Prep for 0.7.0-beta2 dropping Clojure 1.5 and 1.6; implementing IReduce properly --- CHANGES.md | 7 +- pom.xml | 2 +- project.clj | 8 +- src/main/clojure/clojure/java/jdbc.clj | 172 ++++++++------------ src/test/clojure/clojure/java/test_jdbc.clj | 66 ++++++-- 5 files changed, 129 insertions(+), 126 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 8a263a46..3a16fd37 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,12 @@ +Changes coming in 0.7.0-beta2 + +* Support for Clojure 1.6.0 and earlier has been dropped -- breaking change. +* `reducible-query` and `reducible-result-set` use `IReduce` and correctly support the no-`init` arity of `reduce` by using the first row of the `ResultSet`, if present, as the (missing) `init` value, and only calling `f` with no arguments if the `ResultSet` is empty. The `init` arity of `reduce` only ever calls `f` with two arguments. + Changes in 0.7.0-beta1 * Support for Clojure 1.4.0 has been dropped -- breaking change. -* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) +* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). Changes in 0.7.0-alpha3 diff --git a/pom.xml b/pom.xml index 9db5bdf5..1c5d895c 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ - 1.5.1 + 1.7.0 diff --git a/project.clj b/project.clj index 0da34570..61d8a120 100644 --- a/project.clj +++ b/project.clj @@ -30,9 +30,7 @@ ;; if you have the MS driver in your local repo [sqljdbc4 "4.0"]] - :profiles {:1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} - :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} - :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} + :profiles {:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} :dev {:dependencies [[org.clojure/test.check "0.9.0"]]}} @@ -40,6 +38,6 @@ :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/" "ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"} ;; include dev profile with 1.9 to pull in test.check - :aliases {"test-all" ["with-profile" "test,1.5:test,1.6:test,1.7:test,1.8:dev,test,1.9" "test"] - "check-all" ["with-profile" "1.5:1.6:1.7:1.8:1.9" "check"]} + :aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"] + "check-all" ["with-profile" "1.7:1.8:1.9" "check"]} :min-lein-version "2.0.0") diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a9fcfcd4..f7d5f474 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -965,110 +965,74 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (result-set-seq rset opts))) opts)))) -(if (and (>= (:major *clojure-version*) 1) (>= (:minor *clojure-version*) 7)) - (do - (defn reducible-result-set - "Given a java.sql.ResultSet return a reducible collection. - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce - Note: :as-arrays? is not accepted here." - [^ResultSet rs {:keys [identifiers qualifier read-columns] - :or {identifiers str/lower-case - read-columns dft-read-columns}}] - (reify clojure.lang.IReduce - (reduce [this f] (.reduce this f (f))) - (reduce [this f init] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - identifier-fn (if qualifier - (comp (partial keyword qualifier) identifiers) - (comp keyword identifiers)) - keys (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - (make-cols-unique) - (mapv identifier-fn))] - (loop [init' init] - (if (.next rs) - (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] - (if (reduced? result) - @result - (recur result))) - init')))))) - - (defn reducible-query - "Given a database connection, a vector containing SQL and optional parameters, - return a reducible collection. When reduced, it will start the database query - and reduce the result set, and then close the connection: - (transduce (map :cost) + (reducible-query db sql-params)) - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce - The following options from query etc are not accepted here: - :as-arrays? :explain :explain-fn :result-set-fn :row-fn - See also prepare-statement for additional options." - ([db sql-params] (reducible-query db sql-params {})) - ([db sql-params opts] - (let [{:keys [reducing-fn] :as opts} - (merge {:identifiers str/lower-case :read-columns dft-read-columns} - (when (map? db) db) - opts) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (reify clojure.lang.IReduce - (reduce [this f] (.reduce this f (f))) - (reduce [this f init] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts)))))))))) - - (do ;; for backward compatibility thru 1.5.1 use CollReduce - (defn reducible-result-set - "Given a java.sql.ResultSet return a reducible collection. - Compiled with Clojure 1.5 or 1.6 -- uses clojure.core.protocols.CollReduce - Note: :as-arrays? is not accepted here." - [^ResultSet rs {:keys [identifiers qualifier read-columns] - :or {identifiers str/lower-case - read-columns dft-read-columns}}] - (reify clojure.core.protocols.CollReduce - (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) - (coll-reduce [this f init] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - identifier-fn (if qualifier - (comp (partial keyword qualifier) identifiers) - (comp keyword identifiers)) - keys (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - (make-cols-unique) - (mapv identifier-fn))] - (loop [init' init] - (if (.next rs) - (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] - (if (reduced? result) - @result - (recur result))) - init')))))) - - (defn reducible-query - "Given a database connection, a vector containing SQL and optional parameters, - return a reducible collection. When reduced, it will start the database query - and reduce the result set, and then close the connection: - (transduce (map :cost) + (reducible-query db sql-params)) - Compiled with Clojure 1.5 or 1.6 -- uses clojure.core.protocols.CollReduce - The following options from query etc are not accepted here: - :as-arrays? :explain :explain-fn :result-set-fn :row-fn - See also prepare-statement for additional options." - ([db sql-params] (reducible-query db sql-params {})) - ([db sql-params opts] - (let [{:keys [reducing-fn] :as opts} - (merge {:identifiers str/lower-case :read-columns dft-read-columns} - (when (map? db) db) - opts) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (reify clojure.core.protocols.CollReduce - (coll-reduce [this f] (clojure.core.protocols/coll-reduce this f (f))) - (coll-reduce [this f init] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts))))))))))) +(defn reducible-result-set + "Given a java.sql.ResultSet return a reducible collection. + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + Note: :as-arrays? is not accepted here." + [^ResultSet rs {:keys [identifiers qualifier read-columns] + :or {identifiers str/lower-case + read-columns dft-read-columns}}] + (let [identifier-fn (if qualifier + (comp (partial keyword qualifier) identifiers) + (comp keyword identifiers)) + make-keys (fn [idxs rsmeta] + (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + (make-cols-unique) + (mapv identifier-fn))) + init-reduce (fn [keys rs rsmeta idxs f init] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init')))] + (reify clojure.lang.IReduce + (reduce [this f] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (make-keys idxs rsmeta)] + (if (.next rs) + ;; reduce init is first row of ResultSet + (init-reduce keys rs rsmeta idxs f + (zipmap keys (read-columns rs rsmeta idxs))) + ;; no rows so call 0-arity f to get result value + ;; per reduce docstring contract + (f)))) + (reduce [this f init] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (make-keys idxs rsmeta)] + (init-reduce keys rs rsmeta idxs f init)))))) + +(defn reducible-query + "Given a database connection, a vector containing SQL and optional parameters, + return a reducible collection. When reduced, it will start the database query + and reduce the result set, and then close the connection: + (transduce (map :cost) + (reducible-query db sql-params)) + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + The following options from query etc are not accepted here: + :as-arrays? :explain :explain-fn :result-set-fn :row-fn + See also prepare-statement for additional options." + ([db sql-params] (reducible-query db sql-params {})) + ([db sql-params opts] + (let [{:keys [reducing-fn] :as opts} + (merge {:identifiers str/lower-case :read-columns dft-read-columns} + (when (map? db) db) + opts) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (reify clojure.lang.IReduce + (reduce [this f] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f (reducible-result-set rset opts))))) + (reduce [this f init] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f init (reducible-result-set rset opts))))))))) (defn- direction "Given an entities function, a column name, and a direction, diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 9b22dbae..7c0c4bb0 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -438,23 +438,59 @@ (is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]})))) (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))) ;; reduce with init - (is (= 366 (reduce (fn [n r] (+ n (:cost r))) 0 + (is (= 466 (reduce (fn [n r] (+ n (:cost r))) 100 (sql/reducible-query db "SELECT * FROM fruit")))) - ;; reduce without init - (is (= 366 (reduce (fn ([] 0) ([n r] (+ n (:cost r)))) - (sql/reducible-query db "SELECT * FROM fruit")))) - ;; plain old into + ;; reduce without init -- uses first row as init! + (is (= 366 + (:cost (reduce (fn + ([] (throw (ex-info "I should not be called!" {}))) + ([m r] (update-in m [:cost] + (:cost r)))) + (sql/reducible-query db "SELECT * FROM fruit"))))) + ;; verify reduce without init on empty rs calls 0-arity only + (is (= "Zero-arity!" + (reduce (fn + ([] "Zero-arity!") + ([m r] (throw (ex-info "I should not be called!" + {:m m :r r})))) + (sql/reducible-query db "SELECT * FROM fruit WHERE ID = -99")))) + ;; verify reduce with init does not call f for empty rs + (is (= "Unchanged!" + (reduce (fn + ([] (throw (ex-info "I should not be called!" {}))) + ([m r] (throw (ex-info "I should not be called!" + {:m m :r r})))) + "Unchanged!" + (sql/reducible-query db "SELECT * FROM fruit WHERE ID = -99")))) + ;; verify reduce without init does not call f if only one row is in the rs + (is (= "Orange" + (:name (reduce (fn + ([] (throw (ex-info "I should not be called!" {}))) + ([m r] (throw (ex-info "I should not be called!" + {:m m :r r})))) + (sql/reducible-query db "SELECT * FROM fruit WHERE ID = 4"))))) + ;; verify reduce with init does not call 0-arity f and + ;; only calls 2-arity f once if only one row is in the rs + (is (= 239 + (reduce (fn + ([] (throw (ex-info "I should not be called!" {}))) + ;; cannot be called on its own result: + ([m r] (+ (:a m) (:cost r)))) + {:a 100} + (sql/reducible-query db "SELECT * FROM fruit WHERE ID = 4")))) + ;; plain old into (uses (reduce conj coll) behind the scenes) (is (= 4 (count (into [] (sql/reducible-query db "SELECT * FROM fruit"))))) - (when-let [transduce-fn (resolve 'clojure.core/transduce)] - ;; transducing into - (is (= [29 59 139 139] - (into [] (map :cost) (sql/reducible-query - db - (str "SELECT * FROM fruit" - " ORDER BY cost"))))) - ;; transduce without init - (is (= 366 (transduce-fn (map :cost) + - (sql/reducible-query db "SELECT * FROM fruit"))))))) + ;; transducing into + (is (= [29 59 139 139] + (into [] + (map :cost) + (sql/reducible-query db (str "SELECT * FROM fruit" + " ORDER BY cost"))))) + ;; transduce without init (calls (+) to get init value) + (is (= 366 (transduce (map :cost) + + (sql/reducible-query db "SELECT * FROM fruit")))) + ;; transduce with init + (is (= 466 (transduce (map :cost) + 100 + (sql/reducible-query db "SELECT * FROM fruit")))))) (deftest test-insert-values (doseq [db (test-specs)] From 412ff6b6091a833c76334ce6221305b23d6c3d6c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 30 Jun 2017 14:52:16 -0700 Subject: [PATCH 467/630] Complete specs; prepare 0.7.0-beta2 --- CHANGES.md | 5 +- README.md | 15 +++-- src/main/clojure/clojure/java/jdbc/spec.clj | 55 +++++++++++++++--- src/test/clojure/clojure/java/test_jdbc.clj | 64 ++++++++++++--------- 4 files changed, 99 insertions(+), 40 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3a16fd37..c40a5452 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,11 +1,14 @@ -Changes coming in 0.7.0-beta2 +Changes in 0.7.0-beta2 * Support for Clojure 1.6.0 and earlier has been dropped -- breaking change. +* Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later! +* All public functions now have specs in the optional `clojure.java.jdbc.spec` namespace (requires `clojure.spec.alpha`). * `reducible-query` and `reducible-result-set` use `IReduce` and correctly support the no-`init` arity of `reduce` by using the first row of the `ResultSet`, if present, as the (missing) `init` value, and only calling `f` with no arguments if the `ResultSet` is empty. The `init` arity of `reduce` only ever calls `f` with two arguments. Changes in 0.7.0-beta1 * Support for Clojure 1.4.0 has been dropped -- breaking change. +* Optional spec support now uses `clojure.spec.alpha`. * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). Changes in 0.7.0-alpha3 diff --git a/README.md b/README.md index 1ea5d978..937deec0 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-beta1 +Latest stable release: 0.7.0-beta2 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-beta1 [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-beta1"] +[org.clojure/java.jdbc "0.7.0-beta2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-beta1 + 0.7.0-beta2 ``` You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: @@ -132,9 +132,16 @@ Developer Information Change Log ==================== +Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2) + * Support for Clojure 1.5 and 1.6 has been dropped -- breaking change. + * Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later! + * All public functions now have specs in the optional `clojure.java.jdbc.spec` namespace (requires `clojure.spec.alpha`). + * `reducible-query` and `reducible-result-set` use `IReduce` and correctly support the no-`init` arity of `reduce` by using the first row of the `ResultSet`, if present, as the (missing) `init` value, and only calling `f` with no arguments if the `ResultSet` is empty. The `init` arity of `reduce` only ever calls `f` with two arguments. + Release 0.7.0-beta1 on 2017-06-29 * Support for Clojure 1.4.0 has been dropped -- breaking change. - * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99) + * Optional spec support now uses `clojure.spec.alpha`. + * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). Release 0.7.0-alpha3 on 2017-03-23 * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 70ba78f5..73af9aa4 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -30,7 +30,7 @@ (s/def ::subprotocol-base #{"derby" "h2" "hsqldb" "jtds:sqlserver" "mysql" "oracle:oci" "oracle:thin" "pgsql" "postgresql" - "sqlite" "sqlserver"}) + "redshift" "sqlite" "sqlserver"}) (s/def ::subprotocol-alias #{"hsql" "jtds" "mssql" "oracle" "postgres"}) ;; technically :subprotocol can be any string... (s/def ::subprotocol string?) @@ -269,13 +269,34 @@ :args (s/cat :meta-query any? :opt-args (s/? any?))) -;; db-do-commands +(s/fdef sql/db-do-commands + :args (s/cat :db ::db-spec + :transaction? (s/? boolean?) + :sql-commands (s/or :command string? + :commands (s/coll-of string?))) + :ret any?) -;; db-do-prepared-return-keys -- can have both execute options and query options! +(s/fdef sql/db-do-prepared-return-keys + :args (s/cat :db ::db-spec + :transaction? (s/? boolean?) + :sql-params ::sql-params + :opts (s/? (s/merge ::execute-options ::query-options))) + :ret any?) -;; db-do-prepared +(s/fdef sql/db-do-prepared + :args (s/cat :db ::db-spec + :transaction? (s/? boolean?) + :sql-params ::sql-params + ;; TODO: this set of options needs reviewing: + :opts (s/? (s/merge ::execute-options ::query-options))) + :ret any?) -;; db-query-with-resultset +(s/fdef sql/db-query-with-resultset + :args (s/cat :db ::db-spec + :sql-params ::sql-params + :func ifn? + :opts (s/? ::query-options)) + :ret any?) (s/fdef sql/query :args (s/cat :db ::db-spec @@ -322,9 +343,29 @@ :opts (s/? ::exec-sql-options)) :ret ::execute-result) -;; insert! -- can have both execute options and query options! +(s/fdef sql/insert! + :args (s/or :row (s/cat :db ::db-spec + :table ::identifier + :row (s/map-of ::identifier any?) + :opts (s/? (s/merge ::execute-options ::query-options))) + :cvs (s/cat :db ::db-spec + :table ::identifier + :cols (s/nilable (s/coll-of ::identifier)) + :vals (s/coll-of any?) + :opts (s/? (s/merge ::execute-options ::query-options)))) + :ret any?) -;; insert-multi! -- can have both execute options and query options! +(s/fdef sql/insert-multi! + :args (s/or :rows (s/cat :db ::db-spec + :table ::identifier + :rows (s/coll-of (s/map-of ::identifier any?)) + :opts (s/? (s/merge ::execute-options ::query-options))) + :cvs (s/cat :db ::db-spec + :table ::identifier + :cols (s/nilable (s/coll-of ::identifier)) + :vals (s/coll-of (s/coll-of any?)) + :opts (s/? (s/merge ::execute-options ::query-options)))) + :ret any?) (s/fdef sql/update! :args (s/cat :db ::db-spec diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 7c0c4bb0..d5792332 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -683,56 +683,64 @@ (catch Exception _ (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))))) +(defmacro illegal-arg-or-spec + "Execute a form in the context of a try/catch that verifies either + IllegalArgumentException was thrown or a spec violation occurred + so that we can test transparently across Clojure 1.7 to 1.9+." + [fn-name & body] + `(try + ~@body + (is false (str "Illegal arguments to " ~fn-name " were not detected!")) + (catch IllegalArgumentException _#) + (catch clojure.lang.ExceptionInfo e# + (is (re-find #"did not conform to spec" (.getMessage e#)))))) + (deftest test-sql-exception (doseq [db (test-specs)] (create-test-table :fruit db) - (try + (illegal-arg-or-spec "insert!" (sql/with-db-transaction [t-conn db] (sql/insert! t-conn :fruit [:name :appearance] - ["Apple" "strange" "whoops"])) - (catch IllegalArgumentException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + ["Apple" "strange" "whoops"]))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-sql-exception-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) - (try + (illegal-arg-or-spec "insert!" (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] (sql/insert! t-conn :fruit [:name :appearance] - ["Apple" "strange" "whoops"])) - (catch IllegalArgumentException _ - (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) + ["Apple" "strange" "whoops"]))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-insert-values-exception (doseq [db (test-specs)] (create-test-table :fruit db) - (is (thrown? IllegalArgumentException - (sql/with-db-transaction [t-conn db] - (sql/insert-multi! t-conn - :fruit - [:name :appearance] - [["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]])))) + (illegal-arg-or-spec "insert-multi!" + (sql/with-db-transaction [t-conn db] + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]]))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-insert-values-exception-with-isolation (doseq [db (test-specs)] (create-test-table :fruit db) - (is (thrown? IllegalArgumentException - (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] - (sql/insert-multi! t-conn - :fruit - [:name :appearance] - [["Grape" "yummy"] - ["Pear" "bruised"] - ["Apple" "strange" "whoops"]])))) + (illegal-arg-or-spec + (sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}] + (sql/insert-multi! t-conn + :fruit + [:name :appearance] + [["Grape" "yummy"] + ["Pear" "bruised"] + ["Apple" "strange" "whoops"]]))) (is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))) (deftest test-rollback @@ -1029,10 +1037,10 @@ (deftest illegal-insert-arguments (doseq [db (test-specs)] - (is (thrown? IllegalArgumentException (sql/insert! db))) - (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name]))) - (is (thrown? IllegalArgumentException (sql/insert! db {:name "Apple"} [:name] {:entities identity}))) - (is (thrown? IllegalArgumentException (sql/insert! db [:name]))) + (illegal-arg-or-spec "insert!" (sql/insert! db)) + (illegal-arg-or-spec "insert!" (sql/insert! db {:name "Apple"} [:name])) + (illegal-arg-or-spec "insert!" (sql/insert! db {:name "Apple"} [:name] {:entities identity})) + (illegal-arg-or-spec "insert!" (sql/insert! db [:name])) (if with-spec? ; clojure.spec catches this differently (is (thrown? clojure.lang.ExceptionInfo (sql/insert! db [:name] {:entities identity}))) (is (thrown? ClassCastException (sql/insert! db [:name] {:entities identity})))))) From 9773355d10ec0418235c4233c1368abcd881d898 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 30 Jun 2017 15:10:54 -0700 Subject: [PATCH 468/630] Clarification of Clojure version support --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 937deec0..dfeeaa04 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-beta2 +Latest stable release: 0.7.0-beta2 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -34,6 +34,8 @@ Latest stable release: 0.7.0-beta2 0.7.0-beta2 ``` +_Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ + You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: * [Apache Derby](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.derby%22%20AND%20a%3A%22derby%22) @@ -46,7 +48,7 @@ You will also need to add dependencies for the JDBC driver you intend to use. He Note: different versions of various database drivers have different Java/JVM version requirements. In particular, recent versions of Apache Derby require at least Java 8 and recent versions of H2 require at least Java 7. Clojure's Continuous Integration system uses older versions so tests can be run on Java 6 (see `pom.xml`); local testing is done with more recent versions on Java 8. -clojure.java.jdbc is also tested against Microsoft's own JDBC4 Driver 4.0 but that +`clojure.java.jdbc` is also tested against Microsoft's own JDBC4 Driver 4.0 but that has to be [downloaded manually](https://www.microsoft.com/en-us/download/details.aspx?id=11774) and placed in a Maven repository accessible to your system. For testing, it was installed locally as: ```clojure ;; Microsoft SQL Server JDBC4 Driver 4.0 From ef0b4cc6cd7c663d16eda2531eda891d3c481a2f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 30 Jun 2017 17:12:06 -0500 Subject: [PATCH 469/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-beta2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1c5d895c..d964c6ee 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-beta2 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-beta2 From 8f32b6b964d60e03ea78b7759a2f2d141fa30d66 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 30 Jun 2017 17:12:06 -0500 Subject: [PATCH 470/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d964c6ee..1c5d895c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-beta2 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-beta2 + HEAD From 877e4e1050e89dbb7c082e343e13a19876a69747 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 3 Jul 2017 10:47:46 -0700 Subject: [PATCH 471/630] Fix reflection warnings JDBC-152 --- CHANGES.md | 4 ++++ project.clj | 3 +-- src/main/clojure/clojure/java/jdbc.clj | 7 ++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c40a5452..3cb7cd19 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.0 + +* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). + Changes in 0.7.0-beta2 * Support for Clojure 1.6.0 and earlier has been dropped -- breaking change. diff --git a/project.clj b/project.clj index 61d8a120..c582843c 100644 --- a/project.clj +++ b/project.clj @@ -38,6 +38,5 @@ :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/" "ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"} ;; include dev profile with 1.9 to pull in test.check - :aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"] - "check-all" ["with-profile" "1.7:1.8:1.9" "check"]} + :aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"]} :min-lein-version "2.0.0") diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f7d5f474..13368efc 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -45,7 +45,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} [clojure.walk :as walk]) (:import (java.net URI) (java.sql BatchUpdateException DriverManager - PreparedStatement ResultSet SQLException Statement Types) + PreparedStatement ResultSet ResultSetMetaData + SQLException Statement Types) (java.util Hashtable Map Properties) (javax.sql DataSource))) @@ -975,12 +976,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [identifier-fn (if qualifier (comp (partial keyword qualifier) identifiers) (comp keyword identifiers)) - make-keys (fn [idxs rsmeta] + make-keys (fn [idxs ^ResultSetMetaData rsmeta] (->> idxs (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) (make-cols-unique) (mapv identifier-fn))) - init-reduce (fn [keys rs rsmeta idxs f init] + init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init] (loop [init' init] (if (.next rs) (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] From 4bc29598e0e23ff768986adfed72e216dd8aa773 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 4 Jul 2017 19:39:22 -0700 Subject: [PATCH 472/630] Release 0.7.0-beta3 Fix reflection warnings; fix opts in reducible-query; clarify specs. --- CHANGES.md | 4 +++- README.md | 12 +++++++++--- src/main/clojure/clojure/java/jdbc.clj | 6 ++++-- src/main/clojure/clojure/java/jdbc/spec.clj | 18 ++++++++++-------- src/test/clojure/clojure/java/test_jdbc.clj | 5 +++-- 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3cb7cd19..606d8b1c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ -Changes coming in 0.7.0 +Changes in 0.7.0-beta3 * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). +* `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. +* Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there. Changes in 0.7.0-beta2 diff --git a/README.md b/README.md index dfeeaa04..418b99ba 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-beta2 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.0-beta3 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-beta2 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-beta2"] +[org.clojure/java.jdbc "0.7.0-beta3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-beta2 + 0.7.0-beta3 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -134,6 +134,12 @@ Developer Information Change Log ==================== +Release 0.7.0-beta3 on 2017-07-04 + + * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). + * `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. + * Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there. + Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2) * Support for Clojure 1.5 and 1.6 has been dropped -- breaking change. * Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later! diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 13368efc..9a31f7f4 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1028,12 +1028,14 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (db-query-with-resultset db sql-params-vector (^{:once true} fn* [rset] - (reduce f (reducible-result-set rset opts))))) + (reduce f (reducible-result-set rset opts))) + opts)) (reduce [this f init] (db-query-with-resultset db sql-params-vector (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts))))))))) + (reduce f init (reducible-result-set rset opts))) + opts)))))) (defn- direction "Given an entities function, a column name, and a direction, diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 73af9aa4..26d56167 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -167,14 +167,16 @@ (s/def ::transaction-options (s/keys :req-un [] :opt-un [::isolation ::read-only?])) -(s/def ::query-options (s/keys :req-un [] - :opt-un [::result-set-fn ::row-fn - ::identifiers ::qualifier - ::as-arrays? ::read-columns])) - -(s/def ::reducible-query-options (s/keys :req-un [] - :opt-un [::identifiers ::qualifier - ::read-columns])) +(s/def ::query-options (s/merge (s/keys :req-un [] + :opt-un [::result-set-fn ::row-fn + ::identifiers ::qualifier + ::as-arrays? ::read-columns]) + ::prepare-options)) + +(s/def ::reducible-query-options (s/merge (s/keys :req-un [] + :opt-un [::identifiers ::qualifier + ::read-columns]) + ::prepare-options)) ;; the function API diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index d5792332..f6dedf8d 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -437,9 +437,10 @@ (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))) (is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]})))) (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))) - ;; reduce with init + ;; reduce with init (and ensure we can pass :fetch-size through) (is (= 466 (reduce (fn [n r] (+ n (:cost r))) 100 - (sql/reducible-query db "SELECT * FROM fruit")))) + (sql/reducible-query db "SELECT * FROM fruit" + {:fetch-size 100})))) ;; reduce without init -- uses first row as init! (is (= 366 (:cost (reduce (fn From 424352f39d34c0d225f256e00b9daf4acea92e68 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 4 Jul 2017 21:41:21 -0500 Subject: [PATCH 473/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-beta3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1c5d895c..fde61b35 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-beta3 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-beta3 From cf8e05d16078fba70773d498740a1ee68f162d11 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 4 Jul 2017 21:41:21 -0500 Subject: [PATCH 474/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index fde61b35..1c5d895c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-beta3 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-beta3 + HEAD From 897d1707e6bc688bb0af4fd64a006d418ac4bb81 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 4 Jul 2017 19:43:47 -0700 Subject: [PATCH 475/630] Release 0.7.0-beta4 Corrected what was in beta 3 vs beta 4 --- CHANGES.md | 7 +++++-- README.md | 13 ++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 606d8b1c..2af5650e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,9 +1,12 @@ -Changes in 0.7.0-beta3 +Changes in 0.7.0-beta4 -* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). * `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. * Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there. +Changes in 0.7.0-beta3 + +* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). + Changes in 0.7.0-beta2 * Support for Clojure 1.6.0 and earlier has been dropped -- breaking change. diff --git a/README.md b/README.md index 418b99ba..7a8e5a34 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-beta3 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.0-beta4 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-beta3 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-beta3"] +[org.clojure/java.jdbc "0.7.0-beta4"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-beta3 + 0.7.0-beta4 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -134,12 +134,15 @@ Developer Information Change Log ==================== -Release 0.7.0-beta3 on 2017-07-04 +Release 0.7.0-beta4 on 2017-07-04 - * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). * `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. * Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there. +Release 0.7.0-beta3 on 2017-07-04 + + * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). + Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2) * Support for Clojure 1.5 and 1.6 has been dropped -- breaking change. * Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later! From b52b2396a38f599122a80d75b62cb1461be3ba1f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 4 Jul 2017 22:17:20 -0500 Subject: [PATCH 476/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-beta4 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1c5d895c..36241320 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-beta4 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-beta4 From cf1d153aaefa8fae7eaef0b19bb71d5f32aad47c Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 4 Jul 2017 22:17:20 -0500 Subject: [PATCH 477/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 36241320..1c5d895c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-beta4 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-beta4 + HEAD From 5471dd4f3123a460d8ea9a288e2a3d8c96be76ad Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 5 Jul 2017 14:17:54 -0700 Subject: [PATCH 478/630] JDBC-153 support :auto-commit? :read-only? on connections; improve option checking on prepare-statement --- CHANGES.md | 5 + src/main/clojure/clojure/java/jdbc.clj | 229 +++++++++++--------- src/main/clojure/clojure/java/jdbc/spec.clj | 16 +- src/test/clojure/clojure/java/test_jdbc.clj | 13 +- 4 files changed, 158 insertions(+), 105 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 2af5650e..2df10054 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes coming in 0.7.0-? + +* `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). +* Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`. + Changes in 0.7.0-beta4 * `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9a31f7f4..4537183b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -203,6 +203,17 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (list* 'do body)) (catch ClassNotFoundException _#))) +(defn- modify-connection + "Given a database connection and a map of options, update the connection + as specified by the options." + ^java.sql.Connection + [^java.sql.Connection connection opts] + (when (contains? opts :auto-commit?) + (.setAutoCommit connection (:auto-commit? opts))) + (when (contains? opts :read-only?) + (.setReadOnly connection (:read-only? opts))) + connection) + (defn get-connection "Creates a connection to a database. db-spec is usually a map containing connection parameters but can also be a URI or a String. The various possibilities are described @@ -255,89 +266,100 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} java.lang.String: subprotocol://user:password@host:post/subname An optional prefix of jdbc: is allowed." - ^java.sql.Connection - [{:keys [connection - factory - connection-uri - classname subprotocol subname - dbtype dbname host port - datasource username password user - name environment] - :as db-spec}] - (cond - (string? db-spec) - (get-connection (URI. (strip-jdbc db-spec))) - - (instance? URI db-spec) - (get-connection (parse-properties-uri db-spec)) - - connection - connection - - (or (and datasource username password) - (and datasource user password)) - (.getConnection ^DataSource datasource ^String (or username user) ^String password) - - datasource - (.getConnection ^DataSource datasource) - - factory - (factory (dissoc db-spec :factory)) - - connection-uri - (DriverManager/getConnection connection-uri) - - (and dbtype dbname) - (let [;; allow aliases for dbtype - subprotocol (subprotocols dbtype dbtype) - host (or host "127.0.0.1") - port (or port (condp = subprotocol - "jtds:sqlserver" 1433 - "mysql" 3306 - "postgresql" 5432 - "sqlserver" 1433 - nil)) - db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") - url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) - (str "jdbc:" subprotocol ":" dbname) - (str "jdbc:" subprotocol "://" host - (when port (str ":" port)) - db-sep dbname)) - etc (dissoc db-spec :dbtype :dbname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) - (DriverManager/getConnection url (as-properties etc))) - - (and subprotocol subname) - (let [;; allow aliases for subprotocols - subprotocol (subprotocols subprotocol subprotocol) - url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) - (DriverManager/getConnection url (as-properties etc))) - - name - (or (when-available javax.naming.InitialContext - (let [env (and environment (Hashtable. ^Map environment)) - context (javax.naming.InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (.getConnection datasource))) - (throw (ex-info (str "javax.naming.InitialContext is not available for: " - name) - db-spec))) - - :else - (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] - (throw (IllegalArgumentException. msg))))) + (^java.sql.Connection [db-spec] (get-connection db-spec {})) + (^java.sql.Connection + [{:keys [connection + factory + connection-uri + classname subprotocol subname + dbtype dbname host port + datasource username password user + name environment] + :as db-spec} + opts] + (cond + (string? db-spec) + (get-connection (URI. (strip-jdbc db-spec)) opts) + + (instance? URI db-spec) + (get-connection (parse-properties-uri db-spec) opts) + + connection + connection ;; do not apply opts here + + (or (and datasource username password) + (and datasource user password)) + (-> (.getConnection ^DataSource datasource + ^String (or username user) + ^String password) + (modify-connection opts)) + + datasource + (-> (.getConnection ^DataSource datasource) + (modify-connection opts)) + + factory + (-> (factory (dissoc db-spec :factory)) + (modify-connection opts)) + + connection-uri + (-> (DriverManager/getConnection connection-uri) + (modify-connection opts)) + + (and dbtype dbname) + (let [;; allow aliases for dbtype + subprotocol (subprotocols dbtype dbtype) + host (or host "127.0.0.1") + port (or port (condp = subprotocol + "jtds:sqlserver" 1433 + "mysql" 3306 + "postgresql" 5432 + "sqlserver" 1433 + nil)) + db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") + url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) + (str "jdbc:" subprotocol ":" dbname) + (str "jdbc:" subprotocol "://" host + (when port (str ":" port)) + db-sep dbname)) + etc (dissoc db-spec :dbtype :dbname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + + (and subprotocol subname) + (let [;; allow aliases for subprotocols + subprotocol (subprotocols subprotocol subprotocol) + url (format "jdbc:%s:%s" subprotocol subname) + etc (dissoc db-spec :classname :subprotocol :subname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + + name + (or (when-available javax.naming.InitialContext + (let [env (and environment (Hashtable. ^Map environment)) + context (javax.naming.InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (-> (.getConnection datasource) + (modify-connection opts)))) + (throw (ex-info (str "javax.naming.InitialContext is not available for: " + name) + db-spec))) + + :else + (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] + (throw (IllegalArgumentException. msg)))))) (defn- make-name-unique "Given a collection of column names and a new column name, @@ -510,7 +532,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} :cursors :fetch-size n :max-rows n - :timeout n" + :timeout n + Note that :result-type and :concurrency must be specified together as the + underlying Java API expects both (or neither)." ([con sql] (prepare-statement con sql {})) ([^java.sql.Connection con ^String sql {:keys [return-keys result-type concurrency cursors @@ -518,6 +542,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [^PreparedStatement stmt (cond return-keys (try + (when (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified with :return-keys.")))) (if (vector? return-keys) (try (.prepareStatement con sql (string-array return-keys)) @@ -539,6 +567,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (get result-set-type result-type result-type) (get result-set-concurrency concurrency concurrency))) + (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified independently."))) :else (.prepareStatement con sql))] (when fetch-size (.setFetchSize stmt fetch-size)) @@ -692,7 +724,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (try (.setReadOnly con old-readonly) (catch Exception _))))))) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (db-transaction* (add-connection db con) func opts))) (do (when (and isolation @@ -719,11 +751,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defmacro with-db-connection "Evaluates body in the context of an active connection to the database. - (with-db-connection [con-db db-spec] + (with-db-connection [con-db db-spec opts] ... con-db ...)" [binding & body] - `(let [db-spec# ~(second binding)] - (with-open [con# (get-connection db-spec#)] + `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + (with-open [con# (get-connection db-spec# opts#)] (let [~(first binding) (add-connection db-spec# con#)] ~@body)))) @@ -731,12 +763,13 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "Evaluates body in the context of an active connection with metadata bound to the specified name. See also metadata-result for dealing with the results of operations that retrieve information from the metadata. - (with-db-metadata [md db-spec] + (with-db-metadata [md db-spec opts] ... md ...)" [binding & body] - `(with-open [con# (get-connection ~(second binding))] - (let [~(first binding) (.getMetaData con#)] - ~@body))) + `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (.getMetaData con#)] + ~@body)))) (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, @@ -843,7 +876,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) (defn- db-do-execute-prepared-statement @@ -885,7 +918,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) (defn db-query-with-resultset @@ -919,7 +952,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (if-let [con (db-find-connection db)] (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] (run-query-with-params stmt)) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] (run-query-with-params stmt)))))))) @@ -1116,7 +1149,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (db-do-prepared db transaction? sql-params opts))] (if-let [con (db-find-connection db)] (execute-helper db) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (execute-helper (add-connection db con))))))) (defn- delete-sql @@ -1212,7 +1245,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (insert-single-row-sql table row entities)) rows)] (if-let [con (db-find-connection db)] (insert-helper db transaction? sql-params opts) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (insert-helper (add-connection db con) transaction? sql-params opts))))) (defn- insert-cols! @@ -1225,7 +1258,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} sql-params (insert-multi-row-sql table cols values entities)] (if-let [con (db-find-connection db)] (db-do-prepared db transaction? sql-params (assoc opts :multi? true)) - (with-open [con (get-connection db)] + (with-open [con (get-connection db opts)] (db-do-prepared (add-connection db con) transaction? sql-params (assoc opts :multi? true)))))) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 26d56167..d531a857 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -100,6 +100,7 @@ ;; the corresponding options must either be omitted or given valid values (s/def ::as-arrays? (s/or :as-is #{:cols-as-is} :truthy (s/nilable boolean?))) +(s/def ::auto-commit? boolean?) (s/def ::concurrency (set (keys @#'sql/result-set-concurrency))) (s/def ::cursors (set (keys @#'sql/result-set-holdability))) (s/def ::fetch-size nat-int?) @@ -159,10 +160,14 @@ ::identifiers ::qualifier ::as-arrays? ::read-columns])) -(s/def ::prepare-options (s/keys :req-un [] - :opt-un [::return-keys ::result-type - ::concurrency ::cursors ::fetch-size - ::max-rows ::timeout])) +(s/def ::connection-options (s/keys :req-un [] + :opt-un [::auto-commit? ::read-only?])) + +(s/def ::prepare-options (s/merge (s/keys :req-un [] + :opt-un [::return-keys ::result-type + ::concurrency ::cursors ::fetch-size + ::max-rows ::timeout]) + ::connection-options)) (s/def ::transaction-options (s/keys :req-un [] :opt-un [::isolation ::read-only?])) @@ -196,7 +201,8 @@ :ret ::naming-strategy) (s/fdef sql/get-connection - :args (s/cat :db-spec ::db-spec) + :args (s/cat :db-spec ::db-spec + :opts (s/? ::connection-options)) :ret ::connection) (s/fdef sql/result-set-seq diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index f6dedf8d..eb35b68f 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -176,6 +176,11 @@ (re-find #"pgsql") (re-find #"pgsql" (or (:subprotocol db) (:dbtype db))))) +(defn- sqlite? [db] + (if (string? db) + (re-find #"sqlite:" db) + (= "sqlite" (or (:subprotocol db) (:dbtype db))))) + (defmulti create-test-table "Create a standard test table. Uses db-do-commands. For MySQL, ensure table uses an engine that supports transactions!" @@ -437,10 +442,14 @@ (is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139})))) (is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]})))) (is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]})))) - ;; reduce with init (and ensure we can pass :fetch-size through) + ;; reduce with init (and ensure we can pass :fetch-size & connection opts through) (is (= 466 (reduce (fn [n r] (+ n (:cost r))) 100 (sql/reducible-query db "SELECT * FROM fruit" - {:fetch-size 100})))) + (cond-> {:fetch-size 100} + (not (sqlite? db)) + (assoc :read-only? true) + (not (derby? db)) + (assoc :auto-commit? false)))))) ;; reduce without init -- uses first row as init! (is (= 366 (:cost (reduce (fn From f67550f3474ecb3a98545fa8ed9e1562cc516dcb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 5 Jul 2017 20:03:49 -0700 Subject: [PATCH 479/630] Release 0.7.0-beta5 Adds :auto-commit? and :read-only? for connection options. --- CHANGES.md | 2 +- README.md | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 2df10054..ca933969 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.0-? +Changes in 0.7.0-beta5 * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). * Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`. diff --git a/README.md b/README.md index 7a8e5a34..04662d56 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-beta4 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.0-beta5 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-beta4 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-beta4"] +[org.clojure/java.jdbc "0.7.0-beta5"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-beta4 + 0.7.0-beta5 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -134,6 +134,11 @@ Developer Information Change Log ==================== +Release 0.7.0-beta5 on 2017-07-05 + + * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). + * Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`. + Release 0.7.0-beta4 on 2017-07-04 * `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. From 7871f7bc1ef4d6109170fd1618ac6904281a3747 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 5 Jul 2017 22:05:18 -0500 Subject: [PATCH 480/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-btea5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1c5d895c..18b5a863 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-btea5 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-btea5 From 9b9ab112fc42632221dbf73d4e3b52b830a98277 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 5 Jul 2017 22:05:18 -0500 Subject: [PATCH 481/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 18b5a863..1c5d895c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-btea5 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-btea5 + HEAD From 425b629e91cfc0f7d13a1b80de410b4dc8329ed5 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 5 Jul 2017 22:23:15 -0500 Subject: [PATCH 482/630] [maven-release-plugin] prepare release java.jdbc-0.7.0-beta5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1c5d895c..fd02594f 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0-beta5 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0-beta5 From 75141ad7a3fdc028fac4db8e0721742bc166836f Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 5 Jul 2017 22:23:15 -0500 Subject: [PATCH 483/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index fd02594f..1c5d895c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-beta5 + 0.7.0-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0-beta5 + HEAD From ddec91da22987a0826706d9bc13ffe722cbc3601 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 13 Jul 2017 23:00:18 -0700 Subject: [PATCH 484/630] Add conditional? to create/drop DDL functions --- src/main/clojure/clojure/java/jdbc.clj | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 4537183b..a42bc6ef 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1360,6 +1360,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ([table specs] (create-table-ddl table specs {})) ([table specs opts] (let [table-spec (:table-spec opts) + conditional? (:conditional? opts) entities (:entities opts identity) table-spec-str (or (and table-spec (str " " table-spec)) "") spec-to-string (fn [spec] @@ -1369,7 +1370,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (catch Exception _ (throw (IllegalArgumentException. "column spec is not a sequence of keywords / strings")))))] - (format "CREATE TABLE %s (%s)%s" + (format "CREATE TABLE%s %s (%s)%s" + (if (boolean? conditional?) + (if conditional? " IF NOT EXISTS" "") + conditional?) (as-sql-name entities table) (str/join ", " (map spec-to-string specs)) table-spec-str)))) @@ -1377,5 +1381,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn drop-table-ddl "Given a table name, return the DDL string for dropping that table." ([name] (drop-table-ddl name {})) - ([name {:keys [entities] :or {entities identity}}] - (format "DROP TABLE %s" (as-sql-name entities name)))) + ([name {:keys [entities conditional?] :or {entities identity}}] + (format "DROP TABLE%s %s" + (if (boolean? conditional?) + (if conditional? " IF EXISTS" "") + conditional?) + (as-sql-name entities name)))) From 8c7bd87c99fe4d1554eca19d82bbce1ccabbf4bc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 16 Jul 2017 16:03:29 -0700 Subject: [PATCH 485/630] Release 0.7.0 Document and spec `:conditional?`; improve Oracle support. --- CHANGES.md | 5 ++ README.md | 11 ++- src/main/clojure/clojure/java/jdbc.clj | 76 +++++++++++++++------ src/main/clojure/clojure/java/jdbc/spec.clj | 20 ++++-- 4 files changed, 84 insertions(+), 28 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index ca933969..c06b6780 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +Changes in 0.7.0 + +* `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL). +* Add better support for Oracle connections (default port to `1521`, support `:dbtype "oracle"` -- as `"oracle:thin"` -- and `:dbtype "oracle:oci"`, with `@` instead of `//` before host). + Changes in 0.7.0-beta5 * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). diff --git a/README.md b/README.md index 04662d56..d02c7a91 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0-beta5 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.0 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0-beta5 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0-beta5"] +[org.clojure/java.jdbc "0.7.0"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0-beta5 + 0.7.0 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -134,6 +134,11 @@ Developer Information Change Log ==================== +Release 0.7.0 on 2017-07-16 + + * `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL). + * Add better support for Oracle connections (default port to `1521`, support `:dbtype "oracle"` -- as `"oracle:thin"` -- and `:dbtype "oracle:oci"`, with `@` instead of `//` before host). + Release 0.7.0-beta5 on 2017-07-05 * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a42bc6ef..9537ff0f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -170,21 +170,29 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "oracle" "oracle:thin" "postgres" "postgresql"}) +(def ^:private host-prefixes + "Map of subprotocols to non-standard host-prefixes. + Anything not listed is assumed to use //." + {"oracle:oci" "@" + "oracle:thin" "@"}) + (defn- parse-properties-uri [^URI uri] (let [host (.getHost uri) port (if (pos? (.getPort uri)) (.getPort uri)) path (.getPath uri) scheme (.getScheme uri) + subprotocol (subprotocols scheme scheme) + host-prefix (host-prefixes subprotocol "//") ^String query (.getQuery uri) query-parts (and query (for [^String kvs (.split query "&")] (vec (.split kvs "="))))] (merge {:subname (if host (if port - (str "//" host ":" port path) - (str "//" host path)) + (str host-prefix host ":" port path) + (str host-prefix host path)) (.getSchemeSpecificPart uri)) - :subprotocol (subprotocols scheme scheme)} + :subprotocol subprotocol} (if-let [user-info (.getUserInfo uri)] {:user (first (str/split user-info #":")) :password (second (str/split user-info #":"))}) @@ -313,13 +321,17 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} port (or port (condp = subprotocol "jtds:sqlserver" 1433 "mysql" 3306 + "oracle:oci" 1521 + "oracle:thin" 1521 "postgresql" 5432 "sqlserver" 1433 nil)) db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) (str "jdbc:" subprotocol ":" dbname) - (str "jdbc:" subprotocol "://" host + (str "jdbc:" subprotocol ":" + (host-prefixes subprotocol "//") + host (when port (str ":" port)) db-sep dbname)) etc (dissoc db-spec :dbtype :dbname)] @@ -1356,12 +1368,18 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} remaining elements are left as-is when converting them to strings. An options map may be provided that can contain: :table-spec -- a string that is appended to the DDL -- and/or - :entities -- a function to specify how column names are transformed." + :entities -- a function to specify how column names are transformed. + :conditional? -- either a boolean, indicating whether to add 'IF NOT EXISTS', + or a string, which is inserted literally before the table name, or a + function of two arguments (table name and the create statement), that can + manipulate the generated statement to better support other databases, e.g., + MS SQL Server which need to wrap create table in an existence query." ([table specs] (create-table-ddl table specs {})) ([table specs opts] (let [table-spec (:table-spec opts) conditional? (:conditional? opts) entities (:entities opts identity) + table-name (as-sql-name entities table) table-spec-str (or (and table-spec (str " " table-spec)) "") spec-to-string (fn [spec] (try @@ -1370,20 +1388,38 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (catch Exception _ (throw (IllegalArgumentException. "column spec is not a sequence of keywords / strings")))))] - (format "CREATE TABLE%s %s (%s)%s" - (if (boolean? conditional?) - (if conditional? " IF NOT EXISTS" "") - conditional?) - (as-sql-name entities table) - (str/join ", " (map spec-to-string specs)) - table-spec-str)))) + (cond->> (format "CREATE TABLE%s %s (%s)%s" + (cond (or (nil? conditional?) + (instance? Boolean conditional?)) + (if conditional? " IF NOT EXISTS" "") + (fn? conditional?) + "" + :else + (str " " conditional?)) + table-name + (str/join ", " (map spec-to-string specs)) + table-spec-str) + (fn? conditional?) (conditional? table-name))))) (defn drop-table-ddl - "Given a table name, return the DDL string for dropping that table." - ([name] (drop-table-ddl name {})) - ([name {:keys [entities conditional?] :or {entities identity}}] - (format "DROP TABLE%s %s" - (if (boolean? conditional?) - (if conditional? " IF EXISTS" "") - conditional?) - (as-sql-name entities name)))) + "Given a table name, return the DDL string for dropping that table. + An options map may be provided that can contain: + :entities -- a function to specify how column names are transformed. + :conditional? -- either a boolean, indicating whether to add 'IF EXISTS', + or a string, which is inserted literally before the table name, or a + function of two arguments (table name and the create statement), that can + manipulate the generated statement to better support other databases, e.g., + MS SQL Server which need to wrap create table in an existence query." + ([table] (drop-table-ddl table {})) + ([table {:keys [entities conditional?] :or {entities identity}}] + (let [table-name (as-sql-name entities table)] + (cond->> (format "DROP TABLE%s %s" + (cond (or (nil? conditional?) + (instance? Boolean conditional?)) + (if conditional? " IF EXISTS" "") + (fn? conditional?) + "" + :else + (str " " conditional?)) + table-name) + (fn? conditional?) (conditional? table-name))))) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index d531a857..f0593560 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -145,11 +145,12 @@ (s/def ::table-spec string?) (s/def ::timeout nat-int?) (s/def ::transaction? boolean?) +(s/def ::explain? (s/or :b boolean? :s string?)) +(s/def ::explain-fn fn?) +(s/def ::conditional? (s/or :b boolean? :s string? :f fn?)) ;; various types of options -(s/def ::create-options (s/keys :req-un [] :opt-un [::table-spec ::entities])) - (s/def ::exec-sql-options (s/keys :req-un [] :opt-un [::entities ::transaction?])) (s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?])) @@ -309,7 +310,10 @@ (s/fdef sql/query :args (s/cat :db ::db-spec :sql-params ::sql-params - :opts (s/? ::query-options)) + :opts (s/? (s/merge ::query-options + (s/keys :req-un [] + :opt-un [::explain? + ::explain-fn])))) :ret any?) (s/fdef sql/reducible-result-set @@ -388,10 +392,16 @@ (s/fdef sql/create-table-ddl :args (s/cat :table ::identifier :specs (s/coll-of ::column-spec) - :opts (s/? ::create-options)) + :opts (s/? (s/keys :req-un [] + :opt-un [::entities + ::conditional? + ::table-spec]))) + :ret string?) (s/fdef sql/drop-table-ddl :args (s/cat :table ::identifier - :opts (s/? (s/keys :req-un [] :opt-un [::entities]))) + :opts (s/? (s/keys :req-un [] + :opt-un [::entities + ::conditional?]))) :ret string?) From 7f24fdd6d16b13ed998ea3968ae6db5cde5f54a0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 16 Jul 2017 18:26:16 -0500 Subject: [PATCH 486/630] [maven-release-plugin] prepare release java.jdbc-0.7.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1c5d895c..ab34936a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0-SNAPSHOT + 0.7.0 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.0 From e83c0fe64cce32fbff75356ce5e871039a1c0a82 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sun, 16 Jul 2017 18:26:16 -0500 Subject: [PATCH 487/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ab34936a..08597b14 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.0 + 0.7.1-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.0 + HEAD From 12604f29c36e3c7b51d28d1f77da856f2bcd8f7e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 12 Aug 2017 17:02:29 -0700 Subject: [PATCH 488/630] JDBC-154 improve prepare-statement docstring --- src/main/clojure/clojure/java/jdbc.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9537ff0f..75c00099 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -541,10 +541,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} the generated keys to return, otherwise it should just be true :result-type :forward-only | :scroll-insensitive | :scroll-sensitive :concurrency :read-only | :updatable - :cursors - :fetch-size n - :max-rows n - :timeout n + :cursors :hold | :close + :fetch-size n + :max-rows n + :timeout n Note that :result-type and :concurrency must be specified together as the underlying Java API expects both (or neither)." ([con sql] (prepare-statement con sql {})) From dd77edeb158edd3e46fb01c4648bbc6264b091e6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 30 Aug 2017 10:16:49 -0700 Subject: [PATCH 489/630] Release 0.7.1 fixes JDBC-155 --- CHANGES.md | 4 ++++ README.md | 11 ++++++++--- project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 5 +++-- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c06b6780..14a22fca 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.7.1 + +* Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). + Changes in 0.7.0 * `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL). diff --git a/README.md b/README.md index d02c7a91..2067a1f3 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.0 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.1 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.0 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.0"] +[org.clojure/java.jdbc "0.7.1"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.0 + 0.7.1 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -134,6 +134,11 @@ Developer Information Change Log ==================== + +Release 0.7.1 on 2017-08-30 + + * Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). + Release 0.7.0 on 2017-07-16 * `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL). diff --git a/project.clj b/project.clj index c582843c..13cefc0c 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.7.0-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.7.2-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 75c00099..a519b857 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -184,8 +184,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} subprotocol (subprotocols scheme scheme) host-prefix (host-prefixes subprotocol "//") ^String query (.getQuery uri) - query-parts (and query (for [^String kvs (.split query "&")] - (vec (.split kvs "="))))] + query-parts (and query + (for [^String kvs (.split query "&")] + ((juxt first second) (.split kvs "="))))] (merge {:subname (if host (if port From 75bb2231f5d04895a6ce7fa363b554c455190ac4 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 30 Aug 2017 12:18:38 -0500 Subject: [PATCH 490/630] [maven-release-plugin] prepare release java.jdbc-0.7.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 08597b14..7febda6b 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.1-SNAPSHOT + 0.7.1 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.1 From 636e7049cd25c96e00f86a1abb5384ea8b83d5bd Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Wed, 30 Aug 2017 12:18:38 -0500 Subject: [PATCH 491/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7febda6b..0c2e54e1 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.1 + 0.7.2-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.1 + HEAD From e606cc81857578d8c99fba89523b03fb5dc092eb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 13 Sep 2017 19:57:50 -0700 Subject: [PATCH 492/630] JDBC-156 fix spec for connection-uri --- CHANGES.md | 4 ++++ src/main/clojure/clojure/java/jdbc/spec.clj | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 14a22fca..e22e9dd9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.2 + +* `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). + Changes in 0.7.1 * Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index f0593560..ed717d41 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -20,7 +20,6 @@ ;; basic java.sql types -- cannot be generated! (s/def ::connection #(instance? java.sql.Connection %)) -(s/def ::connection-uri #(instance? java.net.URI %)) (s/def ::datasource #(instance? javax.sql.DataSource %)) (s/def ::prepared-statement #(instance? java.sql.PreparedStatement %)) (s/def ::result-set #(instance? java.sql.ResultSet %)) @@ -55,6 +54,8 @@ (s/def ::password string?) (s/def ::name string?) (s/def ::environment (s/nilable map?)) +;; raw connection-uri +(s/def ::connection-uri string?) (s/def ::db-spec-connection (s/keys :req-un [::connection])) (s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname] :opt-un [::host ::port])) From b841efa638fd022a6b86269c0be2b2d11afa8eb4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 15 Sep 2017 12:58:38 -0700 Subject: [PATCH 493/630] Update Contributing link --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7800bfb8..512917d6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ See [Contributing] and the [FAQ] on the Clojure development [wiki] for more information on how to contribute. [Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib -[Contributing]: http://dev.clojure.org/display/community/Contributing +[Contributing]: https://clojure.org/community/contributing [FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ [JIRA]: http://dev.clojure.org/jira/browse/JDBC [guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers From 7177209ba178c16902e7eb9b007156062f1bcd10 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 15 Sep 2017 14:54:29 -0700 Subject: [PATCH 494/630] Enhance connection-uri; clarify docstring --- CHANGES.md | 2 ++ src/main/clojure/clojure/java/jdbc.clj | 23 ++++++++++++++--------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index e22e9dd9..8b255784 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ Changes coming in 0.7.2 * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). +* Allow for `:user` and `:password` to be passed with `:connection-uri`, so credentials can be omitted from the connection string. +* Clarified docstring for `get-connection` to show where `:user` and `:password` can be passed. Changes in 0.7.1 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a519b857..f011f2bc 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -236,11 +236,14 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defaults to 127.0.0.1) :port (optional) a Long, the port of the database (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) - (others) (optional) passed to the driver as properties. + (others) (optional) passed to the driver as properties + (may include :user and :password) Raw: :connection-uri (required) a String Passed directly to DriverManager/getConnection + (both :user and :password may be specified as well, rather + than passing them as part of the connection string) Other formats accepted: @@ -252,7 +255,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} :subprotocol (required) a String, the jdbc subprotocol :subname (required) a String, the jdbc subname :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties. + (others) (optional) passed to the driver as properties + (may include :user and :password) Factory: :factory (required) a function of one argument, a map of params @@ -260,10 +264,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} DataSource: :datasource (required) a javax.sql.DataSource - :username (optional) a String - :user (optional) a String - an alternate alias for :username - (added after 0.3.0-beta2 for consistency JDBC-74) - :password (optional) a String, required if :username is supplied + :username (optional) a String - deprecated, use :user instead + :user (optional) a String - preferred + :password (optional) a String, required if :user is supplied JNDI: :name (required) a String or javax.naming.Name @@ -296,8 +299,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} connection connection ;; do not apply opts here - (or (and datasource username password) - (and datasource user password)) + (or (and datasource username password) ; legacy + (and datasource user password)) ; preferred (-> (.getConnection ^DataSource datasource ^String (or username user) ^String password) @@ -312,7 +315,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (modify-connection opts)) connection-uri - (-> (DriverManager/getConnection connection-uri) + (-> (if (and user password) + (DriverManager/getConnection connection-uri user password) + (DriverManager/getConnection connection-uri)) (modify-connection opts)) (and dbtype dbname) From b0545dd90e4c68d6ba3ffb503c2da68afcb1e598 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 2 Oct 2017 10:10:46 -0700 Subject: [PATCH 495/630] Release 0.7.2 --- CHANGES.md | 2 +- README.md | 12 +++++++++--- project.clj | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 8b255784..e8cbef74 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.2 +Changes in 0.7.2 * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). * Allow for `:user` and `:password` to be passed with `:connection-uri`, so credentials can be omitted from the connection string. diff --git a/README.md b/README.md index 2067a1f3..c92d3da6 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.1 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.2 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.1 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.1"] +[org.clojure/java.jdbc "0.7.2"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.1 + 0.7.2 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -135,6 +135,12 @@ Change Log ==================== +Release 0.7.2 on 2017-10-02 + + * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). + * Allow for `:user` and `:password` to be passed with `:connection-uri`, so credentials can be omitted from the connection string. + * Clarified docstring for `get-connection` to show where `:user` and `:password` can be passed. + Release 0.7.1 on 2017-08-30 * Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). diff --git a/project.clj b/project.clj index 13cefc0c..c2db39a1 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.7.2-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.7.3-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From 6797c0cf9b08d15298a7e15c11b1159e0322c351 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 2 Oct 2017 12:18:53 -0500 Subject: [PATCH 496/630] [maven-release-plugin] prepare release java.jdbc-0.7.2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0c2e54e1..9e51a241 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.2-SNAPSHOT + 0.7.2 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.2 From 6024b5762d187236dd78bbbea0848c2991f130cf Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 2 Oct 2017 12:18:53 -0500 Subject: [PATCH 497/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9e51a241..741b4149 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.2 + 0.7.3-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.2 + HEAD From bbc2042df4ae29022a9fdde6715c89f3fed69b24 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 2 Oct 2017 10:37:38 -0700 Subject: [PATCH 498/630] Bump base Clojure dep to 1.9.0-beta1 --- project.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.clj b/project.clj index c2db39a1..78d0f42a 100644 --- a/project.clj +++ b/project.clj @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-alpha17"] + :dependencies [[org.clojure/clojure "1.9.0-beta1"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj From cd0739ed834b82a7c30d24d0ee3f1a4846b22781 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 5 Oct 2017 20:55:34 -0700 Subject: [PATCH 499/630] JDBC-159 add :keywordize? option --- CHANGES.md | 4 ++ src/main/clojure/clojure/java/jdbc.clj | 57 +++++++++++++++++++------- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index e8cbef74..f8a62a10 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.3 + +* Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). + Changes in 0.7.2 * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f011f2bc..99c67f5c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -471,17 +471,29 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} are untouched (the result set maintains column name/value order). The :identifiers option specifies how SQL column names are converted to Clojure keywords. The default is to convert them to lower case. - The :qualifier option specifies the namespace qualifier for those identifiers." + The :keywordize? option can be specified as false to opt-out of the conversion + to keywords. + The :qualifier option specifies the namespace qualifier for those identifiers + (and this may not be specified when :keywordize? is false)." ([rs] (result-set-seq rs {})) - ([^ResultSet rs {:keys [as-arrays? identifiers qualifier read-columns] + ([^ResultSet rs {:keys [as-arrays? identifiers keywordize? + qualifier read-columns] :or {identifiers str/lower-case + keywordize? true read-columns dft-read-columns}}] (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) - identifier-fn (if qualifier - (comp (partial keyword qualifier) identifiers) - (comp keyword identifiers)) + identifier-fn (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers) keys (->> idxs (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) col-name-fn @@ -792,13 +804,15 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, else return it as-is. This makes working with metadata easier. - Also accepts an option map containing :identifiers, :qualifier, :as-arrays?, - :row-fn,and :result-set-fn to control how the ResultSet is transformed and - returned. See query for more details." + Also accepts an option map containing :identifiers, :keywordize?, :qualifier, + :as-arrays?, :row-fn,and :result-set-fn to control how the ResultSet is + transformed and returned. See query for more details." ([rs-or-value] (metadata-result rs-or-value {})) ([rs-or-value opts] (let [{:keys [as-arrays? result-set-fn row-fn] :as opts} - (merge {:identifiers str/lower-case :read-columns dft-read-columns + (merge {:identifiers str/lower-case + :keywordize? true + :read-columns dft-read-columns :row-fn identity} opts) result-set-fn (or result-set-fn (if as-arrays? vec doall))] (if (instance? java.sql.ResultSet rs-or-value) @@ -982,6 +996,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} set (and are also passed to prepare-statement as needed): :as-arrays? - return the results as a set of arrays, default false. :identifiers - applied to each column name in the result set, default lower-case + :keywordize? - defaults to true, can be false to opt-out of converting + identifiers to keywords :qualifier - optionally provides the namespace qualifier for identifiers :result-set-fn - applied to the entire result set, default doall / vec if :as-arrays? true, :result-set-fn will default to vec @@ -994,6 +1010,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ([db sql-params opts] (let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts} (merge {:explain-fn println :identifiers str/lower-case + :keywordize? true :read-columns dft-read-columns :row-fn identity} (when (map? db) db) opts) @@ -1021,12 +1038,20 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "Given a java.sql.ResultSet return a reducible collection. Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce Note: :as-arrays? is not accepted here." - [^ResultSet rs {:keys [identifiers qualifier read-columns] + [^ResultSet rs {:keys [identifiers keywordize? qualifier read-columns] :or {identifiers str/lower-case + keywordize? true read-columns dft-read-columns}}] - (let [identifier-fn (if qualifier - (comp (partial keyword qualifier) identifiers) - (comp keyword identifiers)) + (let [identifier-fn (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers) make-keys (fn [idxs ^ResultSetMetaData rsmeta] (->> idxs (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) @@ -1070,7 +1095,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ([db sql-params] (reducible-query db sql-params {})) ([db sql-params opts] (let [{:keys [reducing-fn] :as opts} - (merge {:identifiers str/lower-case :read-columns dft-read-columns} + (merge {:identifiers str/lower-case :keywordize? true + :read-columns dft-read-columns} (when (map? db) db) opts) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] @@ -1254,7 +1280,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} map, insert the rows into the database." [db table rows opts] (let [{:keys [entities transaction?] :as opts} - (merge {:entities identity :identifiers str/lower-case :transaction? true} + (merge {:entities identity :identifiers str/lower-case + :keywordize? true :transaction? true} (when (map? db) db) opts) sql-params (map (fn [row] From 02d05a3c0055d2296a0b514e3c9728162494809f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 5 Oct 2017 21:15:00 -0700 Subject: [PATCH 500/630] JDBC-158 exposed transaction exception When rollback exception occurs, both exceptions are combined & thrown. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index f8a62a10..72b5382b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.7.3 * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). +* If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). Changes in 0.7.2 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 99c67f5c..a240600a 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -735,7 +735,15 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (.commit con)) result) (catch Throwable t - (.rollback con) + (try + (.rollback con) + (catch Throwable rb + ;; combine both exceptions + (throw (ex-info (str "Rollback failed handling \"" + (.getMessage t) + "\"") + {:rollback rb + :handling t})))) (throw t)) (finally (db-unset-rollback-only! nested-db) From 2063773726771e2a7f58b0b3835555bf4d5f4e8d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 5 Oct 2017 21:27:55 -0700 Subject: [PATCH 501/630] Release 0.7.3 --- CHANGES.md | 2 +- README.md | 10 +++++++--- project.clj | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 72b5382b..20aec6b3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.3 +Changes in 0.7.3 * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). * If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). diff --git a/README.md b/README.md index c92d3da6..09422447 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Additional documentation can be found in the [java.jdbc section of clojure-doc.o Releases and Dependency Information ======================================== -Latest stable release: 0.7.2 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.3 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -24,14 +24,14 @@ Latest stable release: 0.7.2 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.2"] +[org.clojure/java.jdbc "0.7.3"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.2 + 0.7.3 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -134,6 +134,10 @@ Developer Information Change Log ==================== +Release 0.7.3 on 2017-10-05 + + * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). + * If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). Release 0.7.2 on 2017-10-02 diff --git a/project.clj b/project.clj index 78d0f42a..a7d7550a 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.7.3-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.7.4-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" From c1e99fbbe0431216e2ad6e13f8730fe6dc170263 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 5 Oct 2017 23:29:27 -0500 Subject: [PATCH 502/630] [maven-release-plugin] prepare release java.jdbc-0.7.3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 741b4149..bc58a713 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.3-SNAPSHOT + 0.7.3 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.3 From 0a9e5e91642ac43d19681acbf089bbc636bb20f7 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 5 Oct 2017 23:29:27 -0500 Subject: [PATCH 503/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index bc58a713..16727262 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.3 + 0.7.4-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.3 + HEAD From 2ac6363927c9b14a753fb2dbbd28b13acda10aac Mon Sep 17 00:00:00 2001 From: Shaun Mahood Date: Fri, 6 Oct 2017 11:18:35 -0600 Subject: [PATCH 504/630] JDBC-160 change README.md to make API reference and documentation easier to find. Signed-off-by: Sean Corfield --- README.md | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 09422447..4931cb89 100644 --- a/README.md +++ b/README.md @@ -3,15 +3,23 @@ clojure.java.jdbc A low-level Clojure wrapper for JDBC-based access to databases. -For DSLs that are compatible with this library, consider: - -* [HoneySQL](https://github.com/jkk/honeysql) -* [SQLingvo](https://github.com/r0man/sqlingvo) -* [Korma](http://sqlkorma.com) +For higher level DSLs and migration libraries that are compatible, see the [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). Formerly known as `clojure.contrib.sql`. -Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) and there is a dedicated [java.jdbc mailing list](https://groups.google.com/forum/#!forum/clojure-java-jdbc) +Documentation +======================================== +* [API Reference](http://clojure.github.com/java.jdbc/) (Autogenerated) + +* [Overview](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) +* [Manipulating Data with SQL](http://clojure-doc.org/articles/ecosystem/java_jdbc/using_sql.html) +* [How to Reuse Database Connections](http://clojure-doc.org/articles/ecosystem/java_jdbc/reusing_connections.html) +* [Using DDL and Metadata](http://clojure-doc.org/articles/ecosystem/java_jdbc/using_ddl.html) + +Support +======================================== +* [Mailing List](https://groups.google.com/forum/#!forum/clojure-java-jdbc) +* #sql on [Clojurians Slack](http://clojurians.net/) Releases and Dependency Information ======================================== @@ -100,7 +108,7 @@ Example Usage {:row-fn :cost}) ;; (24) ``` -For more detail see the [generated documentation on github](http://clojure.github.com/java.jdbc/). +For more detail see the [API reference](http://clojure.github.com/java.jdbc/) or [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). Developer Information ======================================== From 110a2dab07be442639d4c6acde2b9d99cb16ec30 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 6 Oct 2017 10:32:33 -0700 Subject: [PATCH 505/630] JDBC-160 improve readme --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 20aec6b3..fbff4644 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.4 + +* Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). + Changes in 0.7.3 * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). From 8a6231008bebfa40cb0273624c3f0ae1c3dc8777 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 6 Oct 2017 10:35:53 -0700 Subject: [PATCH 506/630] Tweak release history formatting --- README.md | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 4931cb89..bcf067e3 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Documentation * [How to Reuse Database Connections](http://clojure-doc.org/articles/ecosystem/java_jdbc/reusing_connections.html) * [Using DDL and Metadata](http://clojure-doc.org/articles/ecosystem/java_jdbc/using_ddl.html) -Support +Support ======================================== * [Mailing List](https://groups.google.com/forum/#!forum/clojure-java-jdbc) * #sql on [Clojurians Slack](http://clojurians.net/) @@ -142,47 +142,40 @@ Developer Information Change Log ==================== -Release 0.7.3 on 2017-10-05 - +* Release 0.7.3 on 2017-10-05 * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). * If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). -Release 0.7.2 on 2017-10-02 - +* Release 0.7.2 on 2017-10-02 * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). * Allow for `:user` and `:password` to be passed with `:connection-uri`, so credentials can be omitted from the connection string. * Clarified docstring for `get-connection` to show where `:user` and `:password` can be passed. -Release 0.7.1 on 2017-08-30 - +* Release 0.7.1 on 2017-08-30 * Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). -Release 0.7.0 on 2017-07-16 - +* Release 0.7.0 on 2017-07-16 * `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL). * Add better support for Oracle connections (default port to `1521`, support `:dbtype "oracle"` -- as `"oracle:thin"` -- and `:dbtype "oracle:oci"`, with `@` instead of `//` before host). -Release 0.7.0-beta5 on 2017-07-05 - +* Release 0.7.0-beta5 on 2017-07-05 * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). * Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`. -Release 0.7.0-beta4 on 2017-07-04 - +* Release 0.7.0-beta4 on 2017-07-04 * `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`. * Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there. -Release 0.7.0-beta3 on 2017-07-04 - +* Release 0.7.0-beta3 on 2017-07-04 * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). -Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2) +* Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2) * Support for Clojure 1.5 and 1.6 has been dropped -- breaking change. * Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later! * All public functions now have specs in the optional `clojure.java.jdbc.spec` namespace (requires `clojure.spec.alpha`). * `reducible-query` and `reducible-result-set` use `IReduce` and correctly support the no-`init` arity of `reduce` by using the first row of the `ResultSet`, if present, as the (missing) `init` value, and only calling `f` with no arguments if the `ResultSet` is empty. The `init` arity of `reduce` only ever calls `f` with two arguments. -Release 0.7.0-beta1 on 2017-06-29 +* Release 0.7.0-beta1 on 2017-06-29 * Support for Clojure 1.4.0 has been dropped -- breaking change. * Optional spec support now uses `clojure.spec.alpha`. * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). From dcaca43a86498c0fbe303ed17bdf7541ae898f2e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 6 Oct 2017 10:36:57 -0700 Subject: [PATCH 507/630] Another formatting tweak --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bcf067e3..3bcdb532 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ Change Log * Optional spec support now uses `clojure.spec.alpha`. * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). -Release 0.7.0-alpha3 on 2017-03-23 +* Release 0.7.0-alpha3 on 2017-03-23 * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. From ee8559819a9387ffb89735680559997d4d9bd5ff Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 6 Oct 2017 11:39:03 -0700 Subject: [PATCH 508/630] Optional specs updated with changes in recent versions. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc/spec.clj | 23 +++++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index fbff4644..03a1ea99 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ Changes coming in 0.7.4 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). +* Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. Changes in 0.7.3 diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index ed717d41..2b512d97 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -58,12 +58,18 @@ (s/def ::connection-uri string?) (s/def ::db-spec-connection (s/keys :req-un [::connection])) -(s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname] :opt-un [::host ::port])) -(s/def ::db-spec-raw (s/keys :req-un [::connection-uri])) -(s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname] :opt-un [::classname])) +(s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname] + :opt-un [::host ::port ::user ::password + ::classname])) +(s/def ::db-spec-raw (s/keys :req-un [::connection-uri] + :opt-un [::user ::password])) +(s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname] + :opt-un [::classname ::user ::password])) (s/def ::db-spec-factory (s/keys :req-un [::factory])) -(s/def ::db-spec-data-source (s/keys :req-un [::datasource] :opt-un [::username ::user ::password])) -(s/def ::db-spec-jndi (s/keys :req-un [::name] :opt-un [::environment])) +(s/def ::db-spec-data-source (s/keys :req-un [::datasource] + :opt-un [::username ::user ::password])) +(s/def ::db-spec-jndi (s/keys :req-un [::name] + :opt-un [::environment])) (s/def ::db-spec-string string?) (s/def ::db-spec (s/or :connection ::db-spec-connection :friendly ::db-spec-friendly @@ -115,6 +121,7 @@ (s/def ::isolation (set (keys @#'sql/isolation-levels))) (s/def ::entities (s/fspec :args (s/cat :s string?) :ret ::entity)) +(s/def ::keywordize? boolean?) (s/def ::max-size nat-int?) (s/def ::multi? boolean?) ;; strictly speaking we accept any keyword or string whose upper case name @@ -160,6 +167,7 @@ :opt-un [::entities ::order-by ::result-set-fn ::row-fn ::identifiers ::qualifier + ::keywordize? ::as-arrays? ::read-columns])) (s/def ::connection-options (s/keys :req-un [] @@ -177,11 +185,14 @@ (s/def ::query-options (s/merge (s/keys :req-un [] :opt-un [::result-set-fn ::row-fn ::identifiers ::qualifier + ::keywordize? ::as-arrays? ::read-columns]) ::prepare-options)) (s/def ::reducible-query-options (s/merge (s/keys :req-un [] - :opt-un [::identifiers ::qualifier + :opt-un [::identifiers + ::keywordize? + ::qualifier ::read-columns]) ::prepare-options)) From 4bd4536daa2773fc36bbd5a43680116cdbf066e6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 13 Oct 2017 15:02:49 -0400 Subject: [PATCH 509/630] Add placeholder notes for possible speedups (mostly for reducible-query) --- src/main/clojure/clojure/java/jdbc.clj | 2946 ++++++++++++------------ 1 file changed, 1480 insertions(+), 1466 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a240600a..ce51d0d8 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,1466 +1,1480 @@ -;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved. -;; The use and distribution terms for this software are covered by -;; the Eclipse Public License 1.0 -;; (http://opensource.org/licenses/eclipse-1.0.php) which can be -;; found in the file epl-v10.html at the root of this distribution. -;; By using this software in any fashion, you are agreeing to be -;; bound by the terms of this license. You must not remove this -;; notice, or any other, from this software. -;; -;; jdbc.clj -;; -;; A Clojure interface to sql databases via jdbc -;; -;; scgilardi (gmail) -;; Created 2 April 2008 -;; -;; seancorfield (gmail) -;; Migrated from clojure.contrib.sql 17 April 2011 - -(ns - ^{:author "Stephen C. Gilardi, Sean Corfield", - :doc "A Clojure interface to SQL databases via JDBC - -clojure.java.jdbc provides a simple abstraction for CRUD (create, read, -update, delete) operations on a SQL database, along with basic transaction -support. Basic DDL operations are also supported (create table, drop table, -access to table metadata). - -Maps are used to represent records, making it easy to store and retrieve -data. Results can be processed using any standard sequence operations. - -For most operations, Java's PreparedStatement is used so your SQL and -parameters can be represented as simple vectors where the first element -is the SQL string, with ? for each parameter, and the remaining elements -are the parameter values to be substituted. In general, operations return -the number of rows affected, except for a single record insert where any -generated keys are returned (as a map). - -For more documentation, see: - -http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} - clojure.java.jdbc - (:require [clojure.set :as set] - [clojure.string :as str] - [clojure.walk :as walk]) - (:import (java.net URI) - (java.sql BatchUpdateException DriverManager - PreparedStatement ResultSet ResultSetMetaData - SQLException Statement Types) - (java.util Hashtable Map Properties) - (javax.sql DataSource))) - -(defn as-sql-name - "Given a naming strategy function and a keyword or string, return - a string per that naming strategy. - A name of the form x.y is treated as multiple names, x, y, etc, - and each are turned into strings via the naming strategy and then - joined back together so x.y might become `x`.`y` if the naming - strategy quotes identifiers with `." - [f x] - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\.")))))) - -(defn quoted - "Given a (vector) pair of delimiters (characters or strings), return a naming - strategy function that will quote SQL entities with them. - Given a single delimiter, treat it as a (vector) pair of that delimiter. - ((quoted [\\[ \\]]) \"foo\") will return \"[foo]\" -- for MS SQL Server - ((quoted \\`') \"foo\") will return \"`foo`\" -- for MySQL - Intended to be used with :entities to provide a quoting (naming) strategy that - is appropriate for your database." - [q] - (cond (vector? q) - (fn [x] - (str (first q) x (last q))) - (keyword? q) - (case q - :ansi (quoted \") - :mysql (quoted \`) - :oracle (quoted \") - :sqlserver (quoted [\[ \]])) - :else - (quoted [q q]))) - -(defn- table-str - "Transform a table spec to an entity name for SQL. The table spec may be a - string, a keyword or a map with a single pair - table name and alias." - [table entities] - (let [entities (or entities identity)] - (if (map? table) - (let [[k v] (first table)] - (str (as-sql-name entities k) " " (as-sql-name entities v))) - (as-sql-name entities table)))) - -(defn- kv-sql - "Given a sequence of column name keys and a matching sequence of column - values, and an entities mapping function, return a sequence of SQL fragments - that can be joined for part of an UPDATE SET or a SELECT WHERE clause. - Note that we pass the appropriate operator for NULL since it is different - in each case." - [ks vs entities null-op] - (map (fn [k v] - (str (as-sql-name entities k) - (if (nil? v) null-op " = ?"))) - ks vs)) - -(defn- ^Properties as-properties - "Convert any seq of pairs to a java.utils.Properties instance. - Uses as-sql-name to convert both keys and values into strings." - [m] - (let [p (Properties.)] - (doseq [[k v] m] - (.setProperty p (as-sql-name identity k) - (if (instance? clojure.lang.Named v) - (as-sql-name identity v) - (str v)))) - p)) - -;; convenience for working with different forms of connections -(defprotocol Connectable - (add-connection [db connection]) - (get-level [db])) - -(defn- inc-level - "Increment the nesting level for a transacted database connection. - If we are at the top level, also add in a rollback state." - [db] - (let [nested-db (update-in db [:level] (fnil inc 0))] - (if (= 1 (:level nested-db)) - (assoc nested-db :rollback (atom false)) - nested-db))) - -(extend-protocol Connectable - String - (add-connection [s connection] {:connection connection :level 0 :connection-string s}) - (get-level [_] 0) - - clojure.lang.Associative - (add-connection [m connection] (assoc m :connection connection)) - (get-level [m] (or (:level m) 0)) - - nil - (add-connection [_ connection] {:connection connection :level 0 :legacy true}) - (get-level [_] 0)) - -(def ^:private classnames - "Map of subprotocols to classnames. dbtype specifies one of these keys. - The subprotocols map below provides aliases for dbtype." - {"derby" "org.apache.derby.jdbc.EmbeddedDriver" - "h2" "org.h2.Driver" - "hsqldb" "org.hsqldb.jdbcDriver" - "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" - "mysql" "com.mysql.jdbc.Driver" - "oracle:oci" "oracle.jdbc.OracleDriver" - "oracle:thin" "oracle.jdbc.OracleDriver" - "postgresql" "org.postgresql.Driver" - "pgsql" "com.impossibl.postgres.jdbc.PGDriver" - "redshift" "com.amazon.redshift.jdbc.Driver" - "sqlite" "org.sqlite.JDBC" - "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) - -(def ^:private subprotocols - "Map of schemes to subprotocols. Used to provide aliases for dbtype." - {"hsql" "hsqldb" - "jtds" "jtds:sqlserver" - "mssql" "sqlserver" - "oracle" "oracle:thin" - "postgres" "postgresql"}) - -(def ^:private host-prefixes - "Map of subprotocols to non-standard host-prefixes. - Anything not listed is assumed to use //." - {"oracle:oci" "@" - "oracle:thin" "@"}) - -(defn- parse-properties-uri [^URI uri] - (let [host (.getHost uri) - port (if (pos? (.getPort uri)) (.getPort uri)) - path (.getPath uri) - scheme (.getScheme uri) - subprotocol (subprotocols scheme scheme) - host-prefix (host-prefixes subprotocol "//") - ^String query (.getQuery uri) - query-parts (and query - (for [^String kvs (.split query "&")] - ((juxt first second) (.split kvs "="))))] - (merge - {:subname (if host - (if port - (str host-prefix host ":" port path) - (str host-prefix host path)) - (.getSchemeSpecificPart uri)) - :subprotocol subprotocol} - (if-let [user-info (.getUserInfo uri)] - {:user (first (str/split user-info #":")) - :password (second (str/split user-info #":"))}) - (walk/keywordize-keys (into {} query-parts))))) - -(defn- strip-jdbc [^String spec] - (if (.startsWith spec "jdbc:") - (.substring spec 5) - spec)) - -;; feature testing macro, based on suggestion from Chas Emerick: -(defmacro when-available - [sym & body] - (try - (when (resolve sym) - (list* 'do body)) - (catch ClassNotFoundException _#))) - -(defn- modify-connection - "Given a database connection and a map of options, update the connection - as specified by the options." - ^java.sql.Connection - [^java.sql.Connection connection opts] - (when (contains? opts :auto-commit?) - (.setAutoCommit connection (:auto-commit? opts))) - (when (contains? opts :read-only?) - (.setReadOnly connection (:read-only? opts))) - connection) - -(defn get-connection - "Creates a connection to a database. db-spec is usually a map containing connection - parameters but can also be a URI or a String. The various possibilities are described - below: - - DriverManager (preferred): - :dbtype (required) a String, the type of the database (the jdbc subprotocol) - :dbname (required) a String, the name of the database - :classname (optional) a String, the jdbc driver class name - :host (optional) a String, the host name/IP of the database - (defaults to 127.0.0.1) - :port (optional) a Long, the port of the database - (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) - (others) (optional) passed to the driver as properties - (may include :user and :password) - - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - (both :user and :password may be specified as well, rather - than passing them as part of the connection string) - - Other formats accepted: - - Existing Connection: - :connection (required) an existing open connection that can be used - but cannot be closed (only the parent connection can be closed) - - DriverManager (alternative / legacy style): - :subprotocol (required) a String, the jdbc subprotocol - :subname (required) a String, the jdbc subname - :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties - (may include :user and :password) - - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DataSource: - :datasource (required) a javax.sql.DataSource - :username (optional) a String - deprecated, use :user instead - :user (optional) a String - preferred - :password (optional) a String, required if :user is supplied - - JNDI: - :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map - - java.net.URI: - Parsed JDBC connection string (see java.lang.String format next) - - java.lang.String: - subprotocol://user:password@host:post/subname - An optional prefix of jdbc: is allowed." - (^java.sql.Connection [db-spec] (get-connection db-spec {})) - (^java.sql.Connection - [{:keys [connection - factory - connection-uri - classname subprotocol subname - dbtype dbname host port - datasource username password user - name environment] - :as db-spec} - opts] - (cond - (string? db-spec) - (get-connection (URI. (strip-jdbc db-spec)) opts) - - (instance? URI db-spec) - (get-connection (parse-properties-uri db-spec) opts) - - connection - connection ;; do not apply opts here - - (or (and datasource username password) ; legacy - (and datasource user password)) ; preferred - (-> (.getConnection ^DataSource datasource - ^String (or username user) - ^String password) - (modify-connection opts)) - - datasource - (-> (.getConnection ^DataSource datasource) - (modify-connection opts)) - - factory - (-> (factory (dissoc db-spec :factory)) - (modify-connection opts)) - - connection-uri - (-> (if (and user password) - (DriverManager/getConnection connection-uri user password) - (DriverManager/getConnection connection-uri)) - (modify-connection opts)) - - (and dbtype dbname) - (let [;; allow aliases for dbtype - subprotocol (subprotocols dbtype dbtype) - host (or host "127.0.0.1") - port (or port (condp = subprotocol - "jtds:sqlserver" 1433 - "mysql" 3306 - "oracle:oci" 1521 - "oracle:thin" 1521 - "postgresql" 5432 - "sqlserver" 1433 - nil)) - db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") - url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) - (str "jdbc:" subprotocol ":" dbname) - (str "jdbc:" subprotocol ":" - (host-prefixes subprotocol "//") - host - (when port (str ":" port)) - db-sep dbname)) - etc (dissoc db-spec :dbtype :dbname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) - (-> (DriverManager/getConnection url (as-properties etc)) - (modify-connection opts))) - - (and subprotocol subname) - (let [;; allow aliases for subprotocols - subprotocol (subprotocols subprotocol subprotocol) - url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) - (-> (DriverManager/getConnection url (as-properties etc)) - (modify-connection opts))) - - name - (or (when-available javax.naming.InitialContext - (let [env (and environment (Hashtable. ^Map environment)) - context (javax.naming.InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (-> (.getConnection datasource) - (modify-connection opts)))) - (throw (ex-info (str "javax.naming.InitialContext is not available for: " - name) - db-spec))) - - :else - (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] - (throw (IllegalArgumentException. msg)))))) - -(defn- make-name-unique - "Given a collection of column names and a new column name, - return the new column name made unique, if necessary, by - appending _N where N is some unique integer suffix." - [cols col-name n] - (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] - (if (apply distinct? suffixed-name cols) - suffixed-name - (recur cols col-name (inc n))))) - -(defn- make-cols-unique - "Given a collection of column names, rename duplicates so - that the result is a collection of unique column names." - [cols] - (if (or (empty? cols) (apply distinct? cols)) - cols - (reduce (fn [unique-cols col-name] - (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) - -(defprotocol ISQLValue - "Protocol for creating SQL values from Clojure values. Default - implementations (for Object and nil) just return the argument, - but it can be extended to provide custom behavior to support - exotic types supported by different databases." - (sql-value [val] "Convert a Clojure value into a SQL value.")) - -(extend-protocol ISQLValue - Object - (sql-value [v] v) - - nil - (sql-value [_] nil)) - -(defprotocol ISQLParameter - "Protocol for setting SQL parameters in statement objects, which - can convert from Clojure values. The default implementation just - delegates the conversion to ISQLValue's sql-value conversion and - uses .setObject on the parameter. It can be extended to use other - methods of PreparedStatement to convert and set parameter values." - (set-parameter [val stmt ix] - "Convert a Clojure value into a SQL value and store it as the ix'th - parameter in the given SQL statement object.")) - -(extend-protocol ISQLParameter - Object - (set-parameter [v ^PreparedStatement s ^long i] - (.setObject s i (sql-value v))) - - nil - (set-parameter [_ ^PreparedStatement s ^long i] - (.setObject s i (sql-value nil)))) - -(defn- dft-set-parameters - "Default implementation of parameter setting for the given statement." - [stmt params] - (dorun (map-indexed (fn [ix value] - (set-parameter value stmt (inc ix))) - params))) - -(defprotocol IResultSetReadColumn - "Protocol for reading objects from the java.sql.ResultSet. Default - implementations (for Object and nil) return the argument, and the - Boolean implementation ensures a canonicalized true/false value, - but it can be extended to provide custom behavior for special types." - (result-set-read-column [val rsmeta idx] - "Function for transforming values after reading them from the database")) - -(extend-protocol IResultSetReadColumn - Object - (result-set-read-column [x _2 _3] x) - - Boolean - (result-set-read-column [x _2 _3] (if (= true x) true false)) - - nil - (result-set-read-column [_1 _2 _3] nil)) - -(defn- dft-read-columns - "Default implementation of reading row values from result set, given the - result set metadata and the indices." - [^ResultSet rs rsmeta idxs] - (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) - -(defn result-set-seq - "Creates and returns a lazy sequence of maps corresponding to the rows in the - java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it - respects the specified naming strategy. Duplicate column names are made unique - by appending _N before applying the naming strategy (where N is a unique integer), - unless the :as-arrays? option is :cols-as-is, in which case the column names - are untouched (the result set maintains column name/value order). - The :identifiers option specifies how SQL column names are converted to Clojure - keywords. The default is to convert them to lower case. - The :keywordize? option can be specified as false to opt-out of the conversion - to keywords. - The :qualifier option specifies the namespace qualifier for those identifiers - (and this may not be specified when :keywordize? is false)." - ([rs] (result-set-seq rs {})) - ([^ResultSet rs {:keys [as-arrays? identifiers keywordize? - qualifier read-columns] - :or {identifiers str/lower-case - keywordize? true - read-columns dft-read-columns}}] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) - identifier-fn (cond (and qualifier (not keywordize?)) - (throw (IllegalArgumentException. - (str ":qualifier is not allowed unless " - ":keywordize? is true"))) - (and qualifier keywordize?) - (comp (partial keyword qualifier) identifiers) - keywordize? - (comp keyword identifiers) - :else - identifiers) - keys (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - col-name-fn - (mapv identifier-fn)) - row-values (fn [] (read-columns rs rsmeta idxs)) - ;; This used to use create-struct (on keys) and then struct to populate each row. - ;; That had the side effect of preserving the order of columns in each row. As - ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't - ;; want to switch to records so we're using regular maps instead. We no longer - ;; guarantee column order in rows but using into {} should preserve order for up - ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying - ;; on the order-preserving behavior of structmaps, we can reconsider... - records (fn thisfn [] - (when (.next rs) - (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) - rows (fn thisfn [] - (when (.next rs) - (cons (vec (row-values)) (lazy-seq (thisfn)))))] - (if as-arrays? - (cons (vec keys) (rows)) - (records))))) - -(defn- execute-batch - "Executes a batch of SQL commands and returns a sequence of update counts. - (-2) indicates a single operation operating on an unknown number of rows. - Specifically, Oracle returns that and we must call getUpdateCount() to get - the actual number of rows affected. In general, operations return an array - of update counts, so this may not be a general solution for Oracle..." - [^Statement stmt] - (let [result (.executeBatch stmt)] - (if (and (= 1 (count result)) (= -2 (first result))) - (list (.getUpdateCount stmt)) - (seq result)))) - -(def ^{:private true - :doc "Map friendly :concurrency values to ResultSet constants."} - result-set-concurrency - {:read-only ResultSet/CONCUR_READ_ONLY - :updatable ResultSet/CONCUR_UPDATABLE}) - -(def ^{:private true - :doc "Map friendly :cursors values to ResultSet constants."} - result-set-holdability - {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT - :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) - -(def ^{:private true - :doc "Map friendly :type values to ResultSet constants."} - result-set-type - {:forward-only ResultSet/TYPE_FORWARD_ONLY - :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE - :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) - -(defn ^{:tag (class (into-array String []))} string-array - [return-keys] - (into-array String return-keys)) - -(defn prepare-statement - "Create a prepared statement from a connection, a SQL string and a map - of options: - :return-keys truthy | nil - default nil - for some drivers, this may be a vector of column names to identify - the generated keys to return, otherwise it should just be true - :result-type :forward-only | :scroll-insensitive | :scroll-sensitive - :concurrency :read-only | :updatable - :cursors :hold | :close - :fetch-size n - :max-rows n - :timeout n - Note that :result-type and :concurrency must be specified together as the - underlying Java API expects both (or neither)." - ([con sql] (prepare-statement con sql {})) - ([^java.sql.Connection con ^String sql - {:keys [return-keys result-type concurrency cursors - fetch-size max-rows timeout]}] - (let [^PreparedStatement - stmt (cond return-keys - (try - (when (or result-type concurrency cursors) - (throw (IllegalArgumentException. - (str ":concurrency, :cursors, and :result-type " - "may not be specified with :return-keys.")))) - (if (vector? return-keys) - (try - (.prepareStatement con sql (string-array return-keys)) - (catch Exception _ - ;; assume it is unsupported and try regular generated keys: - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) - (catch Exception _ - ;; assume it is unsupported and try basic PreparedStatement: - (.prepareStatement con sql))) - - (and result-type concurrency) - (if cursors - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency) - (get result-set-holdability cursors cursors)) - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency))) - - (or result-type concurrency cursors) - (throw (IllegalArgumentException. - (str ":concurrency, :cursors, and :result-type " - "may not be specified independently."))) - :else - (.prepareStatement con sql))] - (when fetch-size (.setFetchSize stmt fetch-size)) - (when max-rows (.setMaxRows stmt max-rows)) - (when timeout (.setQueryTimeout stmt timeout)) - stmt))) - -(defn print-sql-exception - "Prints the contents of an SQLException to *out*" - [^SQLException exception] - (let [^Class exception-class (class exception)] - (println - (format (str "%s:" \newline - " Message: %s" \newline - " SQLState: %s" \newline - " Error Code: %d") - (.getSimpleName exception-class) - (.getMessage exception) - (.getSQLState exception) - (.getErrorCode exception))))) - -(defn print-sql-exception-chain - "Prints a chain of SQLExceptions to *out*" - [^SQLException exception] - (loop [e exception] - (when e - (print-sql-exception e) - (recur (.getNextException e))))) - -(def ^{:private true} special-counts - {Statement/EXECUTE_FAILED "EXECUTE_FAILED" - Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) - -(defn print-update-counts - "Prints the update counts from a BatchUpdateException to *out*" - [^BatchUpdateException exception] - (println "Update counts:") - (dorun - (map-indexed - (fn [index count] - (println (format " Statement %d: %s" - index - (get special-counts count count)))) - (.getUpdateCounts exception)))) - -;; java.jdbc pieces rewritten to not use dynamic bindings - -(defn db-find-connection - "Returns the current database connection (or nil if there is none)" - ^java.sql.Connection [db] - (and (map? db) - (:connection db))) - -(defn db-connection - "Returns the current database connection (or throws if there is none)" - ^java.sql.Connection [db] - (or (db-find-connection db) - (throw (Exception. "no current database connection")))) - -(defn db-set-rollback-only! - "Marks the outermost transaction such that it will rollback rather than - commit when complete" - [db] - (reset! (:rollback db) true)) - -(defn db-unset-rollback-only! - "Marks the outermost transaction such that it will not rollback when complete" - [db] - (reset! (:rollback db) false)) - -(defn db-is-rollback-only - "Returns true if the outermost transaction will rollback rather than - commit when complete" - [db] - (deref (:rollback db))) - -(def ^:private - isolation-levels - "Transaction isolation levels." - {:none java.sql.Connection/TRANSACTION_NONE - :read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED - :read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED - :repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ - :serializable java.sql.Connection/TRANSACTION_SERIALIZABLE}) - -(def ^:private isolation-kws - "Map transaction isolation constants to our keywords." - (set/map-invert isolation-levels)) - -(defn get-isolation-level - "Given a db-spec (with an optional connection), return the current - transaction isolation level, if known. Return nil if there is no - active connection in the db-spec. Return :unknown if we do not - recognize the isolation level." - [db] - (when-let [con (db-find-connection db)] - (isolation-kws (.getTransactionIsolation con) :unknown))) - -(defn db-transaction* - "Evaluates func as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If rollback is set within scope of the outermost transaction, - the entire transaction will be rolled back rather than committed when - complete. - The isolation option may be :none, :read-committed, :read-uncommitted, - :repeatable-read, or :serializable. Note that not all databases support - all of those isolation levels, and may either throw an exception or - substitute another isolation level. - The read-only? option puts the transaction in readonly mode (if supported)." - ([db func] (db-transaction* db func {})) - ([db func opts] - (let [{:keys [isolation read-only?] :as opts} - (merge (when (map? db) db) opts)] - (if (zero? (get-level db)) - (if-let [con (db-find-connection db)] - (let [nested-db (inc-level db) - auto-commit (.getAutoCommit con) - old-isolation (.getTransactionIsolation con) - old-readonly (.isReadOnly con)] - (io! - (when isolation - (.setTransactionIsolation con (isolation isolation-levels))) - (when read-only? - (.setReadOnly con true)) - (.setAutoCommit con false) - (try - (let [result (func nested-db)] - (if (db-is-rollback-only nested-db) - (.rollback con) - (.commit con)) - result) - (catch Throwable t - (try - (.rollback con) - (catch Throwable rb - ;; combine both exceptions - (throw (ex-info (str "Rollback failed handling \"" - (.getMessage t) - "\"") - {:rollback rb - :handling t})))) - (throw t)) - (finally - (db-unset-rollback-only! nested-db) - ;; the following can throw SQLExceptions but we do not - ;; want those to replace any exception currently being - ;; handled -- and if the connection got closed, we just - ;; want to ignore exceptions here anyway - (try - (.setAutoCommit con auto-commit) - (catch Exception _)) - (when isolation - (try - (.setTransactionIsolation con old-isolation) - (catch Exception _))) - (when read-only? - (try - (.setReadOnly con old-readonly) - (catch Exception _))))))) - (with-open [con (get-connection db opts)] - (db-transaction* (add-connection db con) func opts))) - (do - (when (and isolation - (let [con (db-find-connection db)] - (not= (isolation isolation-levels) - (.getTransactionIsolation con)))) - (let [msg "Nested transactions may not have different isolation levels"] - (throw (IllegalStateException. msg)))) - (func (inc-level db))))))) - -(defmacro with-db-transaction - "Evaluates body in the context of a transaction on the specified database connection. - The binding provides the database connection for the transaction and the name to which - that is bound for evaluation of the body. The binding may also specify the isolation - level for the transaction, via the :isolation option and/or set the transaction to - readonly via the :read-only? option. - (with-db-transaction [t-con db-spec {:isolation level :read-only? true}] - ... t-con ...) - See db-transaction* for more details." - [binding & body] - `(db-transaction* ~(second binding) - (^{:once true} fn* [~(first binding)] ~@body) - ~@(rest (rest binding)))) - -(defmacro with-db-connection - "Evaluates body in the context of an active connection to the database. - (with-db-connection [con-db db-spec opts] - ... con-db ...)" - [binding & body] - `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] - (with-open [con# (get-connection db-spec# opts#)] - (let [~(first binding) (add-connection db-spec# con#)] - ~@body)))) - -(defmacro with-db-metadata - "Evaluates body in the context of an active connection with metadata bound - to the specified name. See also metadata-result for dealing with the results - of operations that retrieve information from the metadata. - (with-db-metadata [md db-spec opts] - ... md ...)" - [binding & body] - `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] - (with-open [con# (get-connection db-spec# opts#)] - (let [~(first binding) (.getMetaData con#)] - ~@body)))) - -(defn metadata-result - "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, - else return it as-is. This makes working with metadata easier. - Also accepts an option map containing :identifiers, :keywordize?, :qualifier, - :as-arrays?, :row-fn,and :result-set-fn to control how the ResultSet is - transformed and returned. See query for more details." - ([rs-or-value] (metadata-result rs-or-value {})) - ([rs-or-value opts] - (let [{:keys [as-arrays? result-set-fn row-fn] :as opts} - (merge {:identifiers str/lower-case - :keywordize? true - :read-columns dft-read-columns - :row-fn identity} opts) - result-set-fn (or result-set-fn (if as-arrays? vec doall))] - (if (instance? java.sql.ResultSet rs-or-value) - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rs-or-value opts)) - rs-or-value)))) - -(defmacro metadata-query - "Given a Java expression that extracts metadata (in the context of with-db-metadata), - and a map of options like metadata-result, manage the connection for a single - metadata-based query. Example usage: - - (with-db-metadata [meta db-spec] - (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) - {:row-fn ... :result-set-fn ...}))" - [meta-query & opt-args] - `(with-open [rs# ~meta-query] - (metadata-result rs# ~@opt-args))) - -(defn db-do-commands - "Executes SQL commands on the specified database connection. Wraps the commands - in a transaction if transaction? is true. transaction? can be ommitted and it - defaults to true. Accepts a single SQL command (string) or a vector of them. - Uses executeBatch. This may affect what SQL you can run via db-do-commands." - ([db sql-commands] - (db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands))) - ([db transaction? sql-commands] - (if (string? sql-commands) - (db-do-commands db transaction? [sql-commands]) - (if-let [con (db-find-connection db)] - (with-open [^Statement stmt (.createStatement con)] - (doseq [^String cmd sql-commands] - (.addBatch stmt cmd)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt))) - (with-open [con (get-connection db)] - (db-do-commands (add-connection db con) transaction? sql-commands)))))) - -(defn- db-do-execute-prepared-return-keys - "Executes a PreparedStatement, optionally in a transaction, and (attempts to) - return any generated keys." - [db ^PreparedStatement stmt param-group opts] - (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts) - exec-and-return-keys - (^{:once true} fn* [] - (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs opts))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))] - ((:set-parameters opts dft-set-parameters) stmt param-group) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (exec-and-return-keys)) - (exec-and-return-keys)))) - -(defn- sql-stmt? - "Given an expression, return true if it is either a string (SQL) or a - PreparedStatement." - [expr] - (or (string? expr) (instance? PreparedStatement expr))) - -(defn db-do-prepared-return-keys - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. The param-group is a seq of values for all of - the parameters. transaction? can be ommitted and will default to true. - Return the generated keys for the (single) update/insert. - A PreparedStatement may be passed in, instead of a SQL string, in which - case :return-keys MUST BE SET on that PreparedStatement!" - ([db sql-params] - (db-do-prepared-return-keys db true sql-params {})) - ([db transaction? sql-params] - (if (map? sql-params) - (db-do-prepared-return-keys db true transaction? sql-params) - (db-do-prepared-return-keys db transaction? sql-params {}))) - ([db transaction? sql-params opts] - (let [opts (merge (when (map? db) db) opts)] - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] - (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db opts)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) - -(defn- db-do-execute-prepared-statement - "Execute a PreparedStatement, optionally in a transaction." - [db ^PreparedStatement stmt param-groups opts] - (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts)] - (if (empty? param-groups) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) - (vector (.executeUpdate stmt))) - (do - (doseq [param-group param-groups] - ((:set-parameters opts dft-set-parameters) stmt param-group) - (.addBatch stmt)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt)))))) - -(defn db-do-prepared - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. Each param-group is a seq of values for all of - the parameters. transaction? can be omitted and defaults to true. - The sql parameter can either be a SQL string or a PreparedStatement. - Return a seq of update counts (one count for each param-group)." - ([db sql-params] - (db-do-prepared db true sql-params {})) - ([db transaction? sql-params] - (if (map? sql-params) - (db-do-prepared db true transaction? sql-params) - (db-do-prepared db transaction? sql-params {}))) - ([db transaction? sql-params opts] - (let [opts (merge (when (map? db) db) opts)] - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - params (if (or (:multi? opts) (empty? params)) params [params])] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db opts)] - (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) - -(defn db-query-with-resultset - "Executes a query, then evaluates func passing in the raw ResultSet as an - argument. The second argument is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - The opts map is passed to prepare-statement. - Uses executeQuery. This may affect what SQL you can run via query." - ([db sql-params func] (db-query-with-resultset db sql-params func {})) - ([db sql-params func opts] - (let [opts (merge (when (map? db) db) opts) - [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] - ((:set-parameters opts dft-set-parameters) stmt params) - (with-open [rset (.executeQuery stmt)] - (func rset)))] - (when-not (sql-stmt? sql) - (let [^Class sql-class (class sql) - ^String msg (format "\"%s\" expected %s %s, found %s %s" - "sql-params" - "vector" - "[sql param*]" - (.getName sql-class) - (pr-str sql))] - (throw (IllegalArgumentException. msg)))) - (if (instance? PreparedStatement sql) - (let [^PreparedStatement stmt sql] - (run-query-with-params stmt)) - (if-let [con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (run-query-with-params stmt)) - (with-open [con (get-connection db opts)] - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (run-query-with-params stmt)))))))) - -;; top-level API for actual SQL operations - -(defn query - "Given a database connection and a vector containing SQL and optional parameters, - perform a simple database query. The options specify how to construct the result - set (and are also passed to prepare-statement as needed): - :as-arrays? - return the results as a set of arrays, default false. - :identifiers - applied to each column name in the result set, default lower-case - :keywordize? - defaults to true, can be false to opt-out of converting - identifiers to keywords - :qualifier - optionally provides the namespace qualifier for identifiers - :result-set-fn - applied to the entire result set, default doall / vec - if :as-arrays? true, :result-set-fn will default to vec - if :as-arrays? false, :result-set-fn will default to doall - :row-fn - applied to each row as the result set is constructed, default identity - The second argument is a vector containing a SQL string or PreparedStatement, followed - by any parameters it needs. - See also prepare-statement for additional options." - ([db sql-params] (query db sql-params {})) - ([db sql-params opts] - (let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts} - (merge {:explain-fn println :identifiers str/lower-case - :keywordize? true - :read-columns dft-read-columns :row-fn identity} - (when (map? db) db) - opts) - result-set-fn (or result-set-fn (if as-arrays? vec doall)) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (when (and explain? (string? (first sql-params-vector))) - (query db (into [(str (if (string? explain?) explain? "EXPLAIN") - " " - (first sql-params-vector))] - (rest sql-params-vector)) - (-> opts - (dissoc :explain? :result-set-fn :row-fn) - (assoc :result-set-fn explain-fn)))) - (db-query-with-resultset db sql-params-vector - (^{:once true} fn* [rset] - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rset opts))) - opts)))) - -(defn reducible-result-set - "Given a java.sql.ResultSet return a reducible collection. - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce - Note: :as-arrays? is not accepted here." - [^ResultSet rs {:keys [identifiers keywordize? qualifier read-columns] - :or {identifiers str/lower-case - keywordize? true - read-columns dft-read-columns}}] - (let [identifier-fn (cond (and qualifier (not keywordize?)) - (throw (IllegalArgumentException. - (str ":qualifier is not allowed unless " - ":keywordize? is true"))) - (and qualifier keywordize?) - (comp (partial keyword qualifier) identifiers) - keywordize? - (comp keyword identifiers) - :else - identifiers) - make-keys (fn [idxs ^ResultSetMetaData rsmeta] - (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - (make-cols-unique) - (mapv identifier-fn))) - init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init] - (loop [init' init] - (if (.next rs) - (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] - (if (reduced? result) - @result - (recur result))) - init')))] - (reify clojure.lang.IReduce - (reduce [this f] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (make-keys idxs rsmeta)] - (if (.next rs) - ;; reduce init is first row of ResultSet - (init-reduce keys rs rsmeta idxs f - (zipmap keys (read-columns rs rsmeta idxs))) - ;; no rows so call 0-arity f to get result value - ;; per reduce docstring contract - (f)))) - (reduce [this f init] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (make-keys idxs rsmeta)] - (init-reduce keys rs rsmeta idxs f init)))))) - -(defn reducible-query - "Given a database connection, a vector containing SQL and optional parameters, - return a reducible collection. When reduced, it will start the database query - and reduce the result set, and then close the connection: - (transduce (map :cost) + (reducible-query db sql-params)) - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce - The following options from query etc are not accepted here: - :as-arrays? :explain :explain-fn :result-set-fn :row-fn - See also prepare-statement for additional options." - ([db sql-params] (reducible-query db sql-params {})) - ([db sql-params opts] - (let [{:keys [reducing-fn] :as opts} - (merge {:identifiers str/lower-case :keywordize? true - :read-columns dft-read-columns} - (when (map? db) db) - opts) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (reify clojure.lang.IReduce - (reduce [this f] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f (reducible-result-set rset opts))) - opts)) - (reduce [this f init] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts))) - opts)))))) - -(defn- direction - "Given an entities function, a column name, and a direction, - return the matching SQL column / order. - Throw an exception for an invalid direction." - [entities c d] - (str (as-sql-name entities c) " " - (if-let [dir (#{"ASC" "DESC"} (str/upper-case (name d)))] - dir - (throw (IllegalArgumentException. (str "expected :asc or :desc, found: " d)))))) - -(defn- order-by-sql - "Given a sequence of column specs and an entities function, return - a SQL fragment for the ORDER BY clause. A column spec may be a name - (either a string or keyword) or a map from column name to direction - (:asc or :desc)." - [order-by entities] - (str/join ", " (mapcat (fn [col] - (if (map? col) - (reduce-kv (fn [v c d] - (conj v (direction entities c d))) - [] - col) - [(direction entities col :asc)])) order-by))) - -(defn find-by-keys - "Given a database connection, a table name, a map of column name/value - pairs, and an optional options map, return any matching rows. - An :order-by option may be supplied to sort the rows by a sequence of - columns, e.g,. {:order-by [:name {:age :desc]}" - ([db table columns] (find-by-keys db table columns {})) - ([db table columns opts] - (let [{:keys [entities order-by] :as opts} - (merge {:entities identity} (when (map? db) db) opts) - ks (keys columns) - vs (vals columns)] - (query db (into [(str "SELECT * FROM " (table-str table entities) - " WHERE " (str/join " AND " - (kv-sql ks vs entities " IS NULL")) - (when (seq order-by) - (str " ORDER BY " - (order-by-sql order-by entities))))] - (remove nil? vs)) - opts)))) - -(defn get-by-id - "Given a database connection, a table name, a primary key value, an - optional primary key column name, and an optional options map, return - a single matching row, or nil. - The primary key column name defaults to :id." - ([db table pk-value] (get-by-id db table pk-value :id {})) - ([db table pk-value pk-name-or-opts] - (if (map? pk-name-or-opts) - (get-by-id db table pk-value :id pk-name-or-opts) - (get-by-id db table pk-value pk-name-or-opts {}))) - ([db table pk-value pk-name opts] - (let [opts (merge (when (map? db) db) opts) - r-s-fn (or (:result-set-fn opts) identity)] - (find-by-keys db table {pk-name pk-value} - (assoc opts :result-set-fn (comp first r-s-fn)))))) - -(defn execute! - "Given a database connection and a vector containing SQL (or PreparedStatement) - followed by optional parameters, perform a general (non-select) SQL operation. - The :transaction? option specifies whether to run the operation in a - transaction or not (default true). - If the :multi? option is false (the default), the SQL statement should be - followed by the parameters for that statement. - If the :multi? option is true, the SQL statement should be followed by one or - more vectors of parameters, one for each application of the SQL statement. - If there are no parameters specified, executeUpdate will be used, otherwise - executeBatch will be used. This may affect what SQL you can run via execute!" - ([db sql-params] (execute! db sql-params {})) - ([db sql-params opts] - (let [{:keys [transaction?] :as opts} - (merge {:transaction? true :multi? false} (when (map? db) db) opts) - execute-helper (^{:once true} fn* [db] - (db-do-prepared db transaction? sql-params opts))] - (if-let [con (db-find-connection db)] - (execute-helper db) - (with-open [con (get-connection db opts)] - (execute-helper (add-connection db con))))))) - -(defn- delete-sql - "Given a table name, a where class and its parameters and an optional entities spec, - return a vector of the SQL for that delete operation followed by its parameters. The - entities spec (default 'as-is') specifies how to transform column names." - [table [where & params] entities] - (into [(str "DELETE FROM " (table-str table entities) - (when where " WHERE ") where)] - params)) - -(defn delete! - "Given a database connection, a table name and a where clause of columns to match, - perform a delete. The options may specify how to transform column names in the - map (default 'as-is') and whether to run the delete in a transaction (default true). - Example: - (delete! db :person [\"zip = ?\" 94546]) - is equivalent to: - (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" - ([db table where-clause] (delete! db table where-clause {})) - ([db table where-clause opts] - (let [{:keys [entities] :as opts} - (merge {:entities identity :transaction? true} (when (map? db) db) opts)] - (execute! db (delete-sql table where-clause entities) opts)))) - -(defn- multi-insert-helper - "Given a (connected) database connection and some SQL statements (for multiple - inserts), run a prepared statement on each and return any generated keys. - Note: we are eager so an unrealized lazy-seq cannot escape from the connection." - [db stmts opts] - (doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts))) - -(defn- insert-helper - "Given a (connected) database connection, a transaction flag and some SQL statements - (for one or more inserts), run a prepared statement or a sequence of them." - [db transaction? stmts opts] - (if transaction? - (with-db-transaction [t-db db] (multi-insert-helper t-db stmts opts)) - (multi-insert-helper db stmts opts))) - -(defn- col-str - "Transform a column spec to an entity name for SQL. The column spec may be a - string, a keyword or a map with a single pair - column name and alias." - [col entities] - (if (map? col) - (let [[k v] (first col)] - (str (as-sql-name entities k) " AS " (as-sql-name entities v))) - (as-sql-name entities col))) - -(defn- insert-multi-row-sql - "Given a table and a list of columns, followed by a list of column value sequences, - return a vector of the SQL needed for the insert followed by the list of column - value sequences. The entities function specifies how column names are transformed." - [table columns values entities] - (let [nc (count columns) - vcs (map count values)] - (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) - (throw (IllegalArgumentException. "insert! called with inconsistent number of columns / values")) - (into [(str "INSERT INTO " (table-str table entities) - (when (seq columns) - (str " ( " - (str/join ", " (map (fn [col] (col-str col entities)) columns)) - " )")) - " VALUES ( " - (str/join ", " (repeat (first vcs) "?")) - " )")] - values)))) - -(defn- insert-single-row-sql - "Given a table and a map representing a row, return a vector of the SQL needed for - the insert followed by the list of column values. The entities function specifies - how column names are transformed." - [table row entities] - (let [ks (keys row)] - (into [(str "INSERT INTO " (table-str table entities) " ( " - (str/join ", " (map (fn [col] (col-str col entities)) ks)) - " ) VALUES ( " - (str/join ", " (repeat (count ks) "?")) - " )")] - (vals row)))) - -(defn- insert-rows! - "Given a database connection, a table name, a sequence of rows, and an options - map, insert the rows into the database." - [db table rows opts] - (let [{:keys [entities transaction?] :as opts} - (merge {:entities identity :identifiers str/lower-case - :keywordize? true :transaction? true} - (when (map? db) db) - opts) - sql-params (map (fn [row] - (when-not (map? row) - (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) - (insert-single-row-sql table row entities)) rows)] - (if-let [con (db-find-connection db)] - (insert-helper db transaction? sql-params opts) - (with-open [con (get-connection db opts)] - (insert-helper (add-connection db con) transaction? sql-params opts))))) - -(defn- insert-cols! - "Given a database connection, a table name, a sequence of columns names, a - sequence of vectors of column values, one per row, and an options map, - insert the rows into the database." - [db table cols values opts] - (let [{:keys [entities transaction?] :as opts} - (merge {:entities identity :transaction? true} (when (map? db) db) opts) - sql-params (insert-multi-row-sql table cols values entities)] - (if-let [con (db-find-connection db)] - (db-do-prepared db transaction? sql-params (assoc opts :multi? true)) - (with-open [con (get-connection db opts)] - (db-do-prepared (add-connection db con) transaction? sql-params - (assoc opts :multi? true)))))) - -(defn insert! - "Given a database connection, a table name and either a map representing a rows, - or a list of column names followed by a list of column values also representing - a single row, perform an insert. - When inserting a row as a map, the result is the database-specific form of the - generated keys, if available (note: PostgreSQL returns the whole row). - When inserting a row as a list of column values, the result is the count of - rows affected (1), if available (from getUpdateCount after executeBatch). - The row map or column value vector may be followed by a map of options: - The :transaction? option specifies whether to run in a transaction or not. - The default is true (use a transaction). The :entities option specifies how - to convert the table name and column names to SQL entities." - ([db table row] (insert! db table row {})) - ([db table cols-or-row values-or-opts] - (if (map? values-or-opts) - (insert-rows! db table [cols-or-row] values-or-opts) - (insert-cols! db table cols-or-row [values-or-opts] {}))) - ([db table cols values opts] - (insert-cols! db table cols [values] opts))) - -(defn insert-multi! - "Given a database connection, a table name and either a sequence of maps (for - rows) or a sequence of column names, followed by a sequence of vectors (for - the values in each row), and possibly a map of options, insert that data into - the database. - - When inserting rows as a sequence of maps, the result is a sequence of the - generated keys, if available (note: PostgreSQL returns the whole rows). A - separate database operation is used for each row inserted. This may be slow - for if a large sequence of maps is provided. - - When inserting rows as a sequence of lists of column values, the result is - a sequence of the counts of rows affected (a sequence of 1's), if available. - Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch! - A single database operation is used to insert all the rows at once. This may - be much faster than inserting a sequence of rows (which performs an insert for - each map in the sequence). - - The :transaction? option specifies whether to run in a transaction or not. - The default is true (use a transaction). The :entities option specifies how - to convert the table name and column names to SQL entities." - ([db table rows] (insert-rows! db table rows {})) - ([db table cols-or-rows values-or-opts] - (if (map? values-or-opts) - (insert-rows! db table cols-or-rows values-or-opts) - (insert-cols! db table cols-or-rows values-or-opts {}))) - ([db table cols values opts] - (insert-cols! db table cols values opts))) - -(defn- update-sql - "Given a table name, a map of columns to set, a optional map of columns to - match, and an entities, return a vector of the SQL for that update followed - by its parameters. Example: - (update :person {:zip 94540} [\"zip = ?\" 94546] identity) - returns: - [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" - [table set-map [where & params] entities] - (let [ks (keys set-map) - vs (vals set-map)] - (cons (str "UPDATE " (table-str table entities) - " SET " (str/join - "," - (kv-sql ks vs entities " = NULL")) - (when where " WHERE ") - where) - (concat (remove nil? vs) params)))) - -(defn update! - "Given a database connection, a table name, a map of column values to set and a - where clause of columns to match, perform an update. The options may specify - how column names (in the set / match maps) should be transformed (default - 'as-is') and whether to run the update in a transaction (default true). - Example: - (update! db :person {:zip 94540} [\"zip = ?\" 94546]) - is equivalent to: - (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" - ([db table set-map where-clause] (update! db table set-map where-clause {})) - ([db table set-map where-clause opts] - (let [{:keys [entities] :as opts} - (merge {:entities identity :transaction? true} (when (map? db) db) opts)] - (execute! db (update-sql table set-map where-clause entities) opts)))) - -(defn create-table-ddl - "Given a table name and a vector of column specs, return the DDL string for - creating that table. Each column spec is, in turn, a vector of keywords or - strings that is converted to strings and concatenated with spaces to form - a single column description in DDL, e.g., - [:cost :int \"not null\"] - [:name \"varchar(32)\"] - The first element of a column spec is treated as a SQL entity (so if you - provide the :entities option, that will be used to transform it). The - remaining elements are left as-is when converting them to strings. - An options map may be provided that can contain: - :table-spec -- a string that is appended to the DDL -- and/or - :entities -- a function to specify how column names are transformed. - :conditional? -- either a boolean, indicating whether to add 'IF NOT EXISTS', - or a string, which is inserted literally before the table name, or a - function of two arguments (table name and the create statement), that can - manipulate the generated statement to better support other databases, e.g., - MS SQL Server which need to wrap create table in an existence query." - ([table specs] (create-table-ddl table specs {})) - ([table specs opts] - (let [table-spec (:table-spec opts) - conditional? (:conditional? opts) - entities (:entities opts identity) - table-name (as-sql-name entities table) - table-spec-str (or (and table-spec (str " " table-spec)) "") - spec-to-string (fn [spec] - (try - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))) - (catch Exception _ - (throw (IllegalArgumentException. - "column spec is not a sequence of keywords / strings")))))] - (cond->> (format "CREATE TABLE%s %s (%s)%s" - (cond (or (nil? conditional?) - (instance? Boolean conditional?)) - (if conditional? " IF NOT EXISTS" "") - (fn? conditional?) - "" - :else - (str " " conditional?)) - table-name - (str/join ", " (map spec-to-string specs)) - table-spec-str) - (fn? conditional?) (conditional? table-name))))) - -(defn drop-table-ddl - "Given a table name, return the DDL string for dropping that table. - An options map may be provided that can contain: - :entities -- a function to specify how column names are transformed. - :conditional? -- either a boolean, indicating whether to add 'IF EXISTS', - or a string, which is inserted literally before the table name, or a - function of two arguments (table name and the create statement), that can - manipulate the generated statement to better support other databases, e.g., - MS SQL Server which need to wrap create table in an existence query." - ([table] (drop-table-ddl table {})) - ([table {:keys [entities conditional?] :or {entities identity}}] - (let [table-name (as-sql-name entities table)] - (cond->> (format "DROP TABLE%s %s" - (cond (or (nil? conditional?) - (instance? Boolean conditional?)) - (if conditional? " IF EXISTS" "") - (fn? conditional?) - "" - :else - (str " " conditional?)) - table-name) - (fn? conditional?) (conditional? table-name))))) +;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; The use and distribution terms for this software are covered by +;; the Eclipse Public License 1.0 +;; (http://opensource.org/licenses/eclipse-1.0.php) which can be +;; found in the file epl-v10.html at the root of this distribution. +;; By using this software in any fashion, you are agreeing to be +;; bound by the terms of this license. You must not remove this +;; notice, or any other, from this software. +;; +;; jdbc.clj +;; +;; A Clojure interface to sql databases via jdbc +;; +;; scgilardi (gmail) +;; Created 2 April 2008 +;; +;; seancorfield (gmail) +;; Migrated from clojure.contrib.sql 17 April 2011 + +(ns + ^{:author "Stephen C. Gilardi, Sean Corfield", + :doc "A Clojure interface to SQL databases via JDBC + +clojure.java.jdbc provides a simple abstraction for CRUD (create, read, +update, delete) operations on a SQL database, along with basic transaction +support. Basic DDL operations are also supported (create table, drop table, +access to table metadata). + +Maps are used to represent records, making it easy to store and retrieve +data. Results can be processed using any standard sequence operations. + +For most operations, Java's PreparedStatement is used so your SQL and +parameters can be represented as simple vectors where the first element +is the SQL string, with ? for each parameter, and the remaining elements +are the parameter values to be substituted. In general, operations return +the number of rows affected, except for a single record insert where any +generated keys are returned (as a map). + +For more documentation, see: + +http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} + clojure.java.jdbc + (:require [clojure.set :as set] + [clojure.string :as str] + [clojure.walk :as walk]) + (:import (java.net URI) + (java.sql BatchUpdateException DriverManager + PreparedStatement ResultSet ResultSetMetaData + SQLException Statement Types) + (java.util Hashtable Map Properties) + (javax.sql DataSource))) + +(defn as-sql-name + "Given a naming strategy function and a keyword or string, return + a string per that naming strategy. + A name of the form x.y is treated as multiple names, x, y, etc, + and each are turned into strings via the naming strategy and then + joined back together so x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." + [f x] + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\.")))))) + +(defn quoted + "Given a (vector) pair of delimiters (characters or strings), return a naming + strategy function that will quote SQL entities with them. + Given a single delimiter, treat it as a (vector) pair of that delimiter. + ((quoted [\\[ \\]]) \"foo\") will return \"[foo]\" -- for MS SQL Server + ((quoted \\`') \"foo\") will return \"`foo`\" -- for MySQL + Intended to be used with :entities to provide a quoting (naming) strategy that + is appropriate for your database." + [q] + (cond (vector? q) + (fn [x] + (str (first q) x (last q))) + (keyword? q) + (case q + :ansi (quoted \") + :mysql (quoted \`) + :oracle (quoted \") + :sqlserver (quoted [\[ \]])) + :else + (quoted [q q]))) + +(defn- table-str + "Transform a table spec to an entity name for SQL. The table spec may be a + string, a keyword or a map with a single pair - table name and alias." + [table entities] + (let [entities (or entities identity)] + (if (map? table) + (let [[k v] (first table)] + (str (as-sql-name entities k) " " (as-sql-name entities v))) + (as-sql-name entities table)))) + +(defn- kv-sql + "Given a sequence of column name keys and a matching sequence of column + values, and an entities mapping function, return a sequence of SQL fragments + that can be joined for part of an UPDATE SET or a SELECT WHERE clause. + Note that we pass the appropriate operator for NULL since it is different + in each case." + [ks vs entities null-op] + (map (fn [k v] + (str (as-sql-name entities k) + (if (nil? v) null-op " = ?"))) + ks vs)) + +(defn- ^Properties as-properties + "Convert any seq of pairs to a java.utils.Properties instance. + Uses as-sql-name to convert both keys and values into strings." + [m] + (let [p (Properties.)] + (doseq [[k v] m] + (.setProperty p (as-sql-name identity k) + (if (instance? clojure.lang.Named v) + (as-sql-name identity v) + (str v)))) + p)) + +;; convenience for working with different forms of connections +(defprotocol Connectable + (add-connection [db connection]) + (get-level [db])) + +(defn- inc-level + "Increment the nesting level for a transacted database connection. + If we are at the top level, also add in a rollback state." + [db] + (let [nested-db (update-in db [:level] (fnil inc 0))] + (if (= 1 (:level nested-db)) + (assoc nested-db :rollback (atom false)) + nested-db))) + +(extend-protocol Connectable + String + (add-connection [s connection] {:connection connection :level 0 :connection-string s}) + (get-level [_] 0) + + clojure.lang.Associative + (add-connection [m connection] (assoc m :connection connection)) + (get-level [m] (or (:level m) 0)) + + nil + (add-connection [_ connection] {:connection connection :level 0 :legacy true}) + (get-level [_] 0)) + +(def ^:private classnames + "Map of subprotocols to classnames. dbtype specifies one of these keys. + The subprotocols map below provides aliases for dbtype." + {"derby" "org.apache.derby.jdbc.EmbeddedDriver" + "h2" "org.h2.Driver" + "hsqldb" "org.hsqldb.jdbcDriver" + "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" + "mysql" "com.mysql.jdbc.Driver" + "oracle:oci" "oracle.jdbc.OracleDriver" + "oracle:thin" "oracle.jdbc.OracleDriver" + "postgresql" "org.postgresql.Driver" + "pgsql" "com.impossibl.postgres.jdbc.PGDriver" + "redshift" "com.amazon.redshift.jdbc.Driver" + "sqlite" "org.sqlite.JDBC" + "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) + +(def ^:private subprotocols + "Map of schemes to subprotocols. Used to provide aliases for dbtype." + {"hsql" "hsqldb" + "jtds" "jtds:sqlserver" + "mssql" "sqlserver" + "oracle" "oracle:thin" + "postgres" "postgresql"}) + +(def ^:private host-prefixes + "Map of subprotocols to non-standard host-prefixes. + Anything not listed is assumed to use //." + {"oracle:oci" "@" + "oracle:thin" "@"}) + +(defn- parse-properties-uri [^URI uri] + (let [host (.getHost uri) + port (if (pos? (.getPort uri)) (.getPort uri)) + path (.getPath uri) + scheme (.getScheme uri) + subprotocol (subprotocols scheme scheme) + host-prefix (host-prefixes subprotocol "//") + ^String query (.getQuery uri) + query-parts (and query + (for [^String kvs (.split query "&")] + ((juxt first second) (.split kvs "="))))] + (merge + {:subname (if host + (if port + (str host-prefix host ":" port path) + (str host-prefix host path)) + (.getSchemeSpecificPart uri)) + :subprotocol subprotocol} + (if-let [user-info (.getUserInfo uri)] + {:user (first (str/split user-info #":")) + :password (second (str/split user-info #":"))}) + (walk/keywordize-keys (into {} query-parts))))) + +(defn- strip-jdbc [^String spec] + (if (.startsWith spec "jdbc:") + (.substring spec 5) + spec)) + +;; feature testing macro, based on suggestion from Chas Emerick: +(defmacro when-available + [sym & body] + (try + (when (resolve sym) + (list* 'do body)) + (catch ClassNotFoundException _#))) + +(defn- modify-connection + "Given a database connection and a map of options, update the connection + as specified by the options." + ^java.sql.Connection + [^java.sql.Connection connection opts] + (when (contains? opts :auto-commit?) + (.setAutoCommit connection (:auto-commit? opts))) + (when (contains? opts :read-only?) + (.setReadOnly connection (:read-only? opts))) + connection) + +(defn get-connection + "Creates a connection to a database. db-spec is usually a map containing connection + parameters but can also be a URI or a String. The various possibilities are described + below: + + DriverManager (preferred): + :dbtype (required) a String, the type of the database (the jdbc subprotocol) + :dbname (required) a String, the name of the database + :classname (optional) a String, the jdbc driver class name + :host (optional) a String, the host name/IP of the database + (defaults to 127.0.0.1) + :port (optional) a Long, the port of the database + (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) + (others) (optional) passed to the driver as properties + (may include :user and :password) + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + (both :user and :password may be specified as well, rather + than passing them as part of the connection string) + + Other formats accepted: + + Existing Connection: + :connection (required) an existing open connection that can be used + but cannot be closed (only the parent connection can be closed) + + DriverManager (alternative / legacy style): + :subprotocol (required) a String, the jdbc subprotocol + :subname (required) a String, the jdbc subname + :classname (optional) a String, the jdbc driver class name + (others) (optional) passed to the driver as properties + (may include :user and :password) + + Factory: + :factory (required) a function of one argument, a map of params + (others) (optional) passed to the factory function in a map + + DataSource: + :datasource (required) a javax.sql.DataSource + :username (optional) a String - deprecated, use :user instead + :user (optional) a String - preferred + :password (optional) a String, required if :user is supplied + + JNDI: + :name (required) a String or javax.naming.Name + :environment (optional) a java.util.Map + + java.net.URI: + Parsed JDBC connection string (see java.lang.String format next) + + java.lang.String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." + (^java.sql.Connection [db-spec] (get-connection db-spec {})) + (^java.sql.Connection + [{:keys [connection + factory + connection-uri + classname subprotocol subname + dbtype dbname host port + datasource username password user + name environment] + :as db-spec} + opts] + (cond + (string? db-spec) + (get-connection (URI. (strip-jdbc db-spec)) opts) + + (instance? URI db-spec) + (get-connection (parse-properties-uri db-spec) opts) + + connection + connection ;; do not apply opts here + + (or (and datasource username password) ; legacy + (and datasource user password)) ; preferred + (-> (.getConnection ^DataSource datasource + ^String (or username user) + ^String password) + (modify-connection opts)) + + datasource + (-> (.getConnection ^DataSource datasource) + (modify-connection opts)) + + factory + (-> (factory (dissoc db-spec :factory)) + (modify-connection opts)) + + connection-uri + (-> (if (and user password) + (DriverManager/getConnection connection-uri user password) + (DriverManager/getConnection connection-uri)) + (modify-connection opts)) + + (and dbtype dbname) + (let [;; allow aliases for dbtype + subprotocol (subprotocols dbtype dbtype) + host (or host "127.0.0.1") + port (or port (condp = subprotocol + "jtds:sqlserver" 1433 + "mysql" 3306 + "oracle:oci" 1521 + "oracle:thin" 1521 + "postgresql" 5432 + "sqlserver" 1433 + nil)) + db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") + url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) + (str "jdbc:" subprotocol ":" dbname) + (str "jdbc:" subprotocol ":" + (host-prefixes subprotocol "//") + host + (when port (str ":" port)) + db-sep dbname)) + etc (dissoc db-spec :dbtype :dbname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + + (and subprotocol subname) + (let [;; allow aliases for subprotocols + subprotocol (subprotocols subprotocol subprotocol) + url (format "jdbc:%s:%s" subprotocol subname) + etc (dissoc db-spec :classname :subprotocol :subname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + + name + (or (when-available javax.naming.InitialContext + (let [env (and environment (Hashtable. ^Map environment)) + context (javax.naming.InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (-> (.getConnection datasource) + (modify-connection opts)))) + (throw (ex-info (str "javax.naming.InitialContext is not available for: " + name) + db-spec))) + + :else + (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] + (throw (IllegalArgumentException. msg)))))) + +(defn- make-name-unique + "Given a collection of column names and a new column name, + return the new column name made unique, if necessary, by + appending _N where N is some unique integer suffix." + [cols col-name n] + (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] + (if (apply distinct? suffixed-name cols) + suffixed-name + (recur cols col-name (inc n))))) + +(defn- make-cols-unique + "Given a collection of column names, rename duplicates so + that the result is a collection of unique column names." + [cols] + (if (or (empty? cols) (apply distinct? cols)) + cols + (reduce (fn [unique-cols col-name] + (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) + +(defprotocol ISQLValue + "Protocol for creating SQL values from Clojure values. Default + implementations (for Object and nil) just return the argument, + but it can be extended to provide custom behavior to support + exotic types supported by different databases." + (sql-value [val] "Convert a Clojure value into a SQL value.")) + +(extend-protocol ISQLValue + Object + (sql-value [v] v) + + nil + (sql-value [_] nil)) + +(defprotocol ISQLParameter + "Protocol for setting SQL parameters in statement objects, which + can convert from Clojure values. The default implementation just + delegates the conversion to ISQLValue's sql-value conversion and + uses .setObject on the parameter. It can be extended to use other + methods of PreparedStatement to convert and set parameter values." + (set-parameter [val stmt ix] + "Convert a Clojure value into a SQL value and store it as the ix'th + parameter in the given SQL statement object.")) + +(extend-protocol ISQLParameter + Object + (set-parameter [v ^PreparedStatement s ^long i] + (.setObject s i (sql-value v))) + + nil + (set-parameter [_ ^PreparedStatement s ^long i] + (.setObject s i (sql-value nil)))) + +(defn- dft-set-parameters + "Default implementation of parameter setting for the given statement." + [stmt params] + (dorun (map-indexed (fn [ix value] + (set-parameter value stmt (inc ix))) + params))) + +(defprotocol IResultSetReadColumn + "Protocol for reading objects from the java.sql.ResultSet. Default + implementations (for Object and nil) return the argument, and the + Boolean implementation ensures a canonicalized true/false value, + but it can be extended to provide custom behavior for special types." + (result-set-read-column [val rsmeta idx] + "Function for transforming values after reading them from the database")) + +(extend-protocol IResultSetReadColumn + Object + (result-set-read-column [x _2 _3] x) + + Boolean + (result-set-read-column [x _2 _3] (if (= true x) true false)) + + nil + (result-set-read-column [_1 _2 _3] nil)) + +(defn- dft-read-columns + "Default implementation of reading row values from result set, given the + result set metadata and the indices." + [^ResultSet rs rsmeta idxs] + (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) + +(defn result-set-seq + "Creates and returns a lazy sequence of maps corresponding to the rows in the + java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it + respects the specified naming strategy. Duplicate column names are made unique + by appending _N before applying the naming strategy (where N is a unique integer), + unless the :as-arrays? option is :cols-as-is, in which case the column names + are untouched (the result set maintains column name/value order). + The :identifiers option specifies how SQL column names are converted to Clojure + keywords. The default is to convert them to lower case. + The :keywordize? option can be specified as false to opt-out of the conversion + to keywords. + The :qualifier option specifies the namespace qualifier for those identifiers + (and this may not be specified when :keywordize? is false)." + ([rs] (result-set-seq rs {})) + ([^ResultSet rs {:keys [as-arrays? identifiers keywordize? + qualifier read-columns] + :or {identifiers str/lower-case + keywordize? true + read-columns dft-read-columns}}] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) + identifier-fn (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers) + keys (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + col-name-fn + (mapv identifier-fn)) + row-values (fn [] (read-columns rs rsmeta idxs)) + ;; This used to use create-struct (on keys) and then struct to populate each row. + ;; That had the side effect of preserving the order of columns in each row. As + ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't + ;; want to switch to records so we're using regular maps instead. We no longer + ;; guarantee column order in rows but using into {} should preserve order for up + ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying + ;; on the order-preserving behavior of structmaps, we can reconsider... + records (fn thisfn [] + (when (.next rs) + (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) + rows (fn thisfn [] + (when (.next rs) + (cons (vec (row-values)) (lazy-seq (thisfn)))))] + (if as-arrays? + (cons (vec keys) (rows)) + (records))))) + +(defn- execute-batch + "Executes a batch of SQL commands and returns a sequence of update counts. + (-2) indicates a single operation operating on an unknown number of rows. + Specifically, Oracle returns that and we must call getUpdateCount() to get + the actual number of rows affected. In general, operations return an array + of update counts, so this may not be a general solution for Oracle..." + [^Statement stmt] + (let [result (.executeBatch stmt)] + (if (and (= 1 (count result)) (= -2 (first result))) + (list (.getUpdateCount stmt)) + (seq result)))) + +(def ^{:private true + :doc "Map friendly :concurrency values to ResultSet constants."} + result-set-concurrency + {:read-only ResultSet/CONCUR_READ_ONLY + :updatable ResultSet/CONCUR_UPDATABLE}) + +(def ^{:private true + :doc "Map friendly :cursors values to ResultSet constants."} + result-set-holdability + {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT + :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) + +(def ^{:private true + :doc "Map friendly :type values to ResultSet constants."} + result-set-type + {:forward-only ResultSet/TYPE_FORWARD_ONLY + :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE + :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) + +(defn ^{:tag (class (into-array String []))} string-array + [return-keys] + (into-array String return-keys)) + +(defn prepare-statement + "Create a prepared statement from a connection, a SQL string and a map + of options: + :return-keys truthy | nil - default nil + for some drivers, this may be a vector of column names to identify + the generated keys to return, otherwise it should just be true + :result-type :forward-only | :scroll-insensitive | :scroll-sensitive + :concurrency :read-only | :updatable + :cursors :hold | :close + :fetch-size n + :max-rows n + :timeout n + Note that :result-type and :concurrency must be specified together as the + underlying Java API expects both (or neither)." + ([con sql] (prepare-statement con sql {})) + ([^java.sql.Connection con ^String sql + {:keys [return-keys result-type concurrency cursors + fetch-size max-rows timeout]}] + (let [^PreparedStatement + stmt (cond return-keys + (try + (when (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified with :return-keys.")))) + (if (vector? return-keys) + (try + (.prepareStatement con sql (string-array return-keys)) + (catch Exception _ + ;; assume it is unsupported and try regular generated keys: + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) + (catch Exception _ + ;; assume it is unsupported and try basic PreparedStatement: + (.prepareStatement con sql))) + + (and result-type concurrency) + (if cursors + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency) + (get result-set-holdability cursors cursors)) + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency))) + + (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified independently."))) + :else + (.prepareStatement con sql))] + (when fetch-size (.setFetchSize stmt fetch-size)) + (when max-rows (.setMaxRows stmt max-rows)) + (when timeout (.setQueryTimeout stmt timeout)) + stmt))) + +(defn print-sql-exception + "Prints the contents of an SQLException to *out*" + [^SQLException exception] + (let [^Class exception-class (class exception)] + (println + (format (str "%s:" \newline + " Message: %s" \newline + " SQLState: %s" \newline + " Error Code: %d") + (.getSimpleName exception-class) + (.getMessage exception) + (.getSQLState exception) + (.getErrorCode exception))))) + +(defn print-sql-exception-chain + "Prints a chain of SQLExceptions to *out*" + [^SQLException exception] + (loop [e exception] + (when e + (print-sql-exception e) + (recur (.getNextException e))))) + +(def ^{:private true} special-counts + {Statement/EXECUTE_FAILED "EXECUTE_FAILED" + Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) + +(defn print-update-counts + "Prints the update counts from a BatchUpdateException to *out*" + [^BatchUpdateException exception] + (println "Update counts:") + (dorun + (map-indexed + (fn [index count] + (println (format " Statement %d: %s" + index + (get special-counts count count)))) + (.getUpdateCounts exception)))) + +;; java.jdbc pieces rewritten to not use dynamic bindings + +(defn db-find-connection + "Returns the current database connection (or nil if there is none)" + ^java.sql.Connection [db] + (and (map? db) + (:connection db))) + +(defn db-connection + "Returns the current database connection (or throws if there is none)" + ^java.sql.Connection [db] + (or (db-find-connection db) + (throw (Exception. "no current database connection")))) + +(defn db-set-rollback-only! + "Marks the outermost transaction such that it will rollback rather than + commit when complete" + [db] + (reset! (:rollback db) true)) + +(defn db-unset-rollback-only! + "Marks the outermost transaction such that it will not rollback when complete" + [db] + (reset! (:rollback db) false)) + +(defn db-is-rollback-only + "Returns true if the outermost transaction will rollback rather than + commit when complete" + [db] + (deref (:rollback db))) + +(def ^:private + isolation-levels + "Transaction isolation levels." + {:none java.sql.Connection/TRANSACTION_NONE + :read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED + :read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED + :repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ + :serializable java.sql.Connection/TRANSACTION_SERIALIZABLE}) + +(def ^:private isolation-kws + "Map transaction isolation constants to our keywords." + (set/map-invert isolation-levels)) + +(defn get-isolation-level + "Given a db-spec (with an optional connection), return the current + transaction isolation level, if known. Return nil if there is no + active connection in the db-spec. Return :unknown if we do not + recognize the isolation level." + [db] + (when-let [con (db-find-connection db)] + (isolation-kws (.getTransactionIsolation con) :unknown))) + +(defn db-transaction* + "Evaluates func as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If rollback is set within scope of the outermost transaction, + the entire transaction will be rolled back rather than committed when + complete. + The isolation option may be :none, :read-committed, :read-uncommitted, + :repeatable-read, or :serializable. Note that not all databases support + all of those isolation levels, and may either throw an exception or + substitute another isolation level. + The read-only? option puts the transaction in readonly mode (if supported)." + ([db func] (db-transaction* db func {})) + ([db func opts] + (let [{:keys [isolation read-only?] :as opts} + (merge (when (map? db) db) opts)] + (if (zero? (get-level db)) + (if-let [con (db-find-connection db)] + (let [nested-db (inc-level db) + auto-commit (.getAutoCommit con) + old-isolation (.getTransactionIsolation con) + old-readonly (.isReadOnly con)] + (io! + (when isolation + (.setTransactionIsolation con (isolation isolation-levels))) + (when read-only? + (.setReadOnly con true)) + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-is-rollback-only nested-db) + (.rollback con) + (.commit con)) + result) + (catch Throwable t + (try + (.rollback con) + (catch Throwable rb + ;; combine both exceptions + (throw (ex-info (str "Rollback failed handling \"" + (.getMessage t) + "\"") + {:rollback rb + :handling t})))) + (throw t)) + (finally + (db-unset-rollback-only! nested-db) + ;; the following can throw SQLExceptions but we do not + ;; want those to replace any exception currently being + ;; handled -- and if the connection got closed, we just + ;; want to ignore exceptions here anyway + (try + (.setAutoCommit con auto-commit) + (catch Exception _)) + (when isolation + (try + (.setTransactionIsolation con old-isolation) + (catch Exception _))) + (when read-only? + (try + (.setReadOnly con old-readonly) + (catch Exception _))))))) + (with-open [con (get-connection db opts)] + (db-transaction* (add-connection db con) func opts))) + (do + (when (and isolation + (let [con (db-find-connection db)] + (not= (isolation isolation-levels) + (.getTransactionIsolation con)))) + (let [msg "Nested transactions may not have different isolation levels"] + (throw (IllegalStateException. msg)))) + (func (inc-level db))))))) + +(defmacro with-db-transaction + "Evaluates body in the context of a transaction on the specified database connection. + The binding provides the database connection for the transaction and the name to which + that is bound for evaluation of the body. The binding may also specify the isolation + level for the transaction, via the :isolation option and/or set the transaction to + readonly via the :read-only? option. + (with-db-transaction [t-con db-spec {:isolation level :read-only? true}] + ... t-con ...) + See db-transaction* for more details." + [binding & body] + `(db-transaction* ~(second binding) + (^{:once true} fn* [~(first binding)] ~@body) + ~@(rest (rest binding)))) + +(defmacro with-db-connection + "Evaluates body in the context of an active connection to the database. + (with-db-connection [con-db db-spec opts] + ... con-db ...)" + [binding & body] + `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (add-connection db-spec# con#)] + ~@body)))) + +(defmacro with-db-metadata + "Evaluates body in the context of an active connection with metadata bound + to the specified name. See also metadata-result for dealing with the results + of operations that retrieve information from the metadata. + (with-db-metadata [md db-spec opts] + ... md ...)" + [binding & body] + `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (.getMetaData con#)] + ~@body)))) + +(defn metadata-result + "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, + else return it as-is. This makes working with metadata easier. + Also accepts an option map containing :identifiers, :keywordize?, :qualifier, + :as-arrays?, :row-fn,and :result-set-fn to control how the ResultSet is + transformed and returned. See query for more details." + ([rs-or-value] (metadata-result rs-or-value {})) + ([rs-or-value opts] + (let [{:keys [as-arrays? result-set-fn row-fn] :as opts} + (merge {:identifiers str/lower-case + :keywordize? true + :read-columns dft-read-columns + :row-fn identity} opts) + result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (if (instance? java.sql.ResultSet rs-or-value) + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rs-or-value opts)) + rs-or-value)))) + +(defmacro metadata-query + "Given a Java expression that extracts metadata (in the context of with-db-metadata), + and a map of options like metadata-result, manage the connection for a single + metadata-based query. Example usage: + + (with-db-metadata [meta db-spec] + (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) + {:row-fn ... :result-set-fn ...}))" + [meta-query & opt-args] + `(with-open [rs# ~meta-query] + (metadata-result rs# ~@opt-args))) + +(defn db-do-commands + "Executes SQL commands on the specified database connection. Wraps the commands + in a transaction if transaction? is true. transaction? can be ommitted and it + defaults to true. Accepts a single SQL command (string) or a vector of them. + Uses executeBatch. This may affect what SQL you can run via db-do-commands." + ([db sql-commands] + (db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands))) + ([db transaction? sql-commands] + (if (string? sql-commands) + (db-do-commands db transaction? [sql-commands]) + (if-let [con (db-find-connection db)] + (with-open [^Statement stmt (.createStatement con)] + (doseq [^String cmd sql-commands] + (.addBatch stmt cmd)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt))) + (with-open [con (get-connection db)] + (db-do-commands (add-connection db con) transaction? sql-commands)))))) + +(defn- db-do-execute-prepared-return-keys + "Executes a PreparedStatement, optionally in a transaction, and (attempts to) + return any generated keys." + [db ^PreparedStatement stmt param-group opts] + (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts) + exec-and-return-keys + (^{:once true} fn* [] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (result-set-seq rs opts))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] + ((:set-parameters opts dft-set-parameters) stmt param-group) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (exec-and-return-keys)) + (exec-and-return-keys)))) + +(defn- sql-stmt? + "Given an expression, return true if it is either a string (SQL) or a + PreparedStatement." + [expr] + (or (string? expr) (instance? PreparedStatement expr))) + +(defn db-do-prepared-return-keys + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. The param-group is a seq of values for all of + the parameters. transaction? can be ommitted and will default to true. + Return the generated keys for the (single) update/insert. + A PreparedStatement may be passed in, instead of a SQL string, in which + case :return-keys MUST BE SET on that PreparedStatement!" + ([db sql-params] + (db-do-prepared-return-keys db true sql-params {})) + ([db transaction? sql-params] + (if (map? sql-params) + (db-do-prepared-return-keys db true transaction? sql-params) + (db-do-prepared-return-keys db transaction? sql-params {}))) + ([db transaction? sql-params opts] + (let [opts (merge (when (map? db) db) opts)] + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) + (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] + (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) + (with-open [con (get-connection db opts)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) + +(defn- db-do-execute-prepared-statement + "Execute a PreparedStatement, optionally in a transaction." + [db ^PreparedStatement stmt param-groups opts] + (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts)] + (if (empty? param-groups) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (vector (.executeUpdate stmt))) + (vector (.executeUpdate stmt))) + (do + (doseq [param-group param-groups] + ((:set-parameters opts dft-set-parameters) stmt param-group) + (.addBatch stmt)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt)))))) + +(defn db-do-prepared + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. Each param-group is a seq of values for all of + the parameters. transaction? can be omitted and defaults to true. + The sql parameter can either be a SQL string or a PreparedStatement. + Return a seq of update counts (one count for each param-group)." + ([db sql-params] + (db-do-prepared db true sql-params {})) + ([db transaction? sql-params] + (if (map? sql-params) + (db-do-prepared db true transaction? sql-params) + (db-do-prepared db transaction? sql-params {}))) + ([db transaction? sql-params opts] + (let [opts (merge (when (map? db) db) opts)] + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + params (if (or (:multi? opts) (empty? params)) params [params])] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) + (with-open [con (get-connection db opts)] + (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) + +(defn db-query-with-resultset + "Executes a query, then evaluates func passing in the raw ResultSet as an + argument. The second argument is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + The opts map is passed to prepare-statement. + Uses executeQuery. This may affect what SQL you can run via query." + ([db sql-params func] (db-query-with-resultset db sql-params func {})) + ([db sql-params func opts] + (let [opts (merge (when (map? db) db) opts) + [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] + ((:set-parameters opts dft-set-parameters) stmt params) + (with-open [rset (.executeQuery stmt)] + (func rset)))] + (when-not (sql-stmt? sql) + (let [^Class sql-class (class sql) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-class) + (pr-str sql))] + (throw (IllegalArgumentException. msg)))) + (if (instance? PreparedStatement sql) + (let [^PreparedStatement stmt sql] + (run-query-with-params stmt)) + (if-let [con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (run-query-with-params stmt)) + (with-open [con (get-connection db opts)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (run-query-with-params stmt)))))))) + +;; top-level API for actual SQL operations + +(defn query + "Given a database connection and a vector containing SQL and optional parameters, + perform a simple database query. The options specify how to construct the result + set (and are also passed to prepare-statement as needed): + :as-arrays? - return the results as a set of arrays, default false. + :identifiers - applied to each column name in the result set, default lower-case + :keywordize? - defaults to true, can be false to opt-out of converting + identifiers to keywords + :qualifier - optionally provides the namespace qualifier for identifiers + :result-set-fn - applied to the entire result set, default doall / vec + if :as-arrays? true, :result-set-fn will default to vec + if :as-arrays? false, :result-set-fn will default to doall + :row-fn - applied to each row as the result set is constructed, default identity + The second argument is a vector containing a SQL string or PreparedStatement, followed + by any parameters it needs. + See also prepare-statement for additional options." + ([db sql-params] (query db sql-params {})) + ([db sql-params opts] + (let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts} + (merge {:explain-fn println :identifiers str/lower-case + :keywordize? true + :read-columns dft-read-columns :row-fn identity} + (when (map? db) db) + opts) + result-set-fn (or result-set-fn (if as-arrays? vec doall)) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (when (and explain? (string? (first sql-params-vector))) + (query db (into [(str (if (string? explain?) explain? "EXPLAIN") + " " + (first sql-params-vector))] + (rest sql-params-vector)) + (-> opts + (dissoc :explain? :result-set-fn :row-fn) + (assoc :result-set-fn explain-fn)))) + (db-query-with-resultset db sql-params-vector + (^{:once true} fn* [rset] + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rset opts))) + opts)))) + +;; performance notes -- goal is to lift as much logic as possible into a "once" +;; pass (so reducible-query preloads all the stuff that doesn't depend on the +;; query results, and then you can repeatedly reduce it, which runs the query +;; each time and runs the minimal result set reduction) +;; turn make-cols-unique into a transducer and optimize it +;; turn make-keys into a transducer pipeline and lift it +;; lift identifier-fn out as make-identifier-fn and refactor +;; lift init-reduce +;; refactor reducible-result-set to lift identifier-fn out +;; call new reducible-result-set version from reducible-query (after calling +;; make-identifier-fn etc) +;; create an optimized version of db-query-with-resultset without :as-arrays? +;; and with options handling lifted + +(defn reducible-result-set + "Given a java.sql.ResultSet return a reducible collection. + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + Note: :as-arrays? is not accepted here." + [^ResultSet rs {:keys [identifiers keywordize? qualifier read-columns] + :or {identifiers str/lower-case + keywordize? true + read-columns dft-read-columns}}] + (let [identifier-fn (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers) + make-keys (fn [idxs ^ResultSetMetaData rsmeta] + (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + (make-cols-unique) + (mapv identifier-fn))) + init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init')))] + (reify clojure.lang.IReduce + (reduce [this f] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (make-keys idxs rsmeta)] + (if (.next rs) + ;; reduce init is first row of ResultSet + (init-reduce keys rs rsmeta idxs f + (zipmap keys (read-columns rs rsmeta idxs))) + ;; no rows so call 0-arity f to get result value + ;; per reduce docstring contract + (f)))) + (reduce [this f init] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (make-keys idxs rsmeta)] + (init-reduce keys rs rsmeta idxs f init)))))) + +(defn reducible-query + "Given a database connection, a vector containing SQL and optional parameters, + return a reducible collection. When reduced, it will start the database query + and reduce the result set, and then close the connection: + (transduce (map :cost) + (reducible-query db sql-params)) + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + The following options from query etc are not accepted here: + :as-arrays? :explain :explain-fn :result-set-fn :row-fn + See also prepare-statement for additional options." + ([db sql-params] (reducible-query db sql-params {})) + ([db sql-params opts] + (let [{:keys [reducing-fn] :as opts} + (merge {:identifiers str/lower-case :keywordize? true + :read-columns dft-read-columns} + (when (map? db) db) + opts) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (reify clojure.lang.IReduce + (reduce [this f] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f (reducible-result-set rset opts))) + opts)) + (reduce [this f init] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f init (reducible-result-set rset opts))) + opts)))))) + +(defn- direction + "Given an entities function, a column name, and a direction, + return the matching SQL column / order. + Throw an exception for an invalid direction." + [entities c d] + (str (as-sql-name entities c) " " + (if-let [dir (#{"ASC" "DESC"} (str/upper-case (name d)))] + dir + (throw (IllegalArgumentException. (str "expected :asc or :desc, found: " d)))))) + +(defn- order-by-sql + "Given a sequence of column specs and an entities function, return + a SQL fragment for the ORDER BY clause. A column spec may be a name + (either a string or keyword) or a map from column name to direction + (:asc or :desc)." + [order-by entities] + (str/join ", " (mapcat (fn [col] + (if (map? col) + (reduce-kv (fn [v c d] + (conj v (direction entities c d))) + [] + col) + [(direction entities col :asc)])) order-by))) + +(defn find-by-keys + "Given a database connection, a table name, a map of column name/value + pairs, and an optional options map, return any matching rows. + An :order-by option may be supplied to sort the rows by a sequence of + columns, e.g,. {:order-by [:name {:age :desc]}" + ([db table columns] (find-by-keys db table columns {})) + ([db table columns opts] + (let [{:keys [entities order-by] :as opts} + (merge {:entities identity} (when (map? db) db) opts) + ks (keys columns) + vs (vals columns)] + (query db (into [(str "SELECT * FROM " (table-str table entities) + " WHERE " (str/join " AND " + (kv-sql ks vs entities " IS NULL")) + (when (seq order-by) + (str " ORDER BY " + (order-by-sql order-by entities))))] + (remove nil? vs)) + opts)))) + +(defn get-by-id + "Given a database connection, a table name, a primary key value, an + optional primary key column name, and an optional options map, return + a single matching row, or nil. + The primary key column name defaults to :id." + ([db table pk-value] (get-by-id db table pk-value :id {})) + ([db table pk-value pk-name-or-opts] + (if (map? pk-name-or-opts) + (get-by-id db table pk-value :id pk-name-or-opts) + (get-by-id db table pk-value pk-name-or-opts {}))) + ([db table pk-value pk-name opts] + (let [opts (merge (when (map? db) db) opts) + r-s-fn (or (:result-set-fn opts) identity)] + (find-by-keys db table {pk-name pk-value} + (assoc opts :result-set-fn (comp first r-s-fn)))))) + +(defn execute! + "Given a database connection and a vector containing SQL (or PreparedStatement) + followed by optional parameters, perform a general (non-select) SQL operation. + The :transaction? option specifies whether to run the operation in a + transaction or not (default true). + If the :multi? option is false (the default), the SQL statement should be + followed by the parameters for that statement. + If the :multi? option is true, the SQL statement should be followed by one or + more vectors of parameters, one for each application of the SQL statement. + If there are no parameters specified, executeUpdate will be used, otherwise + executeBatch will be used. This may affect what SQL you can run via execute!" + ([db sql-params] (execute! db sql-params {})) + ([db sql-params opts] + (let [{:keys [transaction?] :as opts} + (merge {:transaction? true :multi? false} (when (map? db) db) opts) + execute-helper (^{:once true} fn* [db] + (db-do-prepared db transaction? sql-params opts))] + (if-let [con (db-find-connection db)] + (execute-helper db) + (with-open [con (get-connection db opts)] + (execute-helper (add-connection db con))))))) + +(defn- delete-sql + "Given a table name, a where class and its parameters and an optional entities spec, + return a vector of the SQL for that delete operation followed by its parameters. The + entities spec (default 'as-is') specifies how to transform column names." + [table [where & params] entities] + (into [(str "DELETE FROM " (table-str table entities) + (when where " WHERE ") where)] + params)) + +(defn delete! + "Given a database connection, a table name and a where clause of columns to match, + perform a delete. The options may specify how to transform column names in the + map (default 'as-is') and whether to run the delete in a transaction (default true). + Example: + (delete! db :person [\"zip = ?\" 94546]) + is equivalent to: + (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" + ([db table where-clause] (delete! db table where-clause {})) + ([db table where-clause opts] + (let [{:keys [entities] :as opts} + (merge {:entities identity :transaction? true} (when (map? db) db) opts)] + (execute! db (delete-sql table where-clause entities) opts)))) + +(defn- multi-insert-helper + "Given a (connected) database connection and some SQL statements (for multiple + inserts), run a prepared statement on each and return any generated keys. + Note: we are eager so an unrealized lazy-seq cannot escape from the connection." + [db stmts opts] + (doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts))) + +(defn- insert-helper + "Given a (connected) database connection, a transaction flag and some SQL statements + (for one or more inserts), run a prepared statement or a sequence of them." + [db transaction? stmts opts] + (if transaction? + (with-db-transaction [t-db db] (multi-insert-helper t-db stmts opts)) + (multi-insert-helper db stmts opts))) + +(defn- col-str + "Transform a column spec to an entity name for SQL. The column spec may be a + string, a keyword or a map with a single pair - column name and alias." + [col entities] + (if (map? col) + (let [[k v] (first col)] + (str (as-sql-name entities k) " AS " (as-sql-name entities v))) + (as-sql-name entities col))) + +(defn- insert-multi-row-sql + "Given a table and a list of columns, followed by a list of column value sequences, + return a vector of the SQL needed for the insert followed by the list of column + value sequences. The entities function specifies how column names are transformed." + [table columns values entities] + (let [nc (count columns) + vcs (map count values)] + (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) + (throw (IllegalArgumentException. "insert! called with inconsistent number of columns / values")) + (into [(str "INSERT INTO " (table-str table entities) + (when (seq columns) + (str " ( " + (str/join ", " (map (fn [col] (col-str col entities)) columns)) + " )")) + " VALUES ( " + (str/join ", " (repeat (first vcs) "?")) + " )")] + values)))) + +(defn- insert-single-row-sql + "Given a table and a map representing a row, return a vector of the SQL needed for + the insert followed by the list of column values. The entities function specifies + how column names are transformed." + [table row entities] + (let [ks (keys row)] + (into [(str "INSERT INTO " (table-str table entities) " ( " + (str/join ", " (map (fn [col] (col-str col entities)) ks)) + " ) VALUES ( " + (str/join ", " (repeat (count ks) "?")) + " )")] + (vals row)))) + +(defn- insert-rows! + "Given a database connection, a table name, a sequence of rows, and an options + map, insert the rows into the database." + [db table rows opts] + (let [{:keys [entities transaction?] :as opts} + (merge {:entities identity :identifiers str/lower-case + :keywordize? true :transaction? true} + (when (map? db) db) + opts) + sql-params (map (fn [row] + (when-not (map? row) + (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) + (insert-single-row-sql table row entities)) rows)] + (if-let [con (db-find-connection db)] + (insert-helper db transaction? sql-params opts) + (with-open [con (get-connection db opts)] + (insert-helper (add-connection db con) transaction? sql-params opts))))) + +(defn- insert-cols! + "Given a database connection, a table name, a sequence of columns names, a + sequence of vectors of column values, one per row, and an options map, + insert the rows into the database." + [db table cols values opts] + (let [{:keys [entities transaction?] :as opts} + (merge {:entities identity :transaction? true} (when (map? db) db) opts) + sql-params (insert-multi-row-sql table cols values entities)] + (if-let [con (db-find-connection db)] + (db-do-prepared db transaction? sql-params (assoc opts :multi? true)) + (with-open [con (get-connection db opts)] + (db-do-prepared (add-connection db con) transaction? sql-params + (assoc opts :multi? true)))))) + +(defn insert! + "Given a database connection, a table name and either a map representing a rows, + or a list of column names followed by a list of column values also representing + a single row, perform an insert. + When inserting a row as a map, the result is the database-specific form of the + generated keys, if available (note: PostgreSQL returns the whole row). + When inserting a row as a list of column values, the result is the count of + rows affected (1), if available (from getUpdateCount after executeBatch). + The row map or column value vector may be followed by a map of options: + The :transaction? option specifies whether to run in a transaction or not. + The default is true (use a transaction). The :entities option specifies how + to convert the table name and column names to SQL entities." + ([db table row] (insert! db table row {})) + ([db table cols-or-row values-or-opts] + (if (map? values-or-opts) + (insert-rows! db table [cols-or-row] values-or-opts) + (insert-cols! db table cols-or-row [values-or-opts] {}))) + ([db table cols values opts] + (insert-cols! db table cols [values] opts))) + +(defn insert-multi! + "Given a database connection, a table name and either a sequence of maps (for + rows) or a sequence of column names, followed by a sequence of vectors (for + the values in each row), and possibly a map of options, insert that data into + the database. + + When inserting rows as a sequence of maps, the result is a sequence of the + generated keys, if available (note: PostgreSQL returns the whole rows). A + separate database operation is used for each row inserted. This may be slow + for if a large sequence of maps is provided. + + When inserting rows as a sequence of lists of column values, the result is + a sequence of the counts of rows affected (a sequence of 1's), if available. + Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch! + A single database operation is used to insert all the rows at once. This may + be much faster than inserting a sequence of rows (which performs an insert for + each map in the sequence). + + The :transaction? option specifies whether to run in a transaction or not. + The default is true (use a transaction). The :entities option specifies how + to convert the table name and column names to SQL entities." + ([db table rows] (insert-rows! db table rows {})) + ([db table cols-or-rows values-or-opts] + (if (map? values-or-opts) + (insert-rows! db table cols-or-rows values-or-opts) + (insert-cols! db table cols-or-rows values-or-opts {}))) + ([db table cols values opts] + (insert-cols! db table cols values opts))) + +(defn- update-sql + "Given a table name, a map of columns to set, a optional map of columns to + match, and an entities, return a vector of the SQL for that update followed + by its parameters. Example: + (update :person {:zip 94540} [\"zip = ?\" 94546] identity) + returns: + [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" + [table set-map [where & params] entities] + (let [ks (keys set-map) + vs (vals set-map)] + (cons (str "UPDATE " (table-str table entities) + " SET " (str/join + "," + (kv-sql ks vs entities " = NULL")) + (when where " WHERE ") + where) + (concat (remove nil? vs) params)))) + +(defn update! + "Given a database connection, a table name, a map of column values to set and a + where clause of columns to match, perform an update. The options may specify + how column names (in the set / match maps) should be transformed (default + 'as-is') and whether to run the update in a transaction (default true). + Example: + (update! db :person {:zip 94540} [\"zip = ?\" 94546]) + is equivalent to: + (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" + ([db table set-map where-clause] (update! db table set-map where-clause {})) + ([db table set-map where-clause opts] + (let [{:keys [entities] :as opts} + (merge {:entities identity :transaction? true} (when (map? db) db) opts)] + (execute! db (update-sql table set-map where-clause entities) opts)))) + +(defn create-table-ddl + "Given a table name and a vector of column specs, return the DDL string for + creating that table. Each column spec is, in turn, a vector of keywords or + strings that is converted to strings and concatenated with spaces to form + a single column description in DDL, e.g., + [:cost :int \"not null\"] + [:name \"varchar(32)\"] + The first element of a column spec is treated as a SQL entity (so if you + provide the :entities option, that will be used to transform it). The + remaining elements are left as-is when converting them to strings. + An options map may be provided that can contain: + :table-spec -- a string that is appended to the DDL -- and/or + :entities -- a function to specify how column names are transformed. + :conditional? -- either a boolean, indicating whether to add 'IF NOT EXISTS', + or a string, which is inserted literally before the table name, or a + function of two arguments (table name and the create statement), that can + manipulate the generated statement to better support other databases, e.g., + MS SQL Server which need to wrap create table in an existence query." + ([table specs] (create-table-ddl table specs {})) + ([table specs opts] + (let [table-spec (:table-spec opts) + conditional? (:conditional? opts) + entities (:entities opts identity) + table-name (as-sql-name entities table) + table-spec-str (or (and table-spec (str " " table-spec)) "") + spec-to-string (fn [spec] + (try + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))) + (catch Exception _ + (throw (IllegalArgumentException. + "column spec is not a sequence of keywords / strings")))))] + (cond->> (format "CREATE TABLE%s %s (%s)%s" + (cond (or (nil? conditional?) + (instance? Boolean conditional?)) + (if conditional? " IF NOT EXISTS" "") + (fn? conditional?) + "" + :else + (str " " conditional?)) + table-name + (str/join ", " (map spec-to-string specs)) + table-spec-str) + (fn? conditional?) (conditional? table-name))))) + +(defn drop-table-ddl + "Given a table name, return the DDL string for dropping that table. + An options map may be provided that can contain: + :entities -- a function to specify how column names are transformed. + :conditional? -- either a boolean, indicating whether to add 'IF EXISTS', + or a string, which is inserted literally before the table name, or a + function of two arguments (table name and the create statement), that can + manipulate the generated statement to better support other databases, e.g., + MS SQL Server which need to wrap create table in an existence query." + ([table] (drop-table-ddl table {})) + ([table {:keys [entities conditional?] :or {entities identity}}] + (let [table-name (as-sql-name entities table)] + (cond->> (format "DROP TABLE%s %s" + (cond (or (nil? conditional?) + (instance? Boolean conditional?)) + (if conditional? " IF EXISTS" "") + (fn? conditional?) + "" + :else + (str " " conditional?)) + table-name) + (fn? conditional?) (conditional? table-name))))) From 816b0cf323b1c672f2231c0f88e831a5a9fe57fe Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 13 Oct 2017 15:49:39 -0400 Subject: [PATCH 510/630] Lift return-keys validation out of try/catch If you asked to return keys provided other disallowed options, you did not get an exception, instead it attempted a basic PreparedStatement without returning keys... --- src/main/clojure/clojure/java/jdbc.clj | 64 +++++++++++++------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ce51d0d8..1886d04f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -570,39 +570,41 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} {:keys [return-keys result-type concurrency cursors fetch-size max-rows timeout]}] (let [^PreparedStatement - stmt (cond return-keys - (try - (when (or result-type concurrency cursors) - (throw (IllegalArgumentException. - (str ":concurrency, :cursors, and :result-type " - "may not be specified with :return-keys.")))) - (if (vector? return-keys) - (try - (.prepareStatement con sql (string-array return-keys)) - (catch Exception _ - ;; assume it is unsupported and try regular generated keys: - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) - (catch Exception _ - ;; assume it is unsupported and try basic PreparedStatement: - (.prepareStatement con sql))) - - (and result-type concurrency) - (if cursors - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency) - (get result-set-holdability cursors cursors)) - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency))) - - (or result-type concurrency cursors) + stmt (cond + return-keys + (do + (when (or result-type concurrency cursors) (throw (IllegalArgumentException. (str ":concurrency, :cursors, and :result-type " - "may not be specified independently."))) - :else - (.prepareStatement con sql))] + "may not be specified with :return-keys.")))) + (try + (if (vector? return-keys) + (try + (.prepareStatement con sql (string-array return-keys)) + (catch Exception _ + ;; assume it is unsupported and try regular generated keys: + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) + (catch Exception _ + ;; assume it is unsupported and try basic PreparedStatement: + (.prepareStatement con sql)))) + + (and result-type concurrency) + (if cursors + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency) + (get result-set-holdability cursors cursors)) + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency))) + + (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified independently."))) + :else + (.prepareStatement con sql))] (when fetch-size (.setFetchSize stmt fetch-size)) (when max-rows (.setMaxRows stmt max-rows)) (when timeout (.setQueryTimeout stmt timeout)) From 2c7d7fb16a5df81a44fee4112223dd8715bafcab Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 13 Oct 2017 16:12:32 -0400 Subject: [PATCH 511/630] Remove unused reducing-fn binding --- src/main/clojure/clojure/java/jdbc.clj | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1886d04f..fb82a9c5 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1118,11 +1118,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} See also prepare-statement for additional options." ([db sql-params] (reducible-query db sql-params {})) ([db sql-params opts] - (let [{:keys [reducing-fn] :as opts} - (merge {:identifiers str/lower-case :keywordize? true - :read-columns dft-read-columns} - (when (map? db) db) - opts) + (let [opts (merge {:identifiers str/lower-case :keywordize? true} + :read-columns dft-read-columns + (when (map? db) db) + opts) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (reify clojure.lang.IReduce (reduce [this f] From b0d6bb0d9fc8983848cdd9764eacf469c88a6608 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 18 Oct 2017 10:04:43 -0700 Subject: [PATCH 512/630] Fix typo in options hash map --- src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index fb82a9c5..7fd2c482 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1118,8 +1118,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} See also prepare-statement for additional options." ([db sql-params] (reducible-query db sql-params {})) ([db sql-params opts] - (let [opts (merge {:identifiers str/lower-case :keywordize? true} - :read-columns dft-read-columns + (let [opts (merge {:identifiers str/lower-case :keywordize? true + :read-columns dft-read-columns} (when (map? db) db) opts) sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] From 3a4321012eb04e82fafcf28c2303dd924389a39d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 13:31:49 -0700 Subject: [PATCH 513/630] Fix CRLF --- src/main/clojure/clojure/java/jdbc.clj | 2962 ++++++++++++------------ 1 file changed, 1481 insertions(+), 1481 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7fd2c482..f2d0517c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,1481 +1,1481 @@ -;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved. -;; The use and distribution terms for this software are covered by -;; the Eclipse Public License 1.0 -;; (http://opensource.org/licenses/eclipse-1.0.php) which can be -;; found in the file epl-v10.html at the root of this distribution. -;; By using this software in any fashion, you are agreeing to be -;; bound by the terms of this license. You must not remove this -;; notice, or any other, from this software. -;; -;; jdbc.clj -;; -;; A Clojure interface to sql databases via jdbc -;; -;; scgilardi (gmail) -;; Created 2 April 2008 -;; -;; seancorfield (gmail) -;; Migrated from clojure.contrib.sql 17 April 2011 - -(ns - ^{:author "Stephen C. Gilardi, Sean Corfield", - :doc "A Clojure interface to SQL databases via JDBC - -clojure.java.jdbc provides a simple abstraction for CRUD (create, read, -update, delete) operations on a SQL database, along with basic transaction -support. Basic DDL operations are also supported (create table, drop table, -access to table metadata). - -Maps are used to represent records, making it easy to store and retrieve -data. Results can be processed using any standard sequence operations. - -For most operations, Java's PreparedStatement is used so your SQL and -parameters can be represented as simple vectors where the first element -is the SQL string, with ? for each parameter, and the remaining elements -are the parameter values to be substituted. In general, operations return -the number of rows affected, except for a single record insert where any -generated keys are returned (as a map). - -For more documentation, see: - -http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} - clojure.java.jdbc - (:require [clojure.set :as set] - [clojure.string :as str] - [clojure.walk :as walk]) - (:import (java.net URI) - (java.sql BatchUpdateException DriverManager - PreparedStatement ResultSet ResultSetMetaData - SQLException Statement Types) - (java.util Hashtable Map Properties) - (javax.sql DataSource))) - -(defn as-sql-name - "Given a naming strategy function and a keyword or string, return - a string per that naming strategy. - A name of the form x.y is treated as multiple names, x, y, etc, - and each are turned into strings via the naming strategy and then - joined back together so x.y might become `x`.`y` if the naming - strategy quotes identifiers with `." - [f x] - (let [n (name x) - i (.indexOf n (int \.))] - (if (= -1 i) - (f n) - (str/join "." (map f (.split n "\\.")))))) - -(defn quoted - "Given a (vector) pair of delimiters (characters or strings), return a naming - strategy function that will quote SQL entities with them. - Given a single delimiter, treat it as a (vector) pair of that delimiter. - ((quoted [\\[ \\]]) \"foo\") will return \"[foo]\" -- for MS SQL Server - ((quoted \\`') \"foo\") will return \"`foo`\" -- for MySQL - Intended to be used with :entities to provide a quoting (naming) strategy that - is appropriate for your database." - [q] - (cond (vector? q) - (fn [x] - (str (first q) x (last q))) - (keyword? q) - (case q - :ansi (quoted \") - :mysql (quoted \`) - :oracle (quoted \") - :sqlserver (quoted [\[ \]])) - :else - (quoted [q q]))) - -(defn- table-str - "Transform a table spec to an entity name for SQL. The table spec may be a - string, a keyword or a map with a single pair - table name and alias." - [table entities] - (let [entities (or entities identity)] - (if (map? table) - (let [[k v] (first table)] - (str (as-sql-name entities k) " " (as-sql-name entities v))) - (as-sql-name entities table)))) - -(defn- kv-sql - "Given a sequence of column name keys and a matching sequence of column - values, and an entities mapping function, return a sequence of SQL fragments - that can be joined for part of an UPDATE SET or a SELECT WHERE clause. - Note that we pass the appropriate operator for NULL since it is different - in each case." - [ks vs entities null-op] - (map (fn [k v] - (str (as-sql-name entities k) - (if (nil? v) null-op " = ?"))) - ks vs)) - -(defn- ^Properties as-properties - "Convert any seq of pairs to a java.utils.Properties instance. - Uses as-sql-name to convert both keys and values into strings." - [m] - (let [p (Properties.)] - (doseq [[k v] m] - (.setProperty p (as-sql-name identity k) - (if (instance? clojure.lang.Named v) - (as-sql-name identity v) - (str v)))) - p)) - -;; convenience for working with different forms of connections -(defprotocol Connectable - (add-connection [db connection]) - (get-level [db])) - -(defn- inc-level - "Increment the nesting level for a transacted database connection. - If we are at the top level, also add in a rollback state." - [db] - (let [nested-db (update-in db [:level] (fnil inc 0))] - (if (= 1 (:level nested-db)) - (assoc nested-db :rollback (atom false)) - nested-db))) - -(extend-protocol Connectable - String - (add-connection [s connection] {:connection connection :level 0 :connection-string s}) - (get-level [_] 0) - - clojure.lang.Associative - (add-connection [m connection] (assoc m :connection connection)) - (get-level [m] (or (:level m) 0)) - - nil - (add-connection [_ connection] {:connection connection :level 0 :legacy true}) - (get-level [_] 0)) - -(def ^:private classnames - "Map of subprotocols to classnames. dbtype specifies one of these keys. - The subprotocols map below provides aliases for dbtype." - {"derby" "org.apache.derby.jdbc.EmbeddedDriver" - "h2" "org.h2.Driver" - "hsqldb" "org.hsqldb.jdbcDriver" - "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" - "mysql" "com.mysql.jdbc.Driver" - "oracle:oci" "oracle.jdbc.OracleDriver" - "oracle:thin" "oracle.jdbc.OracleDriver" - "postgresql" "org.postgresql.Driver" - "pgsql" "com.impossibl.postgres.jdbc.PGDriver" - "redshift" "com.amazon.redshift.jdbc.Driver" - "sqlite" "org.sqlite.JDBC" - "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) - -(def ^:private subprotocols - "Map of schemes to subprotocols. Used to provide aliases for dbtype." - {"hsql" "hsqldb" - "jtds" "jtds:sqlserver" - "mssql" "sqlserver" - "oracle" "oracle:thin" - "postgres" "postgresql"}) - -(def ^:private host-prefixes - "Map of subprotocols to non-standard host-prefixes. - Anything not listed is assumed to use //." - {"oracle:oci" "@" - "oracle:thin" "@"}) - -(defn- parse-properties-uri [^URI uri] - (let [host (.getHost uri) - port (if (pos? (.getPort uri)) (.getPort uri)) - path (.getPath uri) - scheme (.getScheme uri) - subprotocol (subprotocols scheme scheme) - host-prefix (host-prefixes subprotocol "//") - ^String query (.getQuery uri) - query-parts (and query - (for [^String kvs (.split query "&")] - ((juxt first second) (.split kvs "="))))] - (merge - {:subname (if host - (if port - (str host-prefix host ":" port path) - (str host-prefix host path)) - (.getSchemeSpecificPart uri)) - :subprotocol subprotocol} - (if-let [user-info (.getUserInfo uri)] - {:user (first (str/split user-info #":")) - :password (second (str/split user-info #":"))}) - (walk/keywordize-keys (into {} query-parts))))) - -(defn- strip-jdbc [^String spec] - (if (.startsWith spec "jdbc:") - (.substring spec 5) - spec)) - -;; feature testing macro, based on suggestion from Chas Emerick: -(defmacro when-available - [sym & body] - (try - (when (resolve sym) - (list* 'do body)) - (catch ClassNotFoundException _#))) - -(defn- modify-connection - "Given a database connection and a map of options, update the connection - as specified by the options." - ^java.sql.Connection - [^java.sql.Connection connection opts] - (when (contains? opts :auto-commit?) - (.setAutoCommit connection (:auto-commit? opts))) - (when (contains? opts :read-only?) - (.setReadOnly connection (:read-only? opts))) - connection) - -(defn get-connection - "Creates a connection to a database. db-spec is usually a map containing connection - parameters but can also be a URI or a String. The various possibilities are described - below: - - DriverManager (preferred): - :dbtype (required) a String, the type of the database (the jdbc subprotocol) - :dbname (required) a String, the name of the database - :classname (optional) a String, the jdbc driver class name - :host (optional) a String, the host name/IP of the database - (defaults to 127.0.0.1) - :port (optional) a Long, the port of the database - (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) - (others) (optional) passed to the driver as properties - (may include :user and :password) - - Raw: - :connection-uri (required) a String - Passed directly to DriverManager/getConnection - (both :user and :password may be specified as well, rather - than passing them as part of the connection string) - - Other formats accepted: - - Existing Connection: - :connection (required) an existing open connection that can be used - but cannot be closed (only the parent connection can be closed) - - DriverManager (alternative / legacy style): - :subprotocol (required) a String, the jdbc subprotocol - :subname (required) a String, the jdbc subname - :classname (optional) a String, the jdbc driver class name - (others) (optional) passed to the driver as properties - (may include :user and :password) - - Factory: - :factory (required) a function of one argument, a map of params - (others) (optional) passed to the factory function in a map - - DataSource: - :datasource (required) a javax.sql.DataSource - :username (optional) a String - deprecated, use :user instead - :user (optional) a String - preferred - :password (optional) a String, required if :user is supplied - - JNDI: - :name (required) a String or javax.naming.Name - :environment (optional) a java.util.Map - - java.net.URI: - Parsed JDBC connection string (see java.lang.String format next) - - java.lang.String: - subprotocol://user:password@host:post/subname - An optional prefix of jdbc: is allowed." - (^java.sql.Connection [db-spec] (get-connection db-spec {})) - (^java.sql.Connection - [{:keys [connection - factory - connection-uri - classname subprotocol subname - dbtype dbname host port - datasource username password user - name environment] - :as db-spec} - opts] - (cond - (string? db-spec) - (get-connection (URI. (strip-jdbc db-spec)) opts) - - (instance? URI db-spec) - (get-connection (parse-properties-uri db-spec) opts) - - connection - connection ;; do not apply opts here - - (or (and datasource username password) ; legacy - (and datasource user password)) ; preferred - (-> (.getConnection ^DataSource datasource - ^String (or username user) - ^String password) - (modify-connection opts)) - - datasource - (-> (.getConnection ^DataSource datasource) - (modify-connection opts)) - - factory - (-> (factory (dissoc db-spec :factory)) - (modify-connection opts)) - - connection-uri - (-> (if (and user password) - (DriverManager/getConnection connection-uri user password) - (DriverManager/getConnection connection-uri)) - (modify-connection opts)) - - (and dbtype dbname) - (let [;; allow aliases for dbtype - subprotocol (subprotocols dbtype dbtype) - host (or host "127.0.0.1") - port (or port (condp = subprotocol - "jtds:sqlserver" 1433 - "mysql" 3306 - "oracle:oci" 1521 - "oracle:thin" 1521 - "postgresql" 5432 - "sqlserver" 1433 - nil)) - db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") - url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) - (str "jdbc:" subprotocol ":" dbname) - (str "jdbc:" subprotocol ":" - (host-prefixes subprotocol "//") - host - (when port (str ":" port)) - db-sep dbname)) - etc (dissoc db-spec :dbtype :dbname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) - (-> (DriverManager/getConnection url (as-properties etc)) - (modify-connection opts))) - - (and subprotocol subname) - (let [;; allow aliases for subprotocols - subprotocol (subprotocols subprotocol subprotocol) - url (format "jdbc:%s:%s" subprotocol subname) - etc (dissoc db-spec :classname :subprotocol :subname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) - (-> (DriverManager/getConnection url (as-properties etc)) - (modify-connection opts))) - - name - (or (when-available javax.naming.InitialContext - (let [env (and environment (Hashtable. ^Map environment)) - context (javax.naming.InitialContext. env) - ^DataSource datasource (.lookup context ^String name)] - (-> (.getConnection datasource) - (modify-connection opts)))) - (throw (ex-info (str "javax.naming.InitialContext is not available for: " - name) - db-spec))) - - :else - (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] - (throw (IllegalArgumentException. msg)))))) - -(defn- make-name-unique - "Given a collection of column names and a new column name, - return the new column name made unique, if necessary, by - appending _N where N is some unique integer suffix." - [cols col-name n] - (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] - (if (apply distinct? suffixed-name cols) - suffixed-name - (recur cols col-name (inc n))))) - -(defn- make-cols-unique - "Given a collection of column names, rename duplicates so - that the result is a collection of unique column names." - [cols] - (if (or (empty? cols) (apply distinct? cols)) - cols - (reduce (fn [unique-cols col-name] - (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) - -(defprotocol ISQLValue - "Protocol for creating SQL values from Clojure values. Default - implementations (for Object and nil) just return the argument, - but it can be extended to provide custom behavior to support - exotic types supported by different databases." - (sql-value [val] "Convert a Clojure value into a SQL value.")) - -(extend-protocol ISQLValue - Object - (sql-value [v] v) - - nil - (sql-value [_] nil)) - -(defprotocol ISQLParameter - "Protocol for setting SQL parameters in statement objects, which - can convert from Clojure values. The default implementation just - delegates the conversion to ISQLValue's sql-value conversion and - uses .setObject on the parameter. It can be extended to use other - methods of PreparedStatement to convert and set parameter values." - (set-parameter [val stmt ix] - "Convert a Clojure value into a SQL value and store it as the ix'th - parameter in the given SQL statement object.")) - -(extend-protocol ISQLParameter - Object - (set-parameter [v ^PreparedStatement s ^long i] - (.setObject s i (sql-value v))) - - nil - (set-parameter [_ ^PreparedStatement s ^long i] - (.setObject s i (sql-value nil)))) - -(defn- dft-set-parameters - "Default implementation of parameter setting for the given statement." - [stmt params] - (dorun (map-indexed (fn [ix value] - (set-parameter value stmt (inc ix))) - params))) - -(defprotocol IResultSetReadColumn - "Protocol for reading objects from the java.sql.ResultSet. Default - implementations (for Object and nil) return the argument, and the - Boolean implementation ensures a canonicalized true/false value, - but it can be extended to provide custom behavior for special types." - (result-set-read-column [val rsmeta idx] - "Function for transforming values after reading them from the database")) - -(extend-protocol IResultSetReadColumn - Object - (result-set-read-column [x _2 _3] x) - - Boolean - (result-set-read-column [x _2 _3] (if (= true x) true false)) - - nil - (result-set-read-column [_1 _2 _3] nil)) - -(defn- dft-read-columns - "Default implementation of reading row values from result set, given the - result set metadata and the indices." - [^ResultSet rs rsmeta idxs] - (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) - -(defn result-set-seq - "Creates and returns a lazy sequence of maps corresponding to the rows in the - java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it - respects the specified naming strategy. Duplicate column names are made unique - by appending _N before applying the naming strategy (where N is a unique integer), - unless the :as-arrays? option is :cols-as-is, in which case the column names - are untouched (the result set maintains column name/value order). - The :identifiers option specifies how SQL column names are converted to Clojure - keywords. The default is to convert them to lower case. - The :keywordize? option can be specified as false to opt-out of the conversion - to keywords. - The :qualifier option specifies the namespace qualifier for those identifiers - (and this may not be specified when :keywordize? is false)." - ([rs] (result-set-seq rs {})) - ([^ResultSet rs {:keys [as-arrays? identifiers keywordize? - qualifier read-columns] - :or {identifiers str/lower-case - keywordize? true - read-columns dft-read-columns}}] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) - identifier-fn (cond (and qualifier (not keywordize?)) - (throw (IllegalArgumentException. - (str ":qualifier is not allowed unless " - ":keywordize? is true"))) - (and qualifier keywordize?) - (comp (partial keyword qualifier) identifiers) - keywordize? - (comp keyword identifiers) - :else - identifiers) - keys (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - col-name-fn - (mapv identifier-fn)) - row-values (fn [] (read-columns rs rsmeta idxs)) - ;; This used to use create-struct (on keys) and then struct to populate each row. - ;; That had the side effect of preserving the order of columns in each row. As - ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't - ;; want to switch to records so we're using regular maps instead. We no longer - ;; guarantee column order in rows but using into {} should preserve order for up - ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying - ;; on the order-preserving behavior of structmaps, we can reconsider... - records (fn thisfn [] - (when (.next rs) - (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) - rows (fn thisfn [] - (when (.next rs) - (cons (vec (row-values)) (lazy-seq (thisfn)))))] - (if as-arrays? - (cons (vec keys) (rows)) - (records))))) - -(defn- execute-batch - "Executes a batch of SQL commands and returns a sequence of update counts. - (-2) indicates a single operation operating on an unknown number of rows. - Specifically, Oracle returns that and we must call getUpdateCount() to get - the actual number of rows affected. In general, operations return an array - of update counts, so this may not be a general solution for Oracle..." - [^Statement stmt] - (let [result (.executeBatch stmt)] - (if (and (= 1 (count result)) (= -2 (first result))) - (list (.getUpdateCount stmt)) - (seq result)))) - -(def ^{:private true - :doc "Map friendly :concurrency values to ResultSet constants."} - result-set-concurrency - {:read-only ResultSet/CONCUR_READ_ONLY - :updatable ResultSet/CONCUR_UPDATABLE}) - -(def ^{:private true - :doc "Map friendly :cursors values to ResultSet constants."} - result-set-holdability - {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT - :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) - -(def ^{:private true - :doc "Map friendly :type values to ResultSet constants."} - result-set-type - {:forward-only ResultSet/TYPE_FORWARD_ONLY - :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE - :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) - -(defn ^{:tag (class (into-array String []))} string-array - [return-keys] - (into-array String return-keys)) - -(defn prepare-statement - "Create a prepared statement from a connection, a SQL string and a map - of options: - :return-keys truthy | nil - default nil - for some drivers, this may be a vector of column names to identify - the generated keys to return, otherwise it should just be true - :result-type :forward-only | :scroll-insensitive | :scroll-sensitive - :concurrency :read-only | :updatable - :cursors :hold | :close - :fetch-size n - :max-rows n - :timeout n - Note that :result-type and :concurrency must be specified together as the - underlying Java API expects both (or neither)." - ([con sql] (prepare-statement con sql {})) - ([^java.sql.Connection con ^String sql - {:keys [return-keys result-type concurrency cursors - fetch-size max-rows timeout]}] - (let [^PreparedStatement - stmt (cond - return-keys - (do - (when (or result-type concurrency cursors) - (throw (IllegalArgumentException. - (str ":concurrency, :cursors, and :result-type " - "may not be specified with :return-keys.")))) - (try - (if (vector? return-keys) - (try - (.prepareStatement con sql (string-array return-keys)) - (catch Exception _ - ;; assume it is unsupported and try regular generated keys: - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) - (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) - (catch Exception _ - ;; assume it is unsupported and try basic PreparedStatement: - (.prepareStatement con sql)))) - - (and result-type concurrency) - (if cursors - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency) - (get result-set-holdability cursors cursors)) - (.prepareStatement con sql - (get result-set-type result-type result-type) - (get result-set-concurrency concurrency concurrency))) - - (or result-type concurrency cursors) - (throw (IllegalArgumentException. - (str ":concurrency, :cursors, and :result-type " - "may not be specified independently."))) - :else - (.prepareStatement con sql))] - (when fetch-size (.setFetchSize stmt fetch-size)) - (when max-rows (.setMaxRows stmt max-rows)) - (when timeout (.setQueryTimeout stmt timeout)) - stmt))) - -(defn print-sql-exception - "Prints the contents of an SQLException to *out*" - [^SQLException exception] - (let [^Class exception-class (class exception)] - (println - (format (str "%s:" \newline - " Message: %s" \newline - " SQLState: %s" \newline - " Error Code: %d") - (.getSimpleName exception-class) - (.getMessage exception) - (.getSQLState exception) - (.getErrorCode exception))))) - -(defn print-sql-exception-chain - "Prints a chain of SQLExceptions to *out*" - [^SQLException exception] - (loop [e exception] - (when e - (print-sql-exception e) - (recur (.getNextException e))))) - -(def ^{:private true} special-counts - {Statement/EXECUTE_FAILED "EXECUTE_FAILED" - Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) - -(defn print-update-counts - "Prints the update counts from a BatchUpdateException to *out*" - [^BatchUpdateException exception] - (println "Update counts:") - (dorun - (map-indexed - (fn [index count] - (println (format " Statement %d: %s" - index - (get special-counts count count)))) - (.getUpdateCounts exception)))) - -;; java.jdbc pieces rewritten to not use dynamic bindings - -(defn db-find-connection - "Returns the current database connection (or nil if there is none)" - ^java.sql.Connection [db] - (and (map? db) - (:connection db))) - -(defn db-connection - "Returns the current database connection (or throws if there is none)" - ^java.sql.Connection [db] - (or (db-find-connection db) - (throw (Exception. "no current database connection")))) - -(defn db-set-rollback-only! - "Marks the outermost transaction such that it will rollback rather than - commit when complete" - [db] - (reset! (:rollback db) true)) - -(defn db-unset-rollback-only! - "Marks the outermost transaction such that it will not rollback when complete" - [db] - (reset! (:rollback db) false)) - -(defn db-is-rollback-only - "Returns true if the outermost transaction will rollback rather than - commit when complete" - [db] - (deref (:rollback db))) - -(def ^:private - isolation-levels - "Transaction isolation levels." - {:none java.sql.Connection/TRANSACTION_NONE - :read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED - :read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED - :repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ - :serializable java.sql.Connection/TRANSACTION_SERIALIZABLE}) - -(def ^:private isolation-kws - "Map transaction isolation constants to our keywords." - (set/map-invert isolation-levels)) - -(defn get-isolation-level - "Given a db-spec (with an optional connection), return the current - transaction isolation level, if known. Return nil if there is no - active connection in the db-spec. Return :unknown if we do not - recognize the isolation level." - [db] - (when-let [con (db-find-connection db)] - (isolation-kws (.getTransactionIsolation con) :unknown))) - -(defn db-transaction* - "Evaluates func as a transaction on the open database connection. Any - nested transactions are absorbed into the outermost transaction. By - default, all database updates are committed together as a group after - evaluating the outermost body, or rolled back on any uncaught - exception. If rollback is set within scope of the outermost transaction, - the entire transaction will be rolled back rather than committed when - complete. - The isolation option may be :none, :read-committed, :read-uncommitted, - :repeatable-read, or :serializable. Note that not all databases support - all of those isolation levels, and may either throw an exception or - substitute another isolation level. - The read-only? option puts the transaction in readonly mode (if supported)." - ([db func] (db-transaction* db func {})) - ([db func opts] - (let [{:keys [isolation read-only?] :as opts} - (merge (when (map? db) db) opts)] - (if (zero? (get-level db)) - (if-let [con (db-find-connection db)] - (let [nested-db (inc-level db) - auto-commit (.getAutoCommit con) - old-isolation (.getTransactionIsolation con) - old-readonly (.isReadOnly con)] - (io! - (when isolation - (.setTransactionIsolation con (isolation isolation-levels))) - (when read-only? - (.setReadOnly con true)) - (.setAutoCommit con false) - (try - (let [result (func nested-db)] - (if (db-is-rollback-only nested-db) - (.rollback con) - (.commit con)) - result) - (catch Throwable t - (try - (.rollback con) - (catch Throwable rb - ;; combine both exceptions - (throw (ex-info (str "Rollback failed handling \"" - (.getMessage t) - "\"") - {:rollback rb - :handling t})))) - (throw t)) - (finally - (db-unset-rollback-only! nested-db) - ;; the following can throw SQLExceptions but we do not - ;; want those to replace any exception currently being - ;; handled -- and if the connection got closed, we just - ;; want to ignore exceptions here anyway - (try - (.setAutoCommit con auto-commit) - (catch Exception _)) - (when isolation - (try - (.setTransactionIsolation con old-isolation) - (catch Exception _))) - (when read-only? - (try - (.setReadOnly con old-readonly) - (catch Exception _))))))) - (with-open [con (get-connection db opts)] - (db-transaction* (add-connection db con) func opts))) - (do - (when (and isolation - (let [con (db-find-connection db)] - (not= (isolation isolation-levels) - (.getTransactionIsolation con)))) - (let [msg "Nested transactions may not have different isolation levels"] - (throw (IllegalStateException. msg)))) - (func (inc-level db))))))) - -(defmacro with-db-transaction - "Evaluates body in the context of a transaction on the specified database connection. - The binding provides the database connection for the transaction and the name to which - that is bound for evaluation of the body. The binding may also specify the isolation - level for the transaction, via the :isolation option and/or set the transaction to - readonly via the :read-only? option. - (with-db-transaction [t-con db-spec {:isolation level :read-only? true}] - ... t-con ...) - See db-transaction* for more details." - [binding & body] - `(db-transaction* ~(second binding) - (^{:once true} fn* [~(first binding)] ~@body) - ~@(rest (rest binding)))) - -(defmacro with-db-connection - "Evaluates body in the context of an active connection to the database. - (with-db-connection [con-db db-spec opts] - ... con-db ...)" - [binding & body] - `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] - (with-open [con# (get-connection db-spec# opts#)] - (let [~(first binding) (add-connection db-spec# con#)] - ~@body)))) - -(defmacro with-db-metadata - "Evaluates body in the context of an active connection with metadata bound - to the specified name. See also metadata-result for dealing with the results - of operations that retrieve information from the metadata. - (with-db-metadata [md db-spec opts] - ... md ...)" - [binding & body] - `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] - (with-open [con# (get-connection db-spec# opts#)] - (let [~(first binding) (.getMetaData con#)] - ~@body)))) - -(defn metadata-result - "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, - else return it as-is. This makes working with metadata easier. - Also accepts an option map containing :identifiers, :keywordize?, :qualifier, - :as-arrays?, :row-fn,and :result-set-fn to control how the ResultSet is - transformed and returned. See query for more details." - ([rs-or-value] (metadata-result rs-or-value {})) - ([rs-or-value opts] - (let [{:keys [as-arrays? result-set-fn row-fn] :as opts} - (merge {:identifiers str/lower-case - :keywordize? true - :read-columns dft-read-columns - :row-fn identity} opts) - result-set-fn (or result-set-fn (if as-arrays? vec doall))] - (if (instance? java.sql.ResultSet rs-or-value) - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rs-or-value opts)) - rs-or-value)))) - -(defmacro metadata-query - "Given a Java expression that extracts metadata (in the context of with-db-metadata), - and a map of options like metadata-result, manage the connection for a single - metadata-based query. Example usage: - - (with-db-metadata [meta db-spec] - (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) - {:row-fn ... :result-set-fn ...}))" - [meta-query & opt-args] - `(with-open [rs# ~meta-query] - (metadata-result rs# ~@opt-args))) - -(defn db-do-commands - "Executes SQL commands on the specified database connection. Wraps the commands - in a transaction if transaction? is true. transaction? can be ommitted and it - defaults to true. Accepts a single SQL command (string) or a vector of them. - Uses executeBatch. This may affect what SQL you can run via db-do-commands." - ([db sql-commands] - (db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands))) - ([db transaction? sql-commands] - (if (string? sql-commands) - (db-do-commands db transaction? [sql-commands]) - (if-let [con (db-find-connection db)] - (with-open [^Statement stmt (.createStatement con)] - (doseq [^String cmd sql-commands] - (.addBatch stmt cmd)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt))) - (with-open [con (get-connection db)] - (db-do-commands (add-connection db con) transaction? sql-commands)))))) - -(defn- db-do-execute-prepared-return-keys - "Executes a PreparedStatement, optionally in a transaction, and (attempts to) - return any generated keys." - [db ^PreparedStatement stmt param-group opts] - (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts) - exec-and-return-keys - (^{:once true} fn* [] - (let [counts (.executeUpdate stmt)] - (try - (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs opts))] - ;; sqlite (and maybe others?) requires - ;; record set to be closed - (.close rs) - result) - (catch Exception _ - ;; assume generated keys is unsupported and return counts instead: - counts))))] - ((:set-parameters opts dft-set-parameters) stmt param-group) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (exec-and-return-keys)) - (exec-and-return-keys)))) - -(defn- sql-stmt? - "Given an expression, return true if it is either a string (SQL) or a - PreparedStatement." - [expr] - (or (string? expr) (instance? PreparedStatement expr))) - -(defn db-do-prepared-return-keys - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. The param-group is a seq of values for all of - the parameters. transaction? can be ommitted and will default to true. - Return the generated keys for the (single) update/insert. - A PreparedStatement may be passed in, instead of a SQL string, in which - case :return-keys MUST BE SET on that PreparedStatement!" - ([db sql-params] - (db-do-prepared-return-keys db true sql-params {})) - ([db transaction? sql-params] - (if (map? sql-params) - (db-do-prepared-return-keys db true transaction? sql-params) - (db-do-prepared-return-keys db transaction? sql-params {}))) - ([db transaction? sql-params opts] - (let [opts (merge (when (map? db) db) opts)] - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] - (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db opts)] - (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) - -(defn- db-do-execute-prepared-statement - "Execute a PreparedStatement, optionally in a transaction." - [db ^PreparedStatement stmt param-groups opts] - (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts)] - (if (empty? param-groups) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (vector (.executeUpdate stmt))) - (vector (.executeUpdate stmt))) - (do - (doseq [param-group param-groups] - ((:set-parameters opts dft-set-parameters) stmt param-group) - (.addBatch stmt)) - (if transaction? - (with-db-transaction [t-db (add-connection db (.getConnection stmt))] - (execute-batch stmt)) - (execute-batch stmt)))))) - -(defn db-do-prepared - "Executes an (optionally parameterized) SQL prepared statement on the - open database connection. Each param-group is a seq of values for all of - the parameters. transaction? can be omitted and defaults to true. - The sql parameter can either be a SQL string or a PreparedStatement. - Return a seq of update counts (one count for each param-group)." - ([db sql-params] - (db-do-prepared db true sql-params {})) - ([db transaction? sql-params] - (if (map? sql-params) - (db-do-prepared db true transaction? sql-params) - (db-do-prepared db transaction? sql-params {}))) - ([db transaction? sql-params opts] - (let [opts (merge (when (map? db) db) opts)] - (if-let [con (db-find-connection db)] - (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - params (if (or (:multi? opts) (empty? params)) params [params])] - (if (instance? PreparedStatement sql) - (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) - (with-open [con (get-connection db opts)] - (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) - -(defn db-query-with-resultset - "Executes a query, then evaluates func passing in the raw ResultSet as an - argument. The second argument is a vector containing either: - [sql & params] - a SQL query, followed by any parameters it needs - [stmt & params] - a PreparedStatement, followed by any parameters it needs - (the PreparedStatement already contains the SQL query) - The opts map is passed to prepare-statement. - Uses executeQuery. This may affect what SQL you can run via query." - ([db sql-params func] (db-query-with-resultset db sql-params func {})) - ([db sql-params func opts] - (let [opts (merge (when (map? db) db) opts) - [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] - ((:set-parameters opts dft-set-parameters) stmt params) - (with-open [rset (.executeQuery stmt)] - (func rset)))] - (when-not (sql-stmt? sql) - (let [^Class sql-class (class sql) - ^String msg (format "\"%s\" expected %s %s, found %s %s" - "sql-params" - "vector" - "[sql param*]" - (.getName sql-class) - (pr-str sql))] - (throw (IllegalArgumentException. msg)))) - (if (instance? PreparedStatement sql) - (let [^PreparedStatement stmt sql] - (run-query-with-params stmt)) - (if-let [con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (run-query-with-params stmt)) - (with-open [con (get-connection db opts)] - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (run-query-with-params stmt)))))))) - -;; top-level API for actual SQL operations - -(defn query - "Given a database connection and a vector containing SQL and optional parameters, - perform a simple database query. The options specify how to construct the result - set (and are also passed to prepare-statement as needed): - :as-arrays? - return the results as a set of arrays, default false. - :identifiers - applied to each column name in the result set, default lower-case - :keywordize? - defaults to true, can be false to opt-out of converting - identifiers to keywords - :qualifier - optionally provides the namespace qualifier for identifiers - :result-set-fn - applied to the entire result set, default doall / vec - if :as-arrays? true, :result-set-fn will default to vec - if :as-arrays? false, :result-set-fn will default to doall - :row-fn - applied to each row as the result set is constructed, default identity - The second argument is a vector containing a SQL string or PreparedStatement, followed - by any parameters it needs. - See also prepare-statement for additional options." - ([db sql-params] (query db sql-params {})) - ([db sql-params opts] - (let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts} - (merge {:explain-fn println :identifiers str/lower-case - :keywordize? true - :read-columns dft-read-columns :row-fn identity} - (when (map? db) db) - opts) - result-set-fn (or result-set-fn (if as-arrays? vec doall)) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (when (and explain? (string? (first sql-params-vector))) - (query db (into [(str (if (string? explain?) explain? "EXPLAIN") - " " - (first sql-params-vector))] - (rest sql-params-vector)) - (-> opts - (dissoc :explain? :result-set-fn :row-fn) - (assoc :result-set-fn explain-fn)))) - (db-query-with-resultset db sql-params-vector - (^{:once true} fn* [rset] - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rset opts))) - opts)))) - -;; performance notes -- goal is to lift as much logic as possible into a "once" -;; pass (so reducible-query preloads all the stuff that doesn't depend on the -;; query results, and then you can repeatedly reduce it, which runs the query -;; each time and runs the minimal result set reduction) -;; turn make-cols-unique into a transducer and optimize it -;; turn make-keys into a transducer pipeline and lift it -;; lift identifier-fn out as make-identifier-fn and refactor -;; lift init-reduce -;; refactor reducible-result-set to lift identifier-fn out -;; call new reducible-result-set version from reducible-query (after calling -;; make-identifier-fn etc) -;; create an optimized version of db-query-with-resultset without :as-arrays? -;; and with options handling lifted - -(defn reducible-result-set - "Given a java.sql.ResultSet return a reducible collection. - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce - Note: :as-arrays? is not accepted here." - [^ResultSet rs {:keys [identifiers keywordize? qualifier read-columns] - :or {identifiers str/lower-case - keywordize? true - read-columns dft-read-columns}}] - (let [identifier-fn (cond (and qualifier (not keywordize?)) - (throw (IllegalArgumentException. - (str ":qualifier is not allowed unless " - ":keywordize? is true"))) - (and qualifier keywordize?) - (comp (partial keyword qualifier) identifiers) - keywordize? - (comp keyword identifiers) - :else - identifiers) - make-keys (fn [idxs ^ResultSetMetaData rsmeta] - (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - (make-cols-unique) - (mapv identifier-fn))) - init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init] - (loop [init' init] - (if (.next rs) - (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] - (if (reduced? result) - @result - (recur result))) - init')))] - (reify clojure.lang.IReduce - (reduce [this f] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (make-keys idxs rsmeta)] - (if (.next rs) - ;; reduce init is first row of ResultSet - (init-reduce keys rs rsmeta idxs f - (zipmap keys (read-columns rs rsmeta idxs))) - ;; no rows so call 0-arity f to get result value - ;; per reduce docstring contract - (f)))) - (reduce [this f init] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (make-keys idxs rsmeta)] - (init-reduce keys rs rsmeta idxs f init)))))) - -(defn reducible-query - "Given a database connection, a vector containing SQL and optional parameters, - return a reducible collection. When reduced, it will start the database query - and reduce the result set, and then close the connection: - (transduce (map :cost) + (reducible-query db sql-params)) - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce - The following options from query etc are not accepted here: - :as-arrays? :explain :explain-fn :result-set-fn :row-fn - See also prepare-statement for additional options." - ([db sql-params] (reducible-query db sql-params {})) - ([db sql-params opts] - (let [opts (merge {:identifiers str/lower-case :keywordize? true - :read-columns dft-read-columns} - (when (map? db) db) - opts) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (reify clojure.lang.IReduce - (reduce [this f] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f (reducible-result-set rset opts))) - opts)) - (reduce [this f init] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts))) - opts)))))) - -(defn- direction - "Given an entities function, a column name, and a direction, - return the matching SQL column / order. - Throw an exception for an invalid direction." - [entities c d] - (str (as-sql-name entities c) " " - (if-let [dir (#{"ASC" "DESC"} (str/upper-case (name d)))] - dir - (throw (IllegalArgumentException. (str "expected :asc or :desc, found: " d)))))) - -(defn- order-by-sql - "Given a sequence of column specs and an entities function, return - a SQL fragment for the ORDER BY clause. A column spec may be a name - (either a string or keyword) or a map from column name to direction - (:asc or :desc)." - [order-by entities] - (str/join ", " (mapcat (fn [col] - (if (map? col) - (reduce-kv (fn [v c d] - (conj v (direction entities c d))) - [] - col) - [(direction entities col :asc)])) order-by))) - -(defn find-by-keys - "Given a database connection, a table name, a map of column name/value - pairs, and an optional options map, return any matching rows. - An :order-by option may be supplied to sort the rows by a sequence of - columns, e.g,. {:order-by [:name {:age :desc]}" - ([db table columns] (find-by-keys db table columns {})) - ([db table columns opts] - (let [{:keys [entities order-by] :as opts} - (merge {:entities identity} (when (map? db) db) opts) - ks (keys columns) - vs (vals columns)] - (query db (into [(str "SELECT * FROM " (table-str table entities) - " WHERE " (str/join " AND " - (kv-sql ks vs entities " IS NULL")) - (when (seq order-by) - (str " ORDER BY " - (order-by-sql order-by entities))))] - (remove nil? vs)) - opts)))) - -(defn get-by-id - "Given a database connection, a table name, a primary key value, an - optional primary key column name, and an optional options map, return - a single matching row, or nil. - The primary key column name defaults to :id." - ([db table pk-value] (get-by-id db table pk-value :id {})) - ([db table pk-value pk-name-or-opts] - (if (map? pk-name-or-opts) - (get-by-id db table pk-value :id pk-name-or-opts) - (get-by-id db table pk-value pk-name-or-opts {}))) - ([db table pk-value pk-name opts] - (let [opts (merge (when (map? db) db) opts) - r-s-fn (or (:result-set-fn opts) identity)] - (find-by-keys db table {pk-name pk-value} - (assoc opts :result-set-fn (comp first r-s-fn)))))) - -(defn execute! - "Given a database connection and a vector containing SQL (or PreparedStatement) - followed by optional parameters, perform a general (non-select) SQL operation. - The :transaction? option specifies whether to run the operation in a - transaction or not (default true). - If the :multi? option is false (the default), the SQL statement should be - followed by the parameters for that statement. - If the :multi? option is true, the SQL statement should be followed by one or - more vectors of parameters, one for each application of the SQL statement. - If there are no parameters specified, executeUpdate will be used, otherwise - executeBatch will be used. This may affect what SQL you can run via execute!" - ([db sql-params] (execute! db sql-params {})) - ([db sql-params opts] - (let [{:keys [transaction?] :as opts} - (merge {:transaction? true :multi? false} (when (map? db) db) opts) - execute-helper (^{:once true} fn* [db] - (db-do-prepared db transaction? sql-params opts))] - (if-let [con (db-find-connection db)] - (execute-helper db) - (with-open [con (get-connection db opts)] - (execute-helper (add-connection db con))))))) - -(defn- delete-sql - "Given a table name, a where class and its parameters and an optional entities spec, - return a vector of the SQL for that delete operation followed by its parameters. The - entities spec (default 'as-is') specifies how to transform column names." - [table [where & params] entities] - (into [(str "DELETE FROM " (table-str table entities) - (when where " WHERE ") where)] - params)) - -(defn delete! - "Given a database connection, a table name and a where clause of columns to match, - perform a delete. The options may specify how to transform column names in the - map (default 'as-is') and whether to run the delete in a transaction (default true). - Example: - (delete! db :person [\"zip = ?\" 94546]) - is equivalent to: - (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" - ([db table where-clause] (delete! db table where-clause {})) - ([db table where-clause opts] - (let [{:keys [entities] :as opts} - (merge {:entities identity :transaction? true} (when (map? db) db) opts)] - (execute! db (delete-sql table where-clause entities) opts)))) - -(defn- multi-insert-helper - "Given a (connected) database connection and some SQL statements (for multiple - inserts), run a prepared statement on each and return any generated keys. - Note: we are eager so an unrealized lazy-seq cannot escape from the connection." - [db stmts opts] - (doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts))) - -(defn- insert-helper - "Given a (connected) database connection, a transaction flag and some SQL statements - (for one or more inserts), run a prepared statement or a sequence of them." - [db transaction? stmts opts] - (if transaction? - (with-db-transaction [t-db db] (multi-insert-helper t-db stmts opts)) - (multi-insert-helper db stmts opts))) - -(defn- col-str - "Transform a column spec to an entity name for SQL. The column spec may be a - string, a keyword or a map with a single pair - column name and alias." - [col entities] - (if (map? col) - (let [[k v] (first col)] - (str (as-sql-name entities k) " AS " (as-sql-name entities v))) - (as-sql-name entities col))) - -(defn- insert-multi-row-sql - "Given a table and a list of columns, followed by a list of column value sequences, - return a vector of the SQL needed for the insert followed by the list of column - value sequences. The entities function specifies how column names are transformed." - [table columns values entities] - (let [nc (count columns) - vcs (map count values)] - (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) - (throw (IllegalArgumentException. "insert! called with inconsistent number of columns / values")) - (into [(str "INSERT INTO " (table-str table entities) - (when (seq columns) - (str " ( " - (str/join ", " (map (fn [col] (col-str col entities)) columns)) - " )")) - " VALUES ( " - (str/join ", " (repeat (first vcs) "?")) - " )")] - values)))) - -(defn- insert-single-row-sql - "Given a table and a map representing a row, return a vector of the SQL needed for - the insert followed by the list of column values. The entities function specifies - how column names are transformed." - [table row entities] - (let [ks (keys row)] - (into [(str "INSERT INTO " (table-str table entities) " ( " - (str/join ", " (map (fn [col] (col-str col entities)) ks)) - " ) VALUES ( " - (str/join ", " (repeat (count ks) "?")) - " )")] - (vals row)))) - -(defn- insert-rows! - "Given a database connection, a table name, a sequence of rows, and an options - map, insert the rows into the database." - [db table rows opts] - (let [{:keys [entities transaction?] :as opts} - (merge {:entities identity :identifiers str/lower-case - :keywordize? true :transaction? true} - (when (map? db) db) - opts) - sql-params (map (fn [row] - (when-not (map? row) - (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) - (insert-single-row-sql table row entities)) rows)] - (if-let [con (db-find-connection db)] - (insert-helper db transaction? sql-params opts) - (with-open [con (get-connection db opts)] - (insert-helper (add-connection db con) transaction? sql-params opts))))) - -(defn- insert-cols! - "Given a database connection, a table name, a sequence of columns names, a - sequence of vectors of column values, one per row, and an options map, - insert the rows into the database." - [db table cols values opts] - (let [{:keys [entities transaction?] :as opts} - (merge {:entities identity :transaction? true} (when (map? db) db) opts) - sql-params (insert-multi-row-sql table cols values entities)] - (if-let [con (db-find-connection db)] - (db-do-prepared db transaction? sql-params (assoc opts :multi? true)) - (with-open [con (get-connection db opts)] - (db-do-prepared (add-connection db con) transaction? sql-params - (assoc opts :multi? true)))))) - -(defn insert! - "Given a database connection, a table name and either a map representing a rows, - or a list of column names followed by a list of column values also representing - a single row, perform an insert. - When inserting a row as a map, the result is the database-specific form of the - generated keys, if available (note: PostgreSQL returns the whole row). - When inserting a row as a list of column values, the result is the count of - rows affected (1), if available (from getUpdateCount after executeBatch). - The row map or column value vector may be followed by a map of options: - The :transaction? option specifies whether to run in a transaction or not. - The default is true (use a transaction). The :entities option specifies how - to convert the table name and column names to SQL entities." - ([db table row] (insert! db table row {})) - ([db table cols-or-row values-or-opts] - (if (map? values-or-opts) - (insert-rows! db table [cols-or-row] values-or-opts) - (insert-cols! db table cols-or-row [values-or-opts] {}))) - ([db table cols values opts] - (insert-cols! db table cols [values] opts))) - -(defn insert-multi! - "Given a database connection, a table name and either a sequence of maps (for - rows) or a sequence of column names, followed by a sequence of vectors (for - the values in each row), and possibly a map of options, insert that data into - the database. - - When inserting rows as a sequence of maps, the result is a sequence of the - generated keys, if available (note: PostgreSQL returns the whole rows). A - separate database operation is used for each row inserted. This may be slow - for if a large sequence of maps is provided. - - When inserting rows as a sequence of lists of column values, the result is - a sequence of the counts of rows affected (a sequence of 1's), if available. - Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch! - A single database operation is used to insert all the rows at once. This may - be much faster than inserting a sequence of rows (which performs an insert for - each map in the sequence). - - The :transaction? option specifies whether to run in a transaction or not. - The default is true (use a transaction). The :entities option specifies how - to convert the table name and column names to SQL entities." - ([db table rows] (insert-rows! db table rows {})) - ([db table cols-or-rows values-or-opts] - (if (map? values-or-opts) - (insert-rows! db table cols-or-rows values-or-opts) - (insert-cols! db table cols-or-rows values-or-opts {}))) - ([db table cols values opts] - (insert-cols! db table cols values opts))) - -(defn- update-sql - "Given a table name, a map of columns to set, a optional map of columns to - match, and an entities, return a vector of the SQL for that update followed - by its parameters. Example: - (update :person {:zip 94540} [\"zip = ?\" 94546] identity) - returns: - [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" - [table set-map [where & params] entities] - (let [ks (keys set-map) - vs (vals set-map)] - (cons (str "UPDATE " (table-str table entities) - " SET " (str/join - "," - (kv-sql ks vs entities " = NULL")) - (when where " WHERE ") - where) - (concat (remove nil? vs) params)))) - -(defn update! - "Given a database connection, a table name, a map of column values to set and a - where clause of columns to match, perform an update. The options may specify - how column names (in the set / match maps) should be transformed (default - 'as-is') and whether to run the update in a transaction (default true). - Example: - (update! db :person {:zip 94540} [\"zip = ?\" 94546]) - is equivalent to: - (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" - ([db table set-map where-clause] (update! db table set-map where-clause {})) - ([db table set-map where-clause opts] - (let [{:keys [entities] :as opts} - (merge {:entities identity :transaction? true} (when (map? db) db) opts)] - (execute! db (update-sql table set-map where-clause entities) opts)))) - -(defn create-table-ddl - "Given a table name and a vector of column specs, return the DDL string for - creating that table. Each column spec is, in turn, a vector of keywords or - strings that is converted to strings and concatenated with spaces to form - a single column description in DDL, e.g., - [:cost :int \"not null\"] - [:name \"varchar(32)\"] - The first element of a column spec is treated as a SQL entity (so if you - provide the :entities option, that will be used to transform it). The - remaining elements are left as-is when converting them to strings. - An options map may be provided that can contain: - :table-spec -- a string that is appended to the DDL -- and/or - :entities -- a function to specify how column names are transformed. - :conditional? -- either a boolean, indicating whether to add 'IF NOT EXISTS', - or a string, which is inserted literally before the table name, or a - function of two arguments (table name and the create statement), that can - manipulate the generated statement to better support other databases, e.g., - MS SQL Server which need to wrap create table in an existence query." - ([table specs] (create-table-ddl table specs {})) - ([table specs opts] - (let [table-spec (:table-spec opts) - conditional? (:conditional? opts) - entities (:entities opts identity) - table-name (as-sql-name entities table) - table-spec-str (or (and table-spec (str " " table-spec)) "") - spec-to-string (fn [spec] - (try - (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))) - (catch Exception _ - (throw (IllegalArgumentException. - "column spec is not a sequence of keywords / strings")))))] - (cond->> (format "CREATE TABLE%s %s (%s)%s" - (cond (or (nil? conditional?) - (instance? Boolean conditional?)) - (if conditional? " IF NOT EXISTS" "") - (fn? conditional?) - "" - :else - (str " " conditional?)) - table-name - (str/join ", " (map spec-to-string specs)) - table-spec-str) - (fn? conditional?) (conditional? table-name))))) - -(defn drop-table-ddl - "Given a table name, return the DDL string for dropping that table. - An options map may be provided that can contain: - :entities -- a function to specify how column names are transformed. - :conditional? -- either a boolean, indicating whether to add 'IF EXISTS', - or a string, which is inserted literally before the table name, or a - function of two arguments (table name and the create statement), that can - manipulate the generated statement to better support other databases, e.g., - MS SQL Server which need to wrap create table in an existence query." - ([table] (drop-table-ddl table {})) - ([table {:keys [entities conditional?] :or {entities identity}}] - (let [table-name (as-sql-name entities table)] - (cond->> (format "DROP TABLE%s %s" - (cond (or (nil? conditional?) - (instance? Boolean conditional?)) - (if conditional? " IF EXISTS" "") - (fn? conditional?) - "" - :else - (str " " conditional?)) - table-name) - (fn? conditional?) (conditional? table-name))))) +;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; The use and distribution terms for this software are covered by +;; the Eclipse Public License 1.0 +;; (http://opensource.org/licenses/eclipse-1.0.php) which can be +;; found in the file epl-v10.html at the root of this distribution. +;; By using this software in any fashion, you are agreeing to be +;; bound by the terms of this license. You must not remove this +;; notice, or any other, from this software. +;; +;; jdbc.clj +;; +;; A Clojure interface to sql databases via jdbc +;; +;; scgilardi (gmail) +;; Created 2 April 2008 +;; +;; seancorfield (gmail) +;; Migrated from clojure.contrib.sql 17 April 2011 + +(ns + ^{:author "Stephen C. Gilardi, Sean Corfield", + :doc "A Clojure interface to SQL databases via JDBC + +clojure.java.jdbc provides a simple abstraction for CRUD (create, read, +update, delete) operations on a SQL database, along with basic transaction +support. Basic DDL operations are also supported (create table, drop table, +access to table metadata). + +Maps are used to represent records, making it easy to store and retrieve +data. Results can be processed using any standard sequence operations. + +For most operations, Java's PreparedStatement is used so your SQL and +parameters can be represented as simple vectors where the first element +is the SQL string, with ? for each parameter, and the remaining elements +are the parameter values to be substituted. In general, operations return +the number of rows affected, except for a single record insert where any +generated keys are returned (as a map). + +For more documentation, see: + +http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} + clojure.java.jdbc + (:require [clojure.set :as set] + [clojure.string :as str] + [clojure.walk :as walk]) + (:import (java.net URI) + (java.sql BatchUpdateException DriverManager + PreparedStatement ResultSet ResultSetMetaData + SQLException Statement Types) + (java.util Hashtable Map Properties) + (javax.sql DataSource))) + +(defn as-sql-name + "Given a naming strategy function and a keyword or string, return + a string per that naming strategy. + A name of the form x.y is treated as multiple names, x, y, etc, + and each are turned into strings via the naming strategy and then + joined back together so x.y might become `x`.`y` if the naming + strategy quotes identifiers with `." + [f x] + (let [n (name x) + i (.indexOf n (int \.))] + (if (= -1 i) + (f n) + (str/join "." (map f (.split n "\\.")))))) + +(defn quoted + "Given a (vector) pair of delimiters (characters or strings), return a naming + strategy function that will quote SQL entities with them. + Given a single delimiter, treat it as a (vector) pair of that delimiter. + ((quoted [\\[ \\]]) \"foo\") will return \"[foo]\" -- for MS SQL Server + ((quoted \\`') \"foo\") will return \"`foo`\" -- for MySQL + Intended to be used with :entities to provide a quoting (naming) strategy that + is appropriate for your database." + [q] + (cond (vector? q) + (fn [x] + (str (first q) x (last q))) + (keyword? q) + (case q + :ansi (quoted \") + :mysql (quoted \`) + :oracle (quoted \") + :sqlserver (quoted [\[ \]])) + :else + (quoted [q q]))) + +(defn- table-str + "Transform a table spec to an entity name for SQL. The table spec may be a + string, a keyword or a map with a single pair - table name and alias." + [table entities] + (let [entities (or entities identity)] + (if (map? table) + (let [[k v] (first table)] + (str (as-sql-name entities k) " " (as-sql-name entities v))) + (as-sql-name entities table)))) + +(defn- kv-sql + "Given a sequence of column name keys and a matching sequence of column + values, and an entities mapping function, return a sequence of SQL fragments + that can be joined for part of an UPDATE SET or a SELECT WHERE clause. + Note that we pass the appropriate operator for NULL since it is different + in each case." + [ks vs entities null-op] + (map (fn [k v] + (str (as-sql-name entities k) + (if (nil? v) null-op " = ?"))) + ks vs)) + +(defn- ^Properties as-properties + "Convert any seq of pairs to a java.utils.Properties instance. + Uses as-sql-name to convert both keys and values into strings." + [m] + (let [p (Properties.)] + (doseq [[k v] m] + (.setProperty p (as-sql-name identity k) + (if (instance? clojure.lang.Named v) + (as-sql-name identity v) + (str v)))) + p)) + +;; convenience for working with different forms of connections +(defprotocol Connectable + (add-connection [db connection]) + (get-level [db])) + +(defn- inc-level + "Increment the nesting level for a transacted database connection. + If we are at the top level, also add in a rollback state." + [db] + (let [nested-db (update-in db [:level] (fnil inc 0))] + (if (= 1 (:level nested-db)) + (assoc nested-db :rollback (atom false)) + nested-db))) + +(extend-protocol Connectable + String + (add-connection [s connection] {:connection connection :level 0 :connection-string s}) + (get-level [_] 0) + + clojure.lang.Associative + (add-connection [m connection] (assoc m :connection connection)) + (get-level [m] (or (:level m) 0)) + + nil + (add-connection [_ connection] {:connection connection :level 0 :legacy true}) + (get-level [_] 0)) + +(def ^:private classnames + "Map of subprotocols to classnames. dbtype specifies one of these keys. + The subprotocols map below provides aliases for dbtype." + {"derby" "org.apache.derby.jdbc.EmbeddedDriver" + "h2" "org.h2.Driver" + "hsqldb" "org.hsqldb.jdbcDriver" + "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" + "mysql" "com.mysql.jdbc.Driver" + "oracle:oci" "oracle.jdbc.OracleDriver" + "oracle:thin" "oracle.jdbc.OracleDriver" + "postgresql" "org.postgresql.Driver" + "pgsql" "com.impossibl.postgres.jdbc.PGDriver" + "redshift" "com.amazon.redshift.jdbc.Driver" + "sqlite" "org.sqlite.JDBC" + "sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"}) + +(def ^:private subprotocols + "Map of schemes to subprotocols. Used to provide aliases for dbtype." + {"hsql" "hsqldb" + "jtds" "jtds:sqlserver" + "mssql" "sqlserver" + "oracle" "oracle:thin" + "postgres" "postgresql"}) + +(def ^:private host-prefixes + "Map of subprotocols to non-standard host-prefixes. + Anything not listed is assumed to use //." + {"oracle:oci" "@" + "oracle:thin" "@"}) + +(defn- parse-properties-uri [^URI uri] + (let [host (.getHost uri) + port (if (pos? (.getPort uri)) (.getPort uri)) + path (.getPath uri) + scheme (.getScheme uri) + subprotocol (subprotocols scheme scheme) + host-prefix (host-prefixes subprotocol "//") + ^String query (.getQuery uri) + query-parts (and query + (for [^String kvs (.split query "&")] + ((juxt first second) (.split kvs "="))))] + (merge + {:subname (if host + (if port + (str host-prefix host ":" port path) + (str host-prefix host path)) + (.getSchemeSpecificPart uri)) + :subprotocol subprotocol} + (if-let [user-info (.getUserInfo uri)] + {:user (first (str/split user-info #":")) + :password (second (str/split user-info #":"))}) + (walk/keywordize-keys (into {} query-parts))))) + +(defn- strip-jdbc [^String spec] + (if (.startsWith spec "jdbc:") + (.substring spec 5) + spec)) + +;; feature testing macro, based on suggestion from Chas Emerick: +(defmacro when-available + [sym & body] + (try + (when (resolve sym) + (list* 'do body)) + (catch ClassNotFoundException _#))) + +(defn- modify-connection + "Given a database connection and a map of options, update the connection + as specified by the options." + ^java.sql.Connection + [^java.sql.Connection connection opts] + (when (contains? opts :auto-commit?) + (.setAutoCommit connection (:auto-commit? opts))) + (when (contains? opts :read-only?) + (.setReadOnly connection (:read-only? opts))) + connection) + +(defn get-connection + "Creates a connection to a database. db-spec is usually a map containing connection + parameters but can also be a URI or a String. The various possibilities are described + below: + + DriverManager (preferred): + :dbtype (required) a String, the type of the database (the jdbc subprotocol) + :dbname (required) a String, the name of the database + :classname (optional) a String, the jdbc driver class name + :host (optional) a String, the host name/IP of the database + (defaults to 127.0.0.1) + :port (optional) a Long, the port of the database + (defaults to 3306 for mysql, 1433 for mssql/jtds, else nil) + (others) (optional) passed to the driver as properties + (may include :user and :password) + + Raw: + :connection-uri (required) a String + Passed directly to DriverManager/getConnection + (both :user and :password may be specified as well, rather + than passing them as part of the connection string) + + Other formats accepted: + + Existing Connection: + :connection (required) an existing open connection that can be used + but cannot be closed (only the parent connection can be closed) + + DriverManager (alternative / legacy style): + :subprotocol (required) a String, the jdbc subprotocol + :subname (required) a String, the jdbc subname + :classname (optional) a String, the jdbc driver class name + (others) (optional) passed to the driver as properties + (may include :user and :password) + + Factory: + :factory (required) a function of one argument, a map of params + (others) (optional) passed to the factory function in a map + + DataSource: + :datasource (required) a javax.sql.DataSource + :username (optional) a String - deprecated, use :user instead + :user (optional) a String - preferred + :password (optional) a String, required if :user is supplied + + JNDI: + :name (required) a String or javax.naming.Name + :environment (optional) a java.util.Map + + java.net.URI: + Parsed JDBC connection string (see java.lang.String format next) + + java.lang.String: + subprotocol://user:password@host:post/subname + An optional prefix of jdbc: is allowed." + (^java.sql.Connection [db-spec] (get-connection db-spec {})) + (^java.sql.Connection + [{:keys [connection + factory + connection-uri + classname subprotocol subname + dbtype dbname host port + datasource username password user + name environment] + :as db-spec} + opts] + (cond + (string? db-spec) + (get-connection (URI. (strip-jdbc db-spec)) opts) + + (instance? URI db-spec) + (get-connection (parse-properties-uri db-spec) opts) + + connection + connection ;; do not apply opts here + + (or (and datasource username password) ; legacy + (and datasource user password)) ; preferred + (-> (.getConnection ^DataSource datasource + ^String (or username user) + ^String password) + (modify-connection opts)) + + datasource + (-> (.getConnection ^DataSource datasource) + (modify-connection opts)) + + factory + (-> (factory (dissoc db-spec :factory)) + (modify-connection opts)) + + connection-uri + (-> (if (and user password) + (DriverManager/getConnection connection-uri user password) + (DriverManager/getConnection connection-uri)) + (modify-connection opts)) + + (and dbtype dbname) + (let [;; allow aliases for dbtype + subprotocol (subprotocols dbtype dbtype) + host (or host "127.0.0.1") + port (or port (condp = subprotocol + "jtds:sqlserver" 1433 + "mysql" 3306 + "oracle:oci" 1521 + "oracle:thin" 1521 + "postgresql" 5432 + "sqlserver" 1433 + nil)) + db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") + url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) + (str "jdbc:" subprotocol ":" dbname) + (str "jdbc:" subprotocol ":" + (host-prefixes subprotocol "//") + host + (when port (str ":" port)) + db-sep dbname)) + etc (dissoc db-spec :dbtype :dbname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + + (and subprotocol subname) + (let [;; allow aliases for subprotocols + subprotocol (subprotocols subprotocol subprotocol) + url (format "jdbc:%s:%s" subprotocol subname) + etc (dissoc db-spec :classname :subprotocol :subname)] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (clojure.lang.RT/loadClassForName class-name)) + (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + + name + (or (when-available javax.naming.InitialContext + (let [env (and environment (Hashtable. ^Map environment)) + context (javax.naming.InitialContext. env) + ^DataSource datasource (.lookup context ^String name)] + (-> (.getConnection datasource) + (modify-connection opts)))) + (throw (ex-info (str "javax.naming.InitialContext is not available for: " + name) + db-spec))) + + :else + (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] + (throw (IllegalArgumentException. msg)))))) + +(defn- make-name-unique + "Given a collection of column names and a new column name, + return the new column name made unique, if necessary, by + appending _N where N is some unique integer suffix." + [cols col-name n] + (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] + (if (apply distinct? suffixed-name cols) + suffixed-name + (recur cols col-name (inc n))))) + +(defn- make-cols-unique + "Given a collection of column names, rename duplicates so + that the result is a collection of unique column names." + [cols] + (if (or (empty? cols) (apply distinct? cols)) + cols + (reduce (fn [unique-cols col-name] + (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) + +(defprotocol ISQLValue + "Protocol for creating SQL values from Clojure values. Default + implementations (for Object and nil) just return the argument, + but it can be extended to provide custom behavior to support + exotic types supported by different databases." + (sql-value [val] "Convert a Clojure value into a SQL value.")) + +(extend-protocol ISQLValue + Object + (sql-value [v] v) + + nil + (sql-value [_] nil)) + +(defprotocol ISQLParameter + "Protocol for setting SQL parameters in statement objects, which + can convert from Clojure values. The default implementation just + delegates the conversion to ISQLValue's sql-value conversion and + uses .setObject on the parameter. It can be extended to use other + methods of PreparedStatement to convert and set parameter values." + (set-parameter [val stmt ix] + "Convert a Clojure value into a SQL value and store it as the ix'th + parameter in the given SQL statement object.")) + +(extend-protocol ISQLParameter + Object + (set-parameter [v ^PreparedStatement s ^long i] + (.setObject s i (sql-value v))) + + nil + (set-parameter [_ ^PreparedStatement s ^long i] + (.setObject s i (sql-value nil)))) + +(defn- dft-set-parameters + "Default implementation of parameter setting for the given statement." + [stmt params] + (dorun (map-indexed (fn [ix value] + (set-parameter value stmt (inc ix))) + params))) + +(defprotocol IResultSetReadColumn + "Protocol for reading objects from the java.sql.ResultSet. Default + implementations (for Object and nil) return the argument, and the + Boolean implementation ensures a canonicalized true/false value, + but it can be extended to provide custom behavior for special types." + (result-set-read-column [val rsmeta idx] + "Function for transforming values after reading them from the database")) + +(extend-protocol IResultSetReadColumn + Object + (result-set-read-column [x _2 _3] x) + + Boolean + (result-set-read-column [x _2 _3] (if (= true x) true false)) + + nil + (result-set-read-column [_1 _2 _3] nil)) + +(defn- dft-read-columns + "Default implementation of reading row values from result set, given the + result set metadata and the indices." + [^ResultSet rs rsmeta idxs] + (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) + +(defn result-set-seq + "Creates and returns a lazy sequence of maps corresponding to the rows in the + java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it + respects the specified naming strategy. Duplicate column names are made unique + by appending _N before applying the naming strategy (where N is a unique integer), + unless the :as-arrays? option is :cols-as-is, in which case the column names + are untouched (the result set maintains column name/value order). + The :identifiers option specifies how SQL column names are converted to Clojure + keywords. The default is to convert them to lower case. + The :keywordize? option can be specified as false to opt-out of the conversion + to keywords. + The :qualifier option specifies the namespace qualifier for those identifiers + (and this may not be specified when :keywordize? is false)." + ([rs] (result-set-seq rs {})) + ([^ResultSet rs {:keys [as-arrays? identifiers keywordize? + qualifier read-columns] + :or {identifiers str/lower-case + keywordize? true + read-columns dft-read-columns}}] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) + identifier-fn (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers) + keys (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + col-name-fn + (mapv identifier-fn)) + row-values (fn [] (read-columns rs rsmeta idxs)) + ;; This used to use create-struct (on keys) and then struct to populate each row. + ;; That had the side effect of preserving the order of columns in each row. As + ;; part of JDBC-15, this was changed because structmaps are deprecated. We don't + ;; want to switch to records so we're using regular maps instead. We no longer + ;; guarantee column order in rows but using into {} should preserve order for up + ;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying + ;; on the order-preserving behavior of structmaps, we can reconsider... + records (fn thisfn [] + (when (.next rs) + (cons (zipmap keys (row-values)) (lazy-seq (thisfn))))) + rows (fn thisfn [] + (when (.next rs) + (cons (vec (row-values)) (lazy-seq (thisfn)))))] + (if as-arrays? + (cons (vec keys) (rows)) + (records))))) + +(defn- execute-batch + "Executes a batch of SQL commands and returns a sequence of update counts. + (-2) indicates a single operation operating on an unknown number of rows. + Specifically, Oracle returns that and we must call getUpdateCount() to get + the actual number of rows affected. In general, operations return an array + of update counts, so this may not be a general solution for Oracle..." + [^Statement stmt] + (let [result (.executeBatch stmt)] + (if (and (= 1 (count result)) (= -2 (first result))) + (list (.getUpdateCount stmt)) + (seq result)))) + +(def ^{:private true + :doc "Map friendly :concurrency values to ResultSet constants."} + result-set-concurrency + {:read-only ResultSet/CONCUR_READ_ONLY + :updatable ResultSet/CONCUR_UPDATABLE}) + +(def ^{:private true + :doc "Map friendly :cursors values to ResultSet constants."} + result-set-holdability + {:hold ResultSet/HOLD_CURSORS_OVER_COMMIT + :close ResultSet/CLOSE_CURSORS_AT_COMMIT}) + +(def ^{:private true + :doc "Map friendly :type values to ResultSet constants."} + result-set-type + {:forward-only ResultSet/TYPE_FORWARD_ONLY + :scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE + :scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE}) + +(defn ^{:tag (class (into-array String []))} string-array + [return-keys] + (into-array String return-keys)) + +(defn prepare-statement + "Create a prepared statement from a connection, a SQL string and a map + of options: + :return-keys truthy | nil - default nil + for some drivers, this may be a vector of column names to identify + the generated keys to return, otherwise it should just be true + :result-type :forward-only | :scroll-insensitive | :scroll-sensitive + :concurrency :read-only | :updatable + :cursors :hold | :close + :fetch-size n + :max-rows n + :timeout n + Note that :result-type and :concurrency must be specified together as the + underlying Java API expects both (or neither)." + ([con sql] (prepare-statement con sql {})) + ([^java.sql.Connection con ^String sql + {:keys [return-keys result-type concurrency cursors + fetch-size max-rows timeout]}] + (let [^PreparedStatement + stmt (cond + return-keys + (do + (when (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified with :return-keys.")))) + (try + (if (vector? return-keys) + (try + (.prepareStatement con sql (string-array return-keys)) + (catch Exception _ + ;; assume it is unsupported and try regular generated keys: + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))) + (.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)) + (catch Exception _ + ;; assume it is unsupported and try basic PreparedStatement: + (.prepareStatement con sql)))) + + (and result-type concurrency) + (if cursors + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency) + (get result-set-holdability cursors cursors)) + (.prepareStatement con sql + (get result-set-type result-type result-type) + (get result-set-concurrency concurrency concurrency))) + + (or result-type concurrency cursors) + (throw (IllegalArgumentException. + (str ":concurrency, :cursors, and :result-type " + "may not be specified independently."))) + :else + (.prepareStatement con sql))] + (when fetch-size (.setFetchSize stmt fetch-size)) + (when max-rows (.setMaxRows stmt max-rows)) + (when timeout (.setQueryTimeout stmt timeout)) + stmt))) + +(defn print-sql-exception + "Prints the contents of an SQLException to *out*" + [^SQLException exception] + (let [^Class exception-class (class exception)] + (println + (format (str "%s:" \newline + " Message: %s" \newline + " SQLState: %s" \newline + " Error Code: %d") + (.getSimpleName exception-class) + (.getMessage exception) + (.getSQLState exception) + (.getErrorCode exception))))) + +(defn print-sql-exception-chain + "Prints a chain of SQLExceptions to *out*" + [^SQLException exception] + (loop [e exception] + (when e + (print-sql-exception e) + (recur (.getNextException e))))) + +(def ^{:private true} special-counts + {Statement/EXECUTE_FAILED "EXECUTE_FAILED" + Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"}) + +(defn print-update-counts + "Prints the update counts from a BatchUpdateException to *out*" + [^BatchUpdateException exception] + (println "Update counts:") + (dorun + (map-indexed + (fn [index count] + (println (format " Statement %d: %s" + index + (get special-counts count count)))) + (.getUpdateCounts exception)))) + +;; java.jdbc pieces rewritten to not use dynamic bindings + +(defn db-find-connection + "Returns the current database connection (or nil if there is none)" + ^java.sql.Connection [db] + (and (map? db) + (:connection db))) + +(defn db-connection + "Returns the current database connection (or throws if there is none)" + ^java.sql.Connection [db] + (or (db-find-connection db) + (throw (Exception. "no current database connection")))) + +(defn db-set-rollback-only! + "Marks the outermost transaction such that it will rollback rather than + commit when complete" + [db] + (reset! (:rollback db) true)) + +(defn db-unset-rollback-only! + "Marks the outermost transaction such that it will not rollback when complete" + [db] + (reset! (:rollback db) false)) + +(defn db-is-rollback-only + "Returns true if the outermost transaction will rollback rather than + commit when complete" + [db] + (deref (:rollback db))) + +(def ^:private + isolation-levels + "Transaction isolation levels." + {:none java.sql.Connection/TRANSACTION_NONE + :read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED + :read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED + :repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ + :serializable java.sql.Connection/TRANSACTION_SERIALIZABLE}) + +(def ^:private isolation-kws + "Map transaction isolation constants to our keywords." + (set/map-invert isolation-levels)) + +(defn get-isolation-level + "Given a db-spec (with an optional connection), return the current + transaction isolation level, if known. Return nil if there is no + active connection in the db-spec. Return :unknown if we do not + recognize the isolation level." + [db] + (when-let [con (db-find-connection db)] + (isolation-kws (.getTransactionIsolation con) :unknown))) + +(defn db-transaction* + "Evaluates func as a transaction on the open database connection. Any + nested transactions are absorbed into the outermost transaction. By + default, all database updates are committed together as a group after + evaluating the outermost body, or rolled back on any uncaught + exception. If rollback is set within scope of the outermost transaction, + the entire transaction will be rolled back rather than committed when + complete. + The isolation option may be :none, :read-committed, :read-uncommitted, + :repeatable-read, or :serializable. Note that not all databases support + all of those isolation levels, and may either throw an exception or + substitute another isolation level. + The read-only? option puts the transaction in readonly mode (if supported)." + ([db func] (db-transaction* db func {})) + ([db func opts] + (let [{:keys [isolation read-only?] :as opts} + (merge (when (map? db) db) opts)] + (if (zero? (get-level db)) + (if-let [con (db-find-connection db)] + (let [nested-db (inc-level db) + auto-commit (.getAutoCommit con) + old-isolation (.getTransactionIsolation con) + old-readonly (.isReadOnly con)] + (io! + (when isolation + (.setTransactionIsolation con (isolation isolation-levels))) + (when read-only? + (.setReadOnly con true)) + (.setAutoCommit con false) + (try + (let [result (func nested-db)] + (if (db-is-rollback-only nested-db) + (.rollback con) + (.commit con)) + result) + (catch Throwable t + (try + (.rollback con) + (catch Throwable rb + ;; combine both exceptions + (throw (ex-info (str "Rollback failed handling \"" + (.getMessage t) + "\"") + {:rollback rb + :handling t})))) + (throw t)) + (finally + (db-unset-rollback-only! nested-db) + ;; the following can throw SQLExceptions but we do not + ;; want those to replace any exception currently being + ;; handled -- and if the connection got closed, we just + ;; want to ignore exceptions here anyway + (try + (.setAutoCommit con auto-commit) + (catch Exception _)) + (when isolation + (try + (.setTransactionIsolation con old-isolation) + (catch Exception _))) + (when read-only? + (try + (.setReadOnly con old-readonly) + (catch Exception _))))))) + (with-open [con (get-connection db opts)] + (db-transaction* (add-connection db con) func opts))) + (do + (when (and isolation + (let [con (db-find-connection db)] + (not= (isolation isolation-levels) + (.getTransactionIsolation con)))) + (let [msg "Nested transactions may not have different isolation levels"] + (throw (IllegalStateException. msg)))) + (func (inc-level db))))))) + +(defmacro with-db-transaction + "Evaluates body in the context of a transaction on the specified database connection. + The binding provides the database connection for the transaction and the name to which + that is bound for evaluation of the body. The binding may also specify the isolation + level for the transaction, via the :isolation option and/or set the transaction to + readonly via the :read-only? option. + (with-db-transaction [t-con db-spec {:isolation level :read-only? true}] + ... t-con ...) + See db-transaction* for more details." + [binding & body] + `(db-transaction* ~(second binding) + (^{:once true} fn* [~(first binding)] ~@body) + ~@(rest (rest binding)))) + +(defmacro with-db-connection + "Evaluates body in the context of an active connection to the database. + (with-db-connection [con-db db-spec opts] + ... con-db ...)" + [binding & body] + `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (add-connection db-spec# con#)] + ~@body)))) + +(defmacro with-db-metadata + "Evaluates body in the context of an active connection with metadata bound + to the specified name. See also metadata-result for dealing with the results + of operations that retrieve information from the metadata. + (with-db-metadata [md db-spec opts] + ... md ...)" + [binding & body] + `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (.getMetaData con#)] + ~@body)))) + +(defn metadata-result + "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, + else return it as-is. This makes working with metadata easier. + Also accepts an option map containing :identifiers, :keywordize?, :qualifier, + :as-arrays?, :row-fn,and :result-set-fn to control how the ResultSet is + transformed and returned. See query for more details." + ([rs-or-value] (metadata-result rs-or-value {})) + ([rs-or-value opts] + (let [{:keys [as-arrays? result-set-fn row-fn] :as opts} + (merge {:identifiers str/lower-case + :keywordize? true + :read-columns dft-read-columns + :row-fn identity} opts) + result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (if (instance? java.sql.ResultSet rs-or-value) + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rs-or-value opts)) + rs-or-value)))) + +(defmacro metadata-query + "Given a Java expression that extracts metadata (in the context of with-db-metadata), + and a map of options like metadata-result, manage the connection for a single + metadata-based query. Example usage: + + (with-db-metadata [meta db-spec] + (metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"])) + {:row-fn ... :result-set-fn ...}))" + [meta-query & opt-args] + `(with-open [rs# ~meta-query] + (metadata-result rs# ~@opt-args))) + +(defn db-do-commands + "Executes SQL commands on the specified database connection. Wraps the commands + in a transaction if transaction? is true. transaction? can be ommitted and it + defaults to true. Accepts a single SQL command (string) or a vector of them. + Uses executeBatch. This may affect what SQL you can run via db-do-commands." + ([db sql-commands] + (db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands))) + ([db transaction? sql-commands] + (if (string? sql-commands) + (db-do-commands db transaction? [sql-commands]) + (if-let [con (db-find-connection db)] + (with-open [^Statement stmt (.createStatement con)] + (doseq [^String cmd sql-commands] + (.addBatch stmt cmd)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt))) + (with-open [con (get-connection db)] + (db-do-commands (add-connection db con) transaction? sql-commands)))))) + +(defn- db-do-execute-prepared-return-keys + "Executes a PreparedStatement, optionally in a transaction, and (attempts to) + return any generated keys." + [db ^PreparedStatement stmt param-group opts] + (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts) + exec-and-return-keys + (^{:once true} fn* [] + (let [counts (.executeUpdate stmt)] + (try + (let [rs (.getGeneratedKeys stmt) + result (first (result-set-seq rs opts))] + ;; sqlite (and maybe others?) requires + ;; record set to be closed + (.close rs) + result) + (catch Exception _ + ;; assume generated keys is unsupported and return counts instead: + counts))))] + ((:set-parameters opts dft-set-parameters) stmt param-group) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (exec-and-return-keys)) + (exec-and-return-keys)))) + +(defn- sql-stmt? + "Given an expression, return true if it is either a string (SQL) or a + PreparedStatement." + [expr] + (or (string? expr) (instance? PreparedStatement expr))) + +(defn db-do-prepared-return-keys + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. The param-group is a seq of values for all of + the parameters. transaction? can be ommitted and will default to true. + Return the generated keys for the (single) update/insert. + A PreparedStatement may be passed in, instead of a SQL string, in which + case :return-keys MUST BE SET on that PreparedStatement!" + ([db sql-params] + (db-do-prepared-return-keys db true sql-params {})) + ([db transaction? sql-params] + (if (map? sql-params) + (db-do-prepared-return-keys db true transaction? sql-params) + (db-do-prepared-return-keys db transaction? sql-params {}))) + ([db transaction? sql-params opts] + (let [opts (merge (when (map? db) db) opts)] + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) + (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] + (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) + (with-open [con (get-connection db opts)] + (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) + +(defn- db-do-execute-prepared-statement + "Execute a PreparedStatement, optionally in a transaction." + [db ^PreparedStatement stmt param-groups opts] + (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts)] + (if (empty? param-groups) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (vector (.executeUpdate stmt))) + (vector (.executeUpdate stmt))) + (do + (doseq [param-group param-groups] + ((:set-parameters opts dft-set-parameters) stmt param-group) + (.addBatch stmt)) + (if transaction? + (with-db-transaction [t-db (add-connection db (.getConnection stmt))] + (execute-batch stmt)) + (execute-batch stmt)))))) + +(defn db-do-prepared + "Executes an (optionally parameterized) SQL prepared statement on the + open database connection. Each param-group is a seq of values for all of + the parameters. transaction? can be omitted and defaults to true. + The sql parameter can either be a SQL string or a PreparedStatement. + Return a seq of update counts (one count for each param-group)." + ([db sql-params] + (db-do-prepared db true sql-params {})) + ([db transaction? sql-params] + (if (map? sql-params) + (db-do-prepared db true transaction? sql-params) + (db-do-prepared db transaction? sql-params {}))) + ([db transaction? sql-params opts] + (let [opts (merge (when (map? db) db) opts)] + (if-let [con (db-find-connection db)] + (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + params (if (or (:multi? opts) (empty? params)) params [params])] + (if (instance? PreparedStatement sql) + (db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?)) + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?))))) + (with-open [con (get-connection db opts)] + (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) + +(defn db-query-with-resultset + "Executes a query, then evaluates func passing in the raw ResultSet as an + argument. The second argument is a vector containing either: + [sql & params] - a SQL query, followed by any parameters it needs + [stmt & params] - a PreparedStatement, followed by any parameters it needs + (the PreparedStatement already contains the SQL query) + The opts map is passed to prepare-statement. + Uses executeQuery. This may affect what SQL you can run via query." + ([db sql-params func] (db-query-with-resultset db sql-params func {})) + ([db sql-params func opts] + (let [opts (merge (when (map? db) db) opts) + [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] + ((:set-parameters opts dft-set-parameters) stmt params) + (with-open [rset (.executeQuery stmt)] + (func rset)))] + (when-not (sql-stmt? sql) + (let [^Class sql-class (class sql) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-class) + (pr-str sql))] + (throw (IllegalArgumentException. msg)))) + (if (instance? PreparedStatement sql) + (let [^PreparedStatement stmt sql] + (run-query-with-params stmt)) + (if-let [con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (run-query-with-params stmt)) + (with-open [con (get-connection db opts)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (run-query-with-params stmt)))))))) + +;; top-level API for actual SQL operations + +(defn query + "Given a database connection and a vector containing SQL and optional parameters, + perform a simple database query. The options specify how to construct the result + set (and are also passed to prepare-statement as needed): + :as-arrays? - return the results as a set of arrays, default false. + :identifiers - applied to each column name in the result set, default lower-case + :keywordize? - defaults to true, can be false to opt-out of converting + identifiers to keywords + :qualifier - optionally provides the namespace qualifier for identifiers + :result-set-fn - applied to the entire result set, default doall / vec + if :as-arrays? true, :result-set-fn will default to vec + if :as-arrays? false, :result-set-fn will default to doall + :row-fn - applied to each row as the result set is constructed, default identity + The second argument is a vector containing a SQL string or PreparedStatement, followed + by any parameters it needs. + See also prepare-statement for additional options." + ([db sql-params] (query db sql-params {})) + ([db sql-params opts] + (let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts} + (merge {:explain-fn println :identifiers str/lower-case + :keywordize? true + :read-columns dft-read-columns :row-fn identity} + (when (map? db) db) + opts) + result-set-fn (or result-set-fn (if as-arrays? vec doall)) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (when (and explain? (string? (first sql-params-vector))) + (query db (into [(str (if (string? explain?) explain? "EXPLAIN") + " " + (first sql-params-vector))] + (rest sql-params-vector)) + (-> opts + (dissoc :explain? :result-set-fn :row-fn) + (assoc :result-set-fn explain-fn)))) + (db-query-with-resultset db sql-params-vector + (^{:once true} fn* [rset] + ((^{:once true} fn* [rs] + (result-set-fn (if as-arrays? + (cons (first rs) + (map row-fn (rest rs))) + (map row-fn rs)))) + (result-set-seq rset opts))) + opts)))) + +;; performance notes -- goal is to lift as much logic as possible into a "once" +;; pass (so reducible-query preloads all the stuff that doesn't depend on the +;; query results, and then you can repeatedly reduce it, which runs the query +;; each time and runs the minimal result set reduction) +;; turn make-cols-unique into a transducer and optimize it +;; turn make-keys into a transducer pipeline and lift it +;; lift identifier-fn out as make-identifier-fn and refactor +;; lift init-reduce +;; refactor reducible-result-set to lift identifier-fn out +;; call new reducible-result-set version from reducible-query (after calling +;; make-identifier-fn etc) +;; create an optimized version of db-query-with-resultset without :as-arrays? +;; and with options handling lifted + +(defn reducible-result-set + "Given a java.sql.ResultSet return a reducible collection. + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + Note: :as-arrays? is not accepted here." + [^ResultSet rs {:keys [identifiers keywordize? qualifier read-columns] + :or {identifiers str/lower-case + keywordize? true + read-columns dft-read-columns}}] + (let [identifier-fn (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers) + make-keys (fn [idxs ^ResultSetMetaData rsmeta] + (->> idxs + (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) + (make-cols-unique) + (mapv identifier-fn))) + init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init')))] + (reify clojure.lang.IReduce + (reduce [this f] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (make-keys idxs rsmeta)] + (if (.next rs) + ;; reduce init is first row of ResultSet + (init-reduce keys rs rsmeta idxs f + (zipmap keys (read-columns rs rsmeta idxs))) + ;; no rows so call 0-arity f to get result value + ;; per reduce docstring contract + (f)))) + (reduce [this f init] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + keys (make-keys idxs rsmeta)] + (init-reduce keys rs rsmeta idxs f init)))))) + +(defn reducible-query + "Given a database connection, a vector containing SQL and optional parameters, + return a reducible collection. When reduced, it will start the database query + and reduce the result set, and then close the connection: + (transduce (map :cost) + (reducible-query db sql-params)) + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + The following options from query etc are not accepted here: + :as-arrays? :explain :explain-fn :result-set-fn :row-fn + See also prepare-statement for additional options." + ([db sql-params] (reducible-query db sql-params {})) + ([db sql-params opts] + (let [opts (merge {:identifiers str/lower-case :keywordize? true + :read-columns dft-read-columns} + (when (map? db) db) + opts) + sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (reify clojure.lang.IReduce + (reduce [this f] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f (reducible-result-set rset opts))) + opts)) + (reduce [this f init] + (db-query-with-resultset + db sql-params-vector + (^{:once true} fn* [rset] + (reduce f init (reducible-result-set rset opts))) + opts)))))) + +(defn- direction + "Given an entities function, a column name, and a direction, + return the matching SQL column / order. + Throw an exception for an invalid direction." + [entities c d] + (str (as-sql-name entities c) " " + (if-let [dir (#{"ASC" "DESC"} (str/upper-case (name d)))] + dir + (throw (IllegalArgumentException. (str "expected :asc or :desc, found: " d)))))) + +(defn- order-by-sql + "Given a sequence of column specs and an entities function, return + a SQL fragment for the ORDER BY clause. A column spec may be a name + (either a string or keyword) or a map from column name to direction + (:asc or :desc)." + [order-by entities] + (str/join ", " (mapcat (fn [col] + (if (map? col) + (reduce-kv (fn [v c d] + (conj v (direction entities c d))) + [] + col) + [(direction entities col :asc)])) order-by))) + +(defn find-by-keys + "Given a database connection, a table name, a map of column name/value + pairs, and an optional options map, return any matching rows. + An :order-by option may be supplied to sort the rows by a sequence of + columns, e.g,. {:order-by [:name {:age :desc]}" + ([db table columns] (find-by-keys db table columns {})) + ([db table columns opts] + (let [{:keys [entities order-by] :as opts} + (merge {:entities identity} (when (map? db) db) opts) + ks (keys columns) + vs (vals columns)] + (query db (into [(str "SELECT * FROM " (table-str table entities) + " WHERE " (str/join " AND " + (kv-sql ks vs entities " IS NULL")) + (when (seq order-by) + (str " ORDER BY " + (order-by-sql order-by entities))))] + (remove nil? vs)) + opts)))) + +(defn get-by-id + "Given a database connection, a table name, a primary key value, an + optional primary key column name, and an optional options map, return + a single matching row, or nil. + The primary key column name defaults to :id." + ([db table pk-value] (get-by-id db table pk-value :id {})) + ([db table pk-value pk-name-or-opts] + (if (map? pk-name-or-opts) + (get-by-id db table pk-value :id pk-name-or-opts) + (get-by-id db table pk-value pk-name-or-opts {}))) + ([db table pk-value pk-name opts] + (let [opts (merge (when (map? db) db) opts) + r-s-fn (or (:result-set-fn opts) identity)] + (find-by-keys db table {pk-name pk-value} + (assoc opts :result-set-fn (comp first r-s-fn)))))) + +(defn execute! + "Given a database connection and a vector containing SQL (or PreparedStatement) + followed by optional parameters, perform a general (non-select) SQL operation. + The :transaction? option specifies whether to run the operation in a + transaction or not (default true). + If the :multi? option is false (the default), the SQL statement should be + followed by the parameters for that statement. + If the :multi? option is true, the SQL statement should be followed by one or + more vectors of parameters, one for each application of the SQL statement. + If there are no parameters specified, executeUpdate will be used, otherwise + executeBatch will be used. This may affect what SQL you can run via execute!" + ([db sql-params] (execute! db sql-params {})) + ([db sql-params opts] + (let [{:keys [transaction?] :as opts} + (merge {:transaction? true :multi? false} (when (map? db) db) opts) + execute-helper (^{:once true} fn* [db] + (db-do-prepared db transaction? sql-params opts))] + (if-let [con (db-find-connection db)] + (execute-helper db) + (with-open [con (get-connection db opts)] + (execute-helper (add-connection db con))))))) + +(defn- delete-sql + "Given a table name, a where class and its parameters and an optional entities spec, + return a vector of the SQL for that delete operation followed by its parameters. The + entities spec (default 'as-is') specifies how to transform column names." + [table [where & params] entities] + (into [(str "DELETE FROM " (table-str table entities) + (when where " WHERE ") where)] + params)) + +(defn delete! + "Given a database connection, a table name and a where clause of columns to match, + perform a delete. The options may specify how to transform column names in the + map (default 'as-is') and whether to run the delete in a transaction (default true). + Example: + (delete! db :person [\"zip = ?\" 94546]) + is equivalent to: + (execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])" + ([db table where-clause] (delete! db table where-clause {})) + ([db table where-clause opts] + (let [{:keys [entities] :as opts} + (merge {:entities identity :transaction? true} (when (map? db) db) opts)] + (execute! db (delete-sql table where-clause entities) opts)))) + +(defn- multi-insert-helper + "Given a (connected) database connection and some SQL statements (for multiple + inserts), run a prepared statement on each and return any generated keys. + Note: we are eager so an unrealized lazy-seq cannot escape from the connection." + [db stmts opts] + (doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts))) + +(defn- insert-helper + "Given a (connected) database connection, a transaction flag and some SQL statements + (for one or more inserts), run a prepared statement or a sequence of them." + [db transaction? stmts opts] + (if transaction? + (with-db-transaction [t-db db] (multi-insert-helper t-db stmts opts)) + (multi-insert-helper db stmts opts))) + +(defn- col-str + "Transform a column spec to an entity name for SQL. The column spec may be a + string, a keyword or a map with a single pair - column name and alias." + [col entities] + (if (map? col) + (let [[k v] (first col)] + (str (as-sql-name entities k) " AS " (as-sql-name entities v))) + (as-sql-name entities col))) + +(defn- insert-multi-row-sql + "Given a table and a list of columns, followed by a list of column value sequences, + return a vector of the SQL needed for the insert followed by the list of column + value sequences. The entities function specifies how column names are transformed." + [table columns values entities] + (let [nc (count columns) + vcs (map count values)] + (if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs))) + (throw (IllegalArgumentException. "insert! called with inconsistent number of columns / values")) + (into [(str "INSERT INTO " (table-str table entities) + (when (seq columns) + (str " ( " + (str/join ", " (map (fn [col] (col-str col entities)) columns)) + " )")) + " VALUES ( " + (str/join ", " (repeat (first vcs) "?")) + " )")] + values)))) + +(defn- insert-single-row-sql + "Given a table and a map representing a row, return a vector of the SQL needed for + the insert followed by the list of column values. The entities function specifies + how column names are transformed." + [table row entities] + (let [ks (keys row)] + (into [(str "INSERT INTO " (table-str table entities) " ( " + (str/join ", " (map (fn [col] (col-str col entities)) ks)) + " ) VALUES ( " + (str/join ", " (repeat (count ks) "?")) + " )")] + (vals row)))) + +(defn- insert-rows! + "Given a database connection, a table name, a sequence of rows, and an options + map, insert the rows into the database." + [db table rows opts] + (let [{:keys [entities transaction?] :as opts} + (merge {:entities identity :identifiers str/lower-case + :keywordize? true :transaction? true} + (when (map? db) db) + opts) + sql-params (map (fn [row] + (when-not (map? row) + (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) + (insert-single-row-sql table row entities)) rows)] + (if-let [con (db-find-connection db)] + (insert-helper db transaction? sql-params opts) + (with-open [con (get-connection db opts)] + (insert-helper (add-connection db con) transaction? sql-params opts))))) + +(defn- insert-cols! + "Given a database connection, a table name, a sequence of columns names, a + sequence of vectors of column values, one per row, and an options map, + insert the rows into the database." + [db table cols values opts] + (let [{:keys [entities transaction?] :as opts} + (merge {:entities identity :transaction? true} (when (map? db) db) opts) + sql-params (insert-multi-row-sql table cols values entities)] + (if-let [con (db-find-connection db)] + (db-do-prepared db transaction? sql-params (assoc opts :multi? true)) + (with-open [con (get-connection db opts)] + (db-do-prepared (add-connection db con) transaction? sql-params + (assoc opts :multi? true)))))) + +(defn insert! + "Given a database connection, a table name and either a map representing a rows, + or a list of column names followed by a list of column values also representing + a single row, perform an insert. + When inserting a row as a map, the result is the database-specific form of the + generated keys, if available (note: PostgreSQL returns the whole row). + When inserting a row as a list of column values, the result is the count of + rows affected (1), if available (from getUpdateCount after executeBatch). + The row map or column value vector may be followed by a map of options: + The :transaction? option specifies whether to run in a transaction or not. + The default is true (use a transaction). The :entities option specifies how + to convert the table name and column names to SQL entities." + ([db table row] (insert! db table row {})) + ([db table cols-or-row values-or-opts] + (if (map? values-or-opts) + (insert-rows! db table [cols-or-row] values-or-opts) + (insert-cols! db table cols-or-row [values-or-opts] {}))) + ([db table cols values opts] + (insert-cols! db table cols [values] opts))) + +(defn insert-multi! + "Given a database connection, a table name and either a sequence of maps (for + rows) or a sequence of column names, followed by a sequence of vectors (for + the values in each row), and possibly a map of options, insert that data into + the database. + + When inserting rows as a sequence of maps, the result is a sequence of the + generated keys, if available (note: PostgreSQL returns the whole rows). A + separate database operation is used for each row inserted. This may be slow + for if a large sequence of maps is provided. + + When inserting rows as a sequence of lists of column values, the result is + a sequence of the counts of rows affected (a sequence of 1's), if available. + Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch! + A single database operation is used to insert all the rows at once. This may + be much faster than inserting a sequence of rows (which performs an insert for + each map in the sequence). + + The :transaction? option specifies whether to run in a transaction or not. + The default is true (use a transaction). The :entities option specifies how + to convert the table name and column names to SQL entities." + ([db table rows] (insert-rows! db table rows {})) + ([db table cols-or-rows values-or-opts] + (if (map? values-or-opts) + (insert-rows! db table cols-or-rows values-or-opts) + (insert-cols! db table cols-or-rows values-or-opts {}))) + ([db table cols values opts] + (insert-cols! db table cols values opts))) + +(defn- update-sql + "Given a table name, a map of columns to set, a optional map of columns to + match, and an entities, return a vector of the SQL for that update followed + by its parameters. Example: + (update :person {:zip 94540} [\"zip = ?\" 94546] identity) + returns: + [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]" + [table set-map [where & params] entities] + (let [ks (keys set-map) + vs (vals set-map)] + (cons (str "UPDATE " (table-str table entities) + " SET " (str/join + "," + (kv-sql ks vs entities " = NULL")) + (when where " WHERE ") + where) + (concat (remove nil? vs) params)))) + +(defn update! + "Given a database connection, a table name, a map of column values to set and a + where clause of columns to match, perform an update. The options may specify + how column names (in the set / match maps) should be transformed (default + 'as-is') and whether to run the update in a transaction (default true). + Example: + (update! db :person {:zip 94540} [\"zip = ?\" 94546]) + is equivalent to: + (execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])" + ([db table set-map where-clause] (update! db table set-map where-clause {})) + ([db table set-map where-clause opts] + (let [{:keys [entities] :as opts} + (merge {:entities identity :transaction? true} (when (map? db) db) opts)] + (execute! db (update-sql table set-map where-clause entities) opts)))) + +(defn create-table-ddl + "Given a table name and a vector of column specs, return the DDL string for + creating that table. Each column spec is, in turn, a vector of keywords or + strings that is converted to strings and concatenated with spaces to form + a single column description in DDL, e.g., + [:cost :int \"not null\"] + [:name \"varchar(32)\"] + The first element of a column spec is treated as a SQL entity (so if you + provide the :entities option, that will be used to transform it). The + remaining elements are left as-is when converting them to strings. + An options map may be provided that can contain: + :table-spec -- a string that is appended to the DDL -- and/or + :entities -- a function to specify how column names are transformed. + :conditional? -- either a boolean, indicating whether to add 'IF NOT EXISTS', + or a string, which is inserted literally before the table name, or a + function of two arguments (table name and the create statement), that can + manipulate the generated statement to better support other databases, e.g., + MS SQL Server which need to wrap create table in an existence query." + ([table specs] (create-table-ddl table specs {})) + ([table specs opts] + (let [table-spec (:table-spec opts) + conditional? (:conditional? opts) + entities (:entities opts identity) + table-name (as-sql-name entities table) + table-spec-str (or (and table-spec (str " " table-spec)) "") + spec-to-string (fn [spec] + (try + (str/join " " (cons (as-sql-name entities (first spec)) + (map name (rest spec)))) + (catch Exception _ + (throw (IllegalArgumentException. + "column spec is not a sequence of keywords / strings")))))] + (cond->> (format "CREATE TABLE%s %s (%s)%s" + (cond (or (nil? conditional?) + (instance? Boolean conditional?)) + (if conditional? " IF NOT EXISTS" "") + (fn? conditional?) + "" + :else + (str " " conditional?)) + table-name + (str/join ", " (map spec-to-string specs)) + table-spec-str) + (fn? conditional?) (conditional? table-name))))) + +(defn drop-table-ddl + "Given a table name, return the DDL string for dropping that table. + An options map may be provided that can contain: + :entities -- a function to specify how column names are transformed. + :conditional? -- either a boolean, indicating whether to add 'IF EXISTS', + or a string, which is inserted literally before the table name, or a + function of two arguments (table name and the create statement), that can + manipulate the generated statement to better support other databases, e.g., + MS SQL Server which need to wrap create table in an existence query." + ([table] (drop-table-ddl table {})) + ([table {:keys [entities conditional?] :or {entities identity}}] + (let [table-name (as-sql-name entities table)] + (cond->> (format "DROP TABLE%s %s" + (cond (or (nil? conditional?) + (instance? Boolean conditional?)) + (if conditional? " IF EXISTS" "") + (fn? conditional?) + "" + :else + (str " " conditional?)) + table-name) + (fn? conditional?) (conditional? table-name))))) From 0a040750a2cac392ec9455e18f9edea7a0ee83f1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 16:22:42 -0700 Subject: [PATCH 514/630] Various refactorings to improve query/reducible-query performance --- CHANGES.md | 1 + project.clj | 4 +- src/main/clojure/clojure/java/jdbc.clj | 311 +++++++++++------- .../clojure/clojure/java/test_utilities.clj | 23 +- 4 files changed, 208 insertions(+), 131 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 03a1ea99..5039260a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,7 @@ Changes coming in 0.7.4 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. +* Performance improvements to `query` and `reducible-query`. Changes in 0.7.3 diff --git a/project.clj b/project.clj index a7d7550a..9f857ccf 100644 --- a/project.clj +++ b/project.clj @@ -27,8 +27,8 @@ [org.postgresql/postgresql "9.4.1212.jre7"] [com.impossibl.pgjdbc-ng/pgjdbc-ng "0.7.1"] [org.xerial/sqlite-jdbc "3.16.1"] - ;; if you have the MS driver in your local repo - [sqljdbc4 "4.0"]] + ;; Assumes Java 8; there's a .jre7 version as well: + [com.microsoft.sqlserver/mssql-jdbc "6.2.2.jre8"]] :profiles {:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f2d0517c..10114ffd 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -379,24 +379,22 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] (throw (IllegalArgumentException. msg)))))) -(defn- make-name-unique - "Given a collection of column names and a new column name, - return the new column name made unique, if necessary, by - appending _N where N is some unique integer suffix." - [cols col-name n] - (let [suffixed-name (if (= n 1) col-name (str col-name "_" n))] - (if (apply distinct? suffixed-name cols) - suffixed-name - (recur cols col-name (inc n))))) - (defn- make-cols-unique - "Given a collection of column names, rename duplicates so - that the result is a collection of unique column names." - [cols] - (if (or (empty? cols) (apply distinct? cols)) - cols - (reduce (fn [unique-cols col-name] - (conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols))) + "A transducer that, given a collection of strings, returns a collection of + strings that have been made unique by appending _n to duplicates." + [xf] + (let [seen (volatile! {})] + (fn + ([] (xf)) + ([result] (xf result)) + ([result input] + (if-let [suffix (get @seen input)] + (do + (vswap! seen assoc input (inc suffix)) + (xf result (str input "_" suffix))) + (do + (vswap! seen assoc input 2) + (xf result input))))))) (defprotocol ISQLValue "Protocol for creating SQL values from Clojure values. Default @@ -462,6 +460,22 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} [^ResultSet rs rsmeta idxs] (mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs)) +(defn- make-identifier-fn + "Given the user's identifiers function, an optional namespace qualifier, and + a flag indicating whether to produce keywords or not, return a compound + function that will perform the appropriate entity to identifier conversion." + [identifiers qualifier keywordize?] + (cond (and qualifier (not keywordize?)) + (throw (IllegalArgumentException. + (str ":qualifier is not allowed unless " + ":keywordize? is true"))) + (and qualifier keywordize?) + (comp (partial keyword qualifier) identifiers) + keywordize? + (comp keyword identifiers) + :else + identifiers)) + (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it @@ -484,20 +498,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [rsmeta (.getMetaData rs) idxs (range 1 (inc (.getColumnCount rsmeta))) col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique) - identifier-fn (cond (and qualifier (not keywordize?)) - (throw (IllegalArgumentException. - (str ":qualifier is not allowed unless " - ":keywordize? is true"))) - (and qualifier keywordize?) - (comp (partial keyword qualifier) identifiers) - keywordize? - (comp keyword identifiers) - :else - identifiers) - keys (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - col-name-fn - (mapv identifier-fn)) + keys (into [] (comp (map (fn [^Integer i] (.getColumnLabel rsmeta i))) + col-name-fn + (map (make-identifier-fn identifiers + qualifier + keywordize?))) + idxs) row-values (fn [] (read-columns rs rsmeta idxs)) ;; This used to use create-struct (on keys) and then struct to populate each row. ;; That had the side effect of preserving the order of columns in each row. As @@ -963,6 +969,41 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (with-open [con (get-connection db opts)] (db-do-prepared (add-connection db con) transaction? sql-params opts)))))) +(defn- execute-query-with-params + "Given a prepared statement, a set of parameters, a parameter setting + function, and a function to process the result set, execute the query and + apply the processing function." + [^PreparedStatement stmt params set-parameters func] + (set-parameters stmt params) + (with-open [rset (.executeQuery stmt)] + (func rset))) + +(defn- db-query-with-resultset* + "Given a db-spec, a SQL statement (or a prepared statement), a set of + parameters, a result set processing function and options, execute the query." + [db sql params func opts] + (if (instance? PreparedStatement sql) + (let [^PreparedStatement stmt sql] + (execute-query-with-params + stmt + params + (:set-parameters opts dft-set-parameters) + func)) + (if-let [con (db-find-connection db)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (execute-query-with-params + stmt + params + (:set-parameters opts dft-set-parameters) + func)) + (with-open [con (get-connection db opts)] + (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] + (execute-query-with-params + stmt + params + (:set-parameters opts dft-set-parameters) + func)))))) + (defn db-query-with-resultset "Executes a query, then evaluates func passing in the raw ResultSet as an argument. The second argument is a vector containing either: @@ -974,11 +1015,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ([db sql-params func] (db-query-with-resultset db sql-params func {})) ([db sql-params func opts] (let [opts (merge (when (map? db) db) opts) - [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - run-query-with-params (^{:once true} fn* [^PreparedStatement stmt] - ((:set-parameters opts dft-set-parameters) stmt params) - (with-open [rset (.executeQuery stmt)] - (func rset)))] + [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (when-not (sql-stmt? sql) (let [^Class sql-class (class sql) ^String msg (format "\"%s\" expected %s %s, found %s %s" @@ -988,15 +1025,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (.getName sql-class) (pr-str sql))] (throw (IllegalArgumentException. msg)))) - (if (instance? PreparedStatement sql) - (let [^PreparedStatement stmt sql] - (run-query-with-params stmt)) - (if-let [con (db-find-connection db)] - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (run-query-with-params stmt)) - (with-open [con (get-connection db opts)] - (with-open [^PreparedStatement stmt (prepare-statement con sql opts)] - (run-query-with-params stmt)))))))) + (db-query-with-resultset* db sql params func opts)))) ;; top-level API for actual SQL operations @@ -1025,39 +1054,92 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (when (map? db) db) opts) result-set-fn (or result-set-fn (if as-arrays? vec doall)) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] - (when (and explain? (string? (first sql-params-vector))) + [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (when-not (sql-stmt? sql) + (let [^Class sql-class (class sql) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-class) + (pr-str sql))] + (throw (IllegalArgumentException. msg)))) + (when (and explain? (string? sql)) (query db (into [(str (if (string? explain?) explain? "EXPLAIN") " " - (first sql-params-vector))] - (rest sql-params-vector)) + sql)] + params) (-> opts (dissoc :explain? :result-set-fn :row-fn) (assoc :result-set-fn explain-fn)))) - (db-query-with-resultset db sql-params-vector - (^{:once true} fn* [rset] - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rset opts))) + (db-query-with-resultset* db sql params + (if as-arrays? + (^{:once true} fn* [rset] + ((^{:once true} fn* [rs] + (result-set-fn (cons (first rs) + (map row-fn (rest rs))))) + (result-set-seq rset opts))) + (^{:once true} fn* [rset] + (result-set-fn (map row-fn + (result-set-seq rset opts))))) opts)))) ;; performance notes -- goal is to lift as much logic as possible into a "once" ;; pass (so reducible-query preloads all the stuff that doesn't depend on the ;; query results, and then you can repeatedly reduce it, which runs the query ;; each time and runs the minimal result set reduction) -;; turn make-cols-unique into a transducer and optimize it -;; turn make-keys into a transducer pipeline and lift it -;; lift identifier-fn out as make-identifier-fn and refactor -;; lift init-reduce -;; refactor reducible-result-set to lift identifier-fn out -;; call new reducible-result-set version from reducible-query (after calling -;; make-identifier-fn etc) +;; done: turn make-cols-unique into a transducer and optimize it +;; done: turn make-keys into a transducer pipeline and lift it +;; done: lift identifier-fn out as make-identifier-fn and refactor +;; done: lift init-reduce +;; done: refactor reducible-result-set to lift identifier-fn out +;; done: call new reducible-result-set version from reducible-query (after calling +;; make-identifier-fn etc) ;; create an optimized version of db-query-with-resultset without :as-arrays? ;; and with options handling lifted +(defn- get-rs-columns + "Given a set of indices, a result set's metadata, and a function to convert + SQL entity names to Clojure column names, + return the unique vector of column names." + [idxs ^ResultSetMetaData rsmeta identifier-fn] + (into [] (comp (map (fn [^Integer i] (.getColumnLabel rsmeta i))) + make-cols-unique + (map identifier-fn)) + idxs)) + +(defn- init-reduce-rs + "Given a sequence of columns, a result set, its metadata, a sequence of + indices, a mapping function to apply, an initial value, and a function that + can read column data from the result set, reduce the result set and + return the result of that reduction." + [cols ^ResultSet rs rsmeta idxs f init read-columns] + (loop [init' init] + (if (.next rs) + (let [result (f init' (zipmap cols (read-columns rs rsmeta idxs)))] + (if (reduced? result) + @result + (recur result))) + init'))) + +(defn- reducible-result-set* + "Given a java.sql.ResultSet, indices, metadata, column names and a reader, + return a reducible collection. + Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce." + [^ResultSet rs idxs ^ResultSetMetaData rsmeta cols read-columns] + (reify clojure.lang.IReduce + (reduce [this f] + (if (.next rs) + ;; reduce init is first row of ResultSet + (init-reduce-rs cols rs rsmeta idxs f + (zipmap cols (read-columns rs rsmeta idxs)) + read-columns) + ;; no rows so call 0-arity f to get result value + ;; per reduce docstring contract + (f))) + (reduce [this f init] + (init-reduce-rs cols rs rsmeta idxs f init read-columns)))) + (defn reducible-result-set "Given a java.sql.ResultSet return a reducible collection. Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce @@ -1066,46 +1148,32 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} :or {identifiers str/lower-case keywordize? true read-columns dft-read-columns}}] - (let [identifier-fn (cond (and qualifier (not keywordize?)) - (throw (IllegalArgumentException. - (str ":qualifier is not allowed unless " - ":keywordize? is true"))) - (and qualifier keywordize?) - (comp (partial keyword qualifier) identifiers) - keywordize? - (comp keyword identifiers) - :else - identifiers) - make-keys (fn [idxs ^ResultSetMetaData rsmeta] - (->> idxs - (mapv (fn [^Integer i] (.getColumnLabel rsmeta i))) - (make-cols-unique) - (mapv identifier-fn))) - init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init] - (loop [init' init] - (if (.next rs) - (let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))] - (if (reduced? result) - @result - (recur result))) - init')))] - (reify clojure.lang.IReduce - (reduce [this f] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (make-keys idxs rsmeta)] - (if (.next rs) - ;; reduce init is first row of ResultSet - (init-reduce keys rs rsmeta idxs f - (zipmap keys (read-columns rs rsmeta idxs))) - ;; no rows so call 0-arity f to get result value - ;; per reduce docstring contract - (f)))) - (reduce [this f init] - (let [rsmeta (.getMetaData rs) - idxs (range 1 (inc (.getColumnCount rsmeta))) - keys (make-keys idxs rsmeta)] - (init-reduce keys rs rsmeta idxs f init)))))) + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + cols (get-rs-columns idxs rsmeta + (make-identifier-fn identifiers + qualifier + keywordize?))] + (reducible-result-set* rs idxs rsmeta cols read-columns))) + +(defn- query-reducer + "Given options, return a function of f that accepts a result set and reduces + it using f." + [identifiers keywordize? qualifier read-columns] + (let [identifier-fn (make-identifier-fn identifiers qualifier keywordize?)] + (fn + ([f] + (^{:once true} fn* [^ResultSet rs] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + cols (get-rs-columns idxs rsmeta identifier-fn)] + (reduce f (reducible-result-set* rs idxs rsmeta cols read-columns))))) + ([f init] + (^{:once true} fn* [^ResultSet rs] + (let [rsmeta (.getMetaData rs) + idxs (range 1 (inc (.getColumnCount rsmeta))) + cols (get-rs-columns idxs rsmeta identifier-fn)] + (reduce f init (reducible-result-set* rs idxs rsmeta cols read-columns)))))))) (defn reducible-query "Given a database connection, a vector containing SQL and optional parameters, @@ -1118,23 +1186,32 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} See also prepare-statement for additional options." ([db sql-params] (reducible-query db sql-params {})) ([db sql-params opts] - (let [opts (merge {:identifiers str/lower-case :keywordize? true - :read-columns dft-read-columns} - (when (map? db) db) - opts) - sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] + (let [{:keys [identifiers keywordize? qualifier read-columns] :as opts} + (merge {:identifiers str/lower-case :keywordize? true + :read-columns dft-read-columns} + (when (map? db) db) + opts) + [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) + reducing-fn (query-reducer identifiers keywordize? qualifier read-columns)] + (when-not (sql-stmt? sql) + (let [^Class sql-class (class sql) + ^String msg (format "\"%s\" expected %s %s, found %s %s" + "sql-params" + "vector" + "[sql param*]" + (.getName sql-class) + (pr-str sql))] + (throw (IllegalArgumentException. msg)))) (reify clojure.lang.IReduce (reduce [this f] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f (reducible-result-set rset opts))) + (db-query-with-resultset* + db sql params + (reducing-fn f) opts)) (reduce [this f init] - (db-query-with-resultset - db sql-params-vector - (^{:once true} fn* [rset] - (reduce f init (reducible-result-set rset opts))) + (db-query-with-resultset* + db sql params + (reducing-fn f init) opts)))))) (defn- direction diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/test_utilities.clj index faf2015c..02d7ba27 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/test_utilities.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2016 Sean Corfield, Stephen C. Gilardi. +;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. ;; All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can @@ -41,19 +41,18 @@ (is (re-find (pattern "Message: Test Message.*Message: Base Message") except-str)) (is (re-find (pattern "SQLState: Test State.*SQLState: Base State") except-str))))) -(deftest test-make-name-unique - (let [make-name-unique @#'sql/make-name-unique] - (is (= "a" (make-name-unique '() "a" 1))) - (is (= "a_2" (make-name-unique '("a") "a" 1))) - (is (= "a_3" (make-name-unique '("a" "b" "a_2") "a" 1))))) - (deftest test-make-cols-unique (let [make-cols-unique @#'sql/make-cols-unique] - (is (= '() (make-cols-unique '()))) - (is (= '("a") (make-cols-unique '("a")))) - (is (= '("a" "a_2") (make-cols-unique '("a" "a")))) - (is (= '("a" "b" "a_2" "a_3") (make-cols-unique '("a" "b" "a" "a")))) - (is (= '("a" "b" "a_2" "b_2" "a_3" "b_3") (make-cols-unique '("a" "b" "a" "b" "a" "b")))))) + (is (= [] + (into [] make-cols-unique []))) + (is (= ["a"] + (into [] make-cols-unique ["a"]))) + (is (= ["a" "a_2"] + (into [] make-cols-unique ["a" "a"]))) + (is (= ["a" "b" "a_2" "a_3"] + (into [] make-cols-unique ["a" "b" "a" "a"]))) + (is (= ["a" "b" "a_2" "b_2" "a_3" "b_3"] + (into [] make-cols-unique ["a" "b" "a" "b" "a" "b"]))))) ;; DDL tests From e4af62abc4f8c39eaf76a414d615634f5ca9d67b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 17:14:02 -0700 Subject: [PATCH 515/630] Improve performance of dft-set-parameters --- src/main/clojure/clojure/java/jdbc.clj | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 10114ffd..9ec08b4b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -432,9 +432,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn- dft-set-parameters "Default implementation of parameter setting for the given statement." [stmt params] - (dorun (map-indexed (fn [ix value] - (set-parameter value stmt (inc ix))) - params))) + (loop [ix 1 values params] + (when (seq values) + (set-parameter (first values) stmt ix) + (recur (inc ix) (rest values))))) (defprotocol IResultSetReadColumn "Protocol for reading objects from the java.sql.ResultSet. Default From 5f1a5eeb54d8e8f06c9e36ba53f2036eb128c94d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 18:25:14 -0700 Subject: [PATCH 516/630] Experimental support for :raw? result set in reducible-query --- src/main/clojure/clojure/java/jdbc.clj | 57 ++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 9ec08b4b..f7e43f41 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1158,8 +1158,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (reducible-result-set* rs idxs rsmeta cols read-columns))) (defn- query-reducer - "Given options, return a function of f that accepts a result set and reduces - it using f." + "Given options, return a function of f (or f and init) that accepts a + result set and reduces it using f." [identifiers keywordize? qualifier read-columns] (let [identifier-fn (make-identifier-fn identifiers qualifier keywordize?)] (fn @@ -1176,6 +1176,55 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} cols (get-rs-columns idxs rsmeta identifier-fn)] (reduce f init (reducible-result-set* rs idxs rsmeta cols read-columns)))))))) +(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 + this wrapper so operations need to be eager (and fairly limited). + Supports ILookup (keywords are treated as strings). + Supports Associative for lookup only (again, keywords are treated as strings). + Later we may realize a new hash map when assoc (and other, future, operations + are performed on the result set row)." + [^ResultSet rs] + (reify + clojure.lang.ILookup + (valAt [this k] + (try + (.getObject rs (name k)) + (catch SQLException _))) + (valAt [this k not-found] + (try + (.getObject rs (name k)) + (catch SQLException _ + not-found))) + clojure.lang.Associative + (containsKey [this k] + (try + (.getObject rs (name k)) + true + (catch SQLException _ + false))) + (entryAt [this k] + (try + (clojure.lang.MapEntry/create k (.getObject rs (name k))) + (catch SQLException _))) + (assoc [this _ _] + (throw (ex-info "assoc not supported on raw result set" {}))))) + +(defn- raw-query-reducer + "Given a function f and an initial value, return a function that accepts a + result set and reduces it using no translation. The result set is extended + to support ILookup only." + [f init] + (^{:once true} fn* [^ResultSet rs] + (let [rs-map (mapify-result-set rs)] + (loop [init' init] + (if (.next rs) + (let [result (f init' rs-map)] + (if (reduced? result) + @result + (recur result))) + init'))))) + (defn reducible-query "Given a database connection, a vector containing SQL and optional parameters, return a reducible collection. When reduced, it will start the database query @@ -1193,7 +1242,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (when (map? db) db) opts) [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params)) - reducing-fn (query-reducer identifiers keywordize? qualifier read-columns)] + reducing-fn (if (:raw? opts) + raw-query-reducer + (query-reducer identifiers keywordize? qualifier read-columns))] (when-not (sql-stmt? sql) (let [^Class sql-class (class sql) ^String msg (format "\"%s\" expected %s %s, found %s %s" From 1dd511aea3675d40e0e42a64d2997309bf5d1958 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 18:43:13 -0700 Subject: [PATCH 517/630] Clean up comments / docstrings --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 14 +++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 5039260a..2f054b0e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,7 @@ Changes coming in 0.7.4 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. * Performance improvements to `query` and `reducible-query`. +* Experimental `:raw?` result set handling in `reducible-query`. Changes in 0.7.3 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index f7e43f41..5a3f8255 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1213,7 +1213,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn- raw-query-reducer "Given a function f and an initial value, return a function that accepts a result set and reduces it using no translation. The result set is extended - to support ILookup only." + to support ILookup and the readonly parts of Associative only." [f init] (^{:once true} fn* [^ResultSet rs] (let [rs-map (mapify-result-set rs)] @@ -1230,10 +1230,18 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} return a reducible collection. When reduced, it will start the database query and reduce the result set, and then close the connection: (transduce (map :cost) + (reducible-query db sql-params)) - Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce + The following options from query etc are not accepted here: :as-arrays? :explain :explain-fn :result-set-fn :row-fn - See also prepare-statement for additional options." + See prepare-statement for additional options that may be passed through. + + If :raw? true is specified, the rows of the result set are not converted to + hash maps, and it as if the following options were specified: + :identifiers identity :keywordize? false :qualifier nil + In addition, the rows of the result set may only be read as if they were hash + maps (get, keyword lookup, select-keys) but the sequence representation is + not available (so, no keys, no vals, and no seq calls). This is much faster + than converting each row to a hash map but it is also more restrictive." ([db sql-params] (reducible-query db sql-params {})) ([db sql-params opts] (let [{:keys [identifiers keywordize? qualifier read-columns] :as opts} From 01b6fd13fd98917e7db73c187cfdcde599df2b1e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 19:17:15 -0700 Subject: [PATCH 518/630] Clojure 1.7 compatibility: clojure.lang.MapEntry/create did not exist then --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5a3f8255..e8140685 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1205,7 +1205,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} false))) (entryAt [this k] (try - (clojure.lang.MapEntry/create k (.getObject rs (name k))) + (clojure.lang.MapEntry. k (.getObject rs (name k))) (catch SQLException _))) (assoc [this _ _] (throw (ex-info "assoc not supported on raw result set" {}))))) From 4a62e2819401925f61ecce58ae47dd75579f4607 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 19 Oct 2017 19:17:35 -0700 Subject: [PATCH 519/630] Ensure a few tests on :raw? result sets --- src/test/clojure/clojure/java/test_jdbc.clj | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index eb35b68f..c3d3fd8b 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -445,7 +445,7 @@ ;; reduce with init (and ensure we can pass :fetch-size & connection opts through) (is (= 466 (reduce (fn [n r] (+ n (:cost r))) 100 (sql/reducible-query db "SELECT * FROM fruit" - (cond-> {:fetch-size 100} + (cond-> {:fetch-size 100 :raw? true} (not (sqlite? db)) (assoc :read-only? true) (not (derby? db)) @@ -494,7 +494,8 @@ (into [] (map :cost) (sql/reducible-query db (str "SELECT * FROM fruit" - " ORDER BY cost"))))) + " ORDER BY cost") + {:raw? true})))) ;; transduce without init (calls (+) to get init value) (is (= 366 (transduce (map :cost) + (sql/reducible-query db "SELECT * FROM fruit")))) From 99a3d6611f973ff47597f4c7df3c36237ab4bde3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 20 Oct 2017 09:28:45 -0700 Subject: [PATCH 520/630] Add Tommi Reiman's benchmarks, clean up comments --- CHANGES.md | 2 +- project.clj | 11 +- src/main/clojure/clojure/java/jdbc.clj | 14 -- src/perf/clojure/clojure/java/perf_jdbc.clj | 226 ++++++++++++++++++++ 4 files changed, 235 insertions(+), 18 deletions(-) create mode 100644 src/perf/clojure/clojure/java/perf_jdbc.clj diff --git a/CHANGES.md b/CHANGES.md index 2f054b0e..12170b57 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,7 +2,7 @@ Changes coming in 0.7.4 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. -* Performance improvements to `query` and `reducible-query`. +* Performance improvements, primarily in `query` and `reducible-query`. * Experimental `:raw?` result set handling in `reducible-query`. Changes in 0.7.3 diff --git a/project.clj b/project.clj index 9f857ccf..1952153f 100644 --- a/project.clj +++ b/project.clj @@ -33,10 +33,15 @@ :profiles {:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} - :dev {:dependencies [[org.clojure/test.check "0.9.0"]]}} - + :dev {:dependencies [[org.clojure/test.check "0.9.0"] + [criterium "0.4.4"]]} + :perf {:test-paths ["src/perf/clojure"] + :jvm-opts ^:replace ["-server" + "-Xmx4096m" + "-Dclojure.compiler.direct-linking=true"]}} :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/" "ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"} ;; include dev profile with 1.9 to pull in test.check - :aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"]} + :aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"] + "perf" ["with-profile" "default,dev,perf"]} :min-lein-version "2.0.0") diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e8140685..770f35f7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1085,20 +1085,6 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (result-set-seq rset opts))))) opts)))) -;; performance notes -- goal is to lift as much logic as possible into a "once" -;; pass (so reducible-query preloads all the stuff that doesn't depend on the -;; query results, and then you can repeatedly reduce it, which runs the query -;; each time and runs the minimal result set reduction) -;; done: turn make-cols-unique into a transducer and optimize it -;; done: turn make-keys into a transducer pipeline and lift it -;; done: lift identifier-fn out as make-identifier-fn and refactor -;; done: lift init-reduce -;; done: refactor reducible-result-set to lift identifier-fn out -;; done: call new reducible-result-set version from reducible-query (after calling -;; make-identifier-fn etc) -;; create an optimized version of db-query-with-resultset without :as-arrays? -;; and with options handling lifted - (defn- get-rs-columns "Given a set of indices, a result set's metadata, and a function to convert SQL entity names to Clojure column names, diff --git a/src/perf/clojure/clojure/java/perf_jdbc.clj b/src/perf/clojure/clojure/java/perf_jdbc.clj new file mode 100644 index 00000000..3554ed12 --- /dev/null +++ b/src/perf/clojure/clojure/java/perf_jdbc.clj @@ -0,0 +1,226 @@ +;; Copyright (c) 2017 Tommmi Reiman, Sean Corfield. All rights reserved. +;; The use and distribution terms for this software are covered by +;; the Eclipse Public License 1.0 +;; (http://opensource.org/licenses/eclipse-1.0.php) which can be +;; found in the file epl-v10.html at the root of this distribution. +;; By using this software in any fashion, you are agreeing to be +;; bound by the terms of this license. You must not remove this +;; notice, or any other, from this software. + +(ns clojure.java.perf-jdbc + "Performance tests for parts of clojure.java.jdbc. + + Start a REPL with `lein perf repl` + Require this namespace and then run `(calibrate)` + followed by `(test-dummy)` and `(test-h2)` + + These test compare the raw performance (against an in-memory H2 database) + for hand-crafted Java JDBC calls and various `query` and `reducible-query` + calls." + (:require [criterium.core :as cc] + [clojure.java.jdbc :as sql]) + (:import (java.sql Connection PreparedStatement ResultSet Statement ResultSetMetaData))) + +(defn calibrate [] + ;; 840ms + (cc/quick-bench (reduce + (take 10e6 (range))))) + +(def db + "Note: loading this namespace creates a connection to the H2 database!" + {:connection (sql/get-connection "jdbc:h2:mem:test_mem")}) + +(defn create-table! [db] + (sql/db-do-commands + db (sql/create-table-ddl + :fruit + [[:id :int "DEFAULT 0"] + [:name "VARCHAR(32)" "PRIMARY KEY"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real]] + {:table-spec ""}))) + +(defn- drop-table! [db] + (doseq [table [:fruit :fruit2 :veggies :veggies2]] + (try + (sql/db-do-commands db (sql/drop-table-ddl table)) + (catch java.sql.SQLException _)))) + +(defn add-stuff! [db] + (sql/insert-multi! db + :fruit + nil + [[1 "Apple" "red" 59 87] + [2 "Banana" "yellow" 29 92.2] + [3 "Peach" "fuzzy" 139 90.0] + [4 "Orange" "juicy" 89 88.6]])) + +(def dummy-con + (reify + Connection + (createStatement [_] + (reify + Statement + (addBatch [_ _]))) + (prepareStatement [_ _] + (reify + PreparedStatement + (setObject [_ _ _]) + (setString [_ _ _]) + (close [_]) + (executeQuery [_] + (reify + ResultSet + (getMetaData [_] + (reify + ResultSetMetaData + (getColumnCount [_] 1) + (getColumnLabel [_ _] "name"))) + (next [_] true) + (close [_]) + (^Object getObject [_ ^int s] + "Apple") + (^Object getObject [_ ^String s] + "Apple") + (^String getString [_ ^String s] + "Apple"))))))) + +(defn select [db] + (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:row-fn :name :result-set-fn first})) + +(defn select-p [db ps] + (sql/query db [ps "red"] + {:row-fn :name :result-set-fn first})) + +(defn select* [^Connection con] + (let [ps (doto (.prepareStatement con "SELECT * FROM fruit WHERE appearance = ?") + (.setObject 1 "red")) + rs (.executeQuery ps) + _ (.next rs) + value (.getObject rs "name")] + (.close ps) + value)) + +(defn test-dummy [] + (do + (let [db {:connection dummy-con}] + (assert (= "Apple" (select db))) + ;(time (dotimes [_ 100000] (select db))) + + ; 3.029268 ms (3030 ns) + (cc/quick-bench (dotimes [_ 1000] (select db)))) + + (let [con dummy-con] + (assert (= "Apple" (select* con))) + ;(time (dotimes [_ 100000] (select* con))) + + ; 716.661522 ns (0.7ns) -> 4300x faster + (cc/quick-bench (dotimes [_ 1000] (select* con)))))) + +(defn test-h2 [] + (do + (drop-table! db) + (create-table! db) + (add-stuff! db) + + (println "Basic select...") + (let [db db] + (assert (= "Apple" (select db))) + (cc/quick-bench (select db))) + + (println "Select with prepared statement...") + (let [con (:connection db)] + (with-open [ps (sql/prepare-statement con "SELECT * FROM fruit WHERE appearance = ?")] + (assert (= "Apple" (select-p db ps))) + (cc/quick-bench (select db)))) + + (println "Reducible query...") + (let [db db + rq (sql/reducible-query db ["SELECT * FROM fruit WHERE appearance = ?" "red"])] + (assert (= "Apple" (reduce (fn [_ row] (reduced (:name row))) + nil rq))) + (cc/quick-bench (reduce (fn [_ row] (reduced (:name row))) + nil rq))) + + (println "Reducible query with prepared statement...") + (let [con (:connection db)] + (with-open [ps (sql/prepare-statement con "SELECT * FROM fruit WHERE appearance = ?")] + (let [rq (sql/reducible-query db [ps "red"])] + (assert (= "Apple" (reduce (fn [_ row] (reduced (:name row))) + nil rq))) + (cc/quick-bench (reduce (fn [_ row] (reduced (:name row))) + nil rq))))) + + (println "Reducible query with prepared statement and simple identifiers...") + (let [con (:connection db)] + (with-open [ps (sql/prepare-statement con "SELECT * FROM fruit WHERE appearance = ?")] + (let [rq (sql/reducible-query db [ps "red"] + {:keywordize? false :identifiers identity})] + (assert (= "Apple" (reduce (fn [_ row] (reduced (get row "NAME"))) + nil rq))) + (cc/quick-bench (reduce (fn [_ row] (reduced (get row "NAME"))) + nil rq))))) + + (println "Reducible query with prepared statement and raw result set...") + (let [con (:connection db)] + (with-open [ps (sql/prepare-statement con "SELECT * FROM fruit WHERE appearance = ?")] + (let [rq (sql/reducible-query db [ps "red"] {:raw? true})] + (assert (= "Apple" (reduce (fn [_ row] (reduced (:name row))) + nil rq))) + (cc/quick-bench (reduce (fn [_ row] (reduced (:name row))) + nil rq))))) + + (println "Reducible query with raw result set...") + (let [db db + rq (sql/reducible-query + db + ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:raw? true})] + (assert (= "Apple" (reduce (fn [_ row] (reduced (:name row))) + nil rq))) + (cc/quick-bench (reduce (fn [_ row] (reduced (:name row))) + nil rq))) + + (println "Repeated reducible query with raw result set...") + (let [db db] + (assert (= "Apple" (reduce (fn [_ row] (reduced (:name row))) + nil (sql/reducible-query + db + ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:raw? true})))) + (cc/quick-bench (reduce (fn [_ row] (reduced (:name row))) + nil (sql/reducible-query + db + ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:raw? true})))) + + (println "Raw Java...") + (let [con (:connection db)] + (assert (= "Apple" (select* con))) + (cc/quick-bench (select* con))))) + +(comment + (calibrate) + (test-dummy) + (test-h2) + ;; The following are just some things I was double-checking while adding + ;; to Tommi's original tests -- Sean. + ;; Shows the row is a reify instance, but you can select by key: + (reduce (fn [_ row] (println row) (reduced (:name row))) + nil (sql/reducible-query + db + ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:raw? true})) + ;; Shows you can construct a map result using select-keys: + (reduce (fn [_ row] (reduced (select-keys row [:cost]))) + nil (sql/reducible-query + db + ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:raw? true})) + ;; Shows you can reconstruct an entire result set (with very little overhead): + (transduce (map #(select-keys % [:id :name :cost :appearance :grade])) + conj [] (sql/reducible-query + db + "SELECT * FROM fruit" + {:raw? true}))) From 183288ba692fbd62ba736c7b1280397dc718dc70 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 20 Oct 2017 10:22:24 -0700 Subject: [PATCH 521/630] Clean up readme to match SQL Server in project.clj --- README.md | 8 +------- project.clj | 2 +- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3bcdb532..4a36de70 100644 --- a/README.md +++ b/README.md @@ -50,19 +50,13 @@ You will also need to add dependencies for the JDBC driver you intend to use. He * [H2](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.h2database%22%20AND%20a%3A%22h2%22) * [HSQLDB](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22hsqldb%22%20AND%20a%3A%22hsqldb%22) * [Microsoft SQL Server jTDS](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.jtds%22%20AND%20a%3A%22jtds%22) +* [Microsoft SQL Server -- Official MS Version](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.microsoft.sqlserver%22%20AND%20a%3A%22mssql-jdbc%22) * [MySQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22mysql%22%20AND%20a%3A%22mysql-connector-java%22) * [PostgreSQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.postgresql%22%20AND%20a%3A%22postgresql%22) * [SQLite](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.xerial%22%20AND%20a%3A%22sqlite-jdbc%22) Note: different versions of various database drivers have different Java/JVM version requirements. In particular, recent versions of Apache Derby require at least Java 8 and recent versions of H2 require at least Java 7. Clojure's Continuous Integration system uses older versions so tests can be run on Java 6 (see `pom.xml`); local testing is done with more recent versions on Java 8. -`clojure.java.jdbc` is also tested against Microsoft's own JDBC4 Driver 4.0 but that -has to be [downloaded manually](https://www.microsoft.com/en-us/download/details.aspx?id=11774) and placed in a Maven repository accessible to your system. For testing, it was installed locally as: -```clojure -;; Microsoft SQL Server JDBC4 Driver 4.0 -[sqljdbc4/sqljdbc4 "4.0"] -``` - Example Usage ======================================== ```clojure diff --git a/project.clj b/project.clj index 1952153f..0310dc68 100644 --- a/project.clj +++ b/project.clj @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-beta1"] + :dependencies [[org.clojure/clojure "1.9.0-beta2"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj From 1e856a7a8fd1cc50950012cf7562e3c0368bdc3d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 7 Dec 2017 12:42:32 -0800 Subject: [PATCH 522/630] JDBC-164 fix typos in docstrings (Stuart Hinson) --- src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 770f35f7..1f03a424 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -855,7 +855,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn db-do-commands "Executes SQL commands on the specified database connection. Wraps the commands - in a transaction if transaction? is true. transaction? can be ommitted and it + in a transaction if transaction? is true. transaction? can be omitted and it defaults to true. Accepts a single SQL command (string) or a vector of them. Uses executeBatch. This may affect what SQL you can run via db-do-commands." ([db sql-commands] @@ -907,7 +907,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn db-do-prepared-return-keys "Executes an (optionally parameterized) SQL prepared statement on the open database connection. The param-group is a seq of values for all of - the parameters. transaction? can be ommitted and will default to true. + the parameters. transaction? can be omitted and will default to true. Return the generated keys for the (single) update/insert. A PreparedStatement may be passed in, instead of a SQL string, in which case :return-keys MUST BE SET on that PreparedStatement!" From 878a5e0593a21d4adb442f3f0b107a3ea2208f13 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 14 Dec 2017 15:11:21 -0800 Subject: [PATCH 523/630] Address reports of NPE while trying to make a connection read only This may be a problem introduced by allowing get-connection to respect :read-only? and that being passed through db-transaction* (which can call get-connection). Added nil checks, and casts to Boolean, to make modify-connection more robust. --- CHANGES.md | 3 ++- README.md | 13 ++++++++++--- project.clj | 2 +- src/main/clojure/clojure/java/jdbc.clj | 11 ++++++----- 4 files changed, 19 insertions(+), 10 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 12170b57..6c4ae644 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,9 +1,10 @@ -Changes coming in 0.7.4 +Changes in 0.7.4 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. * Performance improvements, primarily in `query` and `reducible-query`. * Experimental `:raw?` result set handling in `reducible-query`. +* `modify-connection` is more robust in the face of `null` connections and bad option values. Changes in 0.7.3 diff --git a/README.md b/README.md index 4a36de70..41d04ce2 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.3 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.4 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -32,14 +32,14 @@ Latest stable release: 0.7.3 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.3"] +[org.clojure/java.jdbc "0.7.4"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.3 + 0.7.4 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -136,6 +136,13 @@ Developer Information Change Log ==================== +* Release 0.7.4 on 2017-12-14 + * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). + * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. + * Performance improvements, primarily in `query` and `reducible-query`. + * Experimental `:raw?` result set handling in `reducible-query`. + * `modify-connection` is more robust in the face of `null` connections and bad option values. + * Release 0.7.3 on 2017-10-05 * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). * If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). diff --git a/project.clj b/project.clj index 0310dc68..4471e6b0 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.7.4-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.7.5-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 1f03a424..520da4b6 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -217,10 +217,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} as specified by the options." ^java.sql.Connection [^java.sql.Connection connection opts] - (when (contains? opts :auto-commit?) - (.setAutoCommit connection (:auto-commit? opts))) - (when (contains? opts :read-only?) - (.setReadOnly connection (:read-only? opts))) + (when (and connection (contains? opts :auto-commit?)) + (.setAutoCommit connection (boolean (:auto-commit? opts)))) + (when (and connection (contains? opts :read-only?)) + (.setReadOnly connection (boolean (:read-only? opts)))) connection) (defn get-connection @@ -771,7 +771,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (try (.setReadOnly con old-readonly) (catch Exception _))))))) - (with-open [con (get-connection db opts)] + ;; avoid confusion of read-only? TX and read-only? connection: + (with-open [con (get-connection db (dissoc opts :read-only?))] (db-transaction* (add-connection db con) func opts))) (do (when (and isolation From 613874c761b597075b684f4215d6c0739ee6e1aa Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 14 Dec 2017 17:13:41 -0600 Subject: [PATCH 524/630] [maven-release-plugin] prepare release java.jdbc-0.7.4 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 16727262..0a49d84a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.4-SNAPSHOT + 0.7.4 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.4 From b2cc14a82e5e36e394169ba3404c5f247f8e1ba6 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 14 Dec 2017 17:13:41 -0600 Subject: [PATCH 525/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0a49d84a..3425d8fc 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.4 + 0.7.5-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.4 + HEAD From 5bdd1c03e049305bdb68925ec04e5c2eed2ec148 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 29 Dec 2017 11:56:27 -0800 Subject: [PATCH 526/630] JDBC-163 add :return-keys support to execute! Also adds :multi? support to db-do-prepared-return-keys. Note: not all database drivers allow executeBatch to return keys! --- CHANGES.md | 4 ++ README.md | 9 ++- project.clj | 15 ++--- src/main/clojure/clojure/java/jdbc.clj | 38 ++++++++++--- src/main/clojure/clojure/java/jdbc/spec.clj | 6 +- src/test/clojure/clojure/java/test_jdbc.clj | 63 +++++++++++++++++++-- 6 files changed, 110 insertions(+), 25 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 6c4ae644..420b9022 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.7.5 + +* Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://dev.clojure.org/jira/browse/JDBC-163). + Changes in 0.7.4 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). diff --git a/README.md b/README.md index 41d04ce2..21fd181b 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.4 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.5 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -32,14 +32,14 @@ Latest stable release: 0.7.4 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.4"] +[org.clojure/java.jdbc "0.7.5"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.4 + 0.7.5 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -136,6 +136,9 @@ Developer Information Change Log ==================== +* Release 0.7.5 on 2017-12-29 + * Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://dev.clojure.org/jira/browse/JDBC-163). + * Release 0.7.4 on 2017-12-14 * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. diff --git a/project.clj b/project.clj index 4471e6b0..c25fcaa8 100644 --- a/project.clj +++ b/project.clj @@ -2,7 +2,7 @@ ;; develop and test java.jdbc locally. The pom.xml file is the ;; "system of record" as far as the project version is concerned. -(defproject org.clojure/java.jdbc "0.7.5-SNAPSHOT" +(defproject org.clojure/java.jdbc "0.7.6-SNAPSHOT" :description "A low-level Clojure wrapper for JDBC-based access to databases." :parent [org.clojure/pom.contrib "0.1.2"] :url "https://github.com/clojure/java.jdbc" @@ -10,7 +10,7 @@ :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0-beta2"] + :dependencies [[org.clojure/clojure "1.9.0"] ;; These are just the versions most recently test against ;; for your own projects, use whatever version is most ;; appropriate for you. Again, note that this project.clj @@ -32,16 +32,17 @@ :profiles {:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} - :1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]} + :master {:dependencies [[org.clojure/clojure "1.10.0-master-SNAPSHOT"]]} :dev {:dependencies [[org.clojure/test.check "0.9.0"] [criterium "0.4.4"]]} :perf {:test-paths ["src/perf/clojure"] :jvm-opts ^:replace ["-server" "-Xmx4096m" "-Dclojure.compiler.direct-linking=true"]}} - :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/" - "ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"} - ;; include dev profile with 1.9 to pull in test.check - :aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"] + :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} + ;; include dev profile with 1.9+ to pull in test.check + :aliases {"test-all" ["with-profile" + "dev,test,master:dev,test:test,1.8:test,1.7" + "test"] "perf" ["with-profile" "default,dev,perf"]} :min-lein-version "2.0.0") diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 520da4b6..cdb4c3a8 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -877,15 +877,24 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn- db-do-execute-prepared-return-keys "Executes a PreparedStatement, optionally in a transaction, and (attempts to) - return any generated keys." + return any generated keys. + + Supports :multi? which causes a full result set sequence of keys to be + returned, and assumes the param-group is a sequence of parameter lists, + rather than a single sequence of parameters." [db ^PreparedStatement stmt param-group opts] - (let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts) + (let [{:keys [transaction? multi?] :as opts} (merge (when (map? db) db) opts) exec-and-return-keys (^{:once true} fn* [] - (let [counts (.executeUpdate stmt)] + (let [counts (if multi? + (.executeBatch stmt) + (.executeUpdate stmt))] (try (let [rs (.getGeneratedKeys stmt) - result (first (result-set-seq rs opts))] + rss (result-set-seq rs opts) + result (if multi? + (doall rss) + (first rss))] ;; sqlite (and maybe others?) requires ;; record set to be closed (.close rs) @@ -893,7 +902,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (catch Exception _ ;; assume generated keys is unsupported and return counts instead: counts))))] - ((:set-parameters opts dft-set-parameters) stmt param-group) + (if multi? + (doseq [params param-group] + ((:set-parameters opts dft-set-parameters) stmt params) + (.addBatch stmt)) + ((:set-parameters opts dft-set-parameters) stmt param-group)) (if transaction? (with-db-transaction [t-db (add-connection db (.getConnection stmt))] (exec-and-return-keys)) @@ -1324,20 +1337,31 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn execute! "Given a database connection and a vector containing SQL (or PreparedStatement) followed by optional parameters, perform a general (non-select) SQL operation. + The :transaction? option specifies whether to run the operation in a transaction or not (default true). + If the :multi? option is false (the default), the SQL statement should be followed by the parameters for that statement. + If the :multi? option is true, the SQL statement should be followed by one or more vectors of parameters, one for each application of the SQL statement. + + If :return-keys is provided, db-do-prepared-return-keys will be called + instead of db-do-prepared, and the result will be a sequence of maps + containing the generated keys. + If there are no parameters specified, executeUpdate will be used, otherwise executeBatch will be used. This may affect what SQL you can run via execute!" ([db sql-params] (execute! db sql-params {})) ([db sql-params opts] - (let [{:keys [transaction?] :as opts} + (let [{:keys [transaction? return-keys] :as opts} (merge {:transaction? true :multi? false} (when (map? db) db) opts) + db-do-helper (if return-keys + db-do-prepared-return-keys + db-do-prepared) execute-helper (^{:once true} fn* [db] - (db-do-prepared db transaction? sql-params opts))] + (db-do-helper db transaction? sql-params opts))] (if-let [con (db-find-connection db)] (execute-helper db) (with-open [con (get-connection db opts)] diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 2b512d97..9a4dfb03 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -161,7 +161,8 @@ (s/def ::exec-sql-options (s/keys :req-un [] :opt-un [::entities ::transaction?])) -(s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?])) +(s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi? + ::return-keys])) (s/def ::find-by-keys-options (s/keys :req-un [] :opt-un [::entities ::order-by @@ -358,7 +359,8 @@ :args (s/cat :db ::db-spec :sql-params ::sql-params :opts (s/? ::execute-options)) - :ret ::execute-result) + :ret (s/or :rows ::execute-result + :keys (s/coll-of map?))) (s/fdef sql/delete! :args (s/cat :db ::db-spec diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index c3d3fd8b..1130be3b 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -1,9 +1,9 @@ -;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and -;; distribution terms for this software are covered by the Eclipse Public -;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can -;; be found in the file epl-v10.html at the root of this distribution. By +;; Copyright (c) Stephen C. Gilardi, Sean Corfield. All rights reserved. +;; The use and distribution terms for this software are covered by the Eclipse +;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which +;; can be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the -;; terms of this license. You must not remove this notice, or any other, +;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; test_jdbc.clj @@ -382,7 +382,7 @@ (deftest test-do-prepared1e (doseq [db (test-specs)] ;; Derby/SQL Server does not have auto-generated id column which we're testing here - (when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (when-not (#{"derby" "jtds" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) (create-test-table :fruit db) (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" @@ -893,6 +893,57 @@ (create-test-table :fruit db) (is (= [] (sql/query db "SELECT * FROM fruit"))))) +(deftest insert-one-via-execute + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-key ((select-key db) + (sql/execute! db [(str "INSERT INTO fruit ( name )" + " VALUES ( ? )") + "Apple"] + {:return-keys true}))] + (is (= (returned-key db 1) new-key))))) + +(deftest insert-two-via-execute + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [execute-multi-insert + (fn [db] + (sql/execute! db [(str "INSERT INTO fruit ( name )" + " VALUES ( ? )") + ["Apple"] + ["Orange"]] + {:return-keys true + :multi? true})) + new-keys (map (select-key db) + (if (#{"jtds" "jtds:sqlserver"} + (or (:subprotocol db) (:dbtype db))) + (do + (is (thrown? java.sql.BatchUpdateException + (execute-multi-insert db))) + []) + (execute-multi-insert db)))] + (case (or (:subprotocol db) (:dbtype db)) + ;; SQLite only returns the last key inserted in a batch + "sqlite" (is (= [(returned-key db 2)] new-keys)) + ;; Derby returns a single row count + "derby" (is (= [(returned-key db 1)] new-keys)) + ;; H2 returns nothing useful + "h2" (is (= [] new-keys)) + ;; HSQL returns nothing useful + "hsql" (is (= [] new-keys)) + ;; MS SQL returns row counts + "mssql" (is (= [1 1] new-keys)) + ;; jTDS disallows batch updates returning keys (handled above) + ("jtds" "jtds:sqlserver") + (is (= [] new-keys)) + ;; otherwise expect two rows with the correct keys + (do + (when-not (= [(returned-key db 1) (returned-key db 2)] new-keys) + (println "FAIL FOR" db)) + (is (= [(returned-key db 1) + (returned-key db 2)] + new-keys))))))) + (deftest insert-one-row (doseq [db (test-specs)] (create-test-table :fruit db) From 1183d5738001b8962d83f9883c865d4d4b8578eb Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 29 Dec 2017 14:00:18 -0600 Subject: [PATCH 527/630] [maven-release-plugin] prepare release java.jdbc-0.7.5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3425d8fc..ab1f77e3 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.5-SNAPSHOT + 0.7.5 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.5 From d0407501d6702e8c08b9452edd706011e4a40454 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Fri, 29 Dec 2017 14:00:18 -0600 Subject: [PATCH 528/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ab1f77e3..b047a1cf 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.5 + 0.7.6-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.5 + HEAD From 5b2b9a3985d54b70bdd789891819f0fde37fbeb6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 12 Jan 2018 12:42:56 -0800 Subject: [PATCH 529/630] Expand/improve find-by-keys docstring --- src/main/clojure/clojure/java/jdbc.clj | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index cdb4c3a8..e79b72c0 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1301,8 +1301,21 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn find-by-keys "Given a database connection, a table name, a map of column name/value pairs, and an optional options map, return any matching rows. - An :order-by option may be supplied to sort the rows by a sequence of - columns, e.g,. {:order-by [:name {:age :desc]}" + + An :order-by option may be supplied to sort the rows, e.g., + + {:order-by [{:name :asc} {:age :desc} {:income :asc}]} + ;; equivalent to: + {:order-by [:name {:age :desc} :income]} + + The :order-by value is a sequence of column names (to sort in ascending + order) and/or maps from column names to directions (:asc or :desc). The + directions may be strings or keywords and are not case-sensitive. They + are mapped to ASC or DESC in the generated SQL. + + Note: if a ordering map has more than one key, the order of the columns + in the generated SQL ORDER BY clause is unspecified (so such maps should + only contain one key/value pair)." ([db table columns] (find-by-keys db table columns {})) ([db table columns opts] (let [{:keys [entities order-by] :as opts} From e8040925beddab6048873625cfe791341082290d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 16:17:42 -0800 Subject: [PATCH 530/630] Replace Leiningen with clj script and deps.edn --- .gitignore | 1 + README.md | 2 + deps.edn | 36 +++++++++++++ project.clj | 48 ------------------ run-tests.sh | 56 +++++++++++++++++++++ src/perf/clojure/clojure/java/perf_jdbc.clj | 17 +++++-- 6 files changed, 109 insertions(+), 51 deletions(-) create mode 100644 deps.edn delete mode 100644 project.clj create mode 100755 run-tests.sh diff --git a/.gitignore b/.gitignore index 4c0fdbdb..c1878206 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ *.jar .classpath +.cpcache .project .settings /.lein-failures diff --git a/README.md b/README.md index 21fd181b..77014295 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,8 @@ Developer Information $ TEST_DBS=mysql,postgres mvn test +* Also see the `run-tests.sh` shell script which uses the `clj` CLI and `deps.edn` for multi-version testing! + Change Log ==================== diff --git a/deps.edn b/deps.edn new file mode 100644 index 00000000..5cc4b181 --- /dev/null +++ b/deps.edn @@ -0,0 +1,36 @@ +;; You can run clojure.java.jdbc tests with: clj -A:test -A:runner +;; You can also specify an alias to select which version of Clojure to test +;; against: :1.7 :1.8 :1.9 :master + +{:paths ["src/main/clojure"] + :aliases {:test + {:extra-paths ["src/test/clojure"] + :extra-deps {org.clojure/test.check {:mvn/version "0.9.0"} + ;; Note: 1.12.1.1 is used in pom.xml for Java 6/7 compat + org.apache.derby/derby {:mvn/version "10.13.1.1"} + org.hsqldb/hsqldb {:mvn/version "2.3.4"} + ;; Note: 1.4.191 is used in pom.xml for Java 6 compat + com.h2database/h2 {:mvn/version "1.4.193"} + net.sourceforge.jtds/jtds {:mvn/version "1.3.1"} + ;; Note: Tests fail with 6.0.2+ driver + mysql/mysql-connector-java {:mvn/version "5.1.41"} + org.postgresql/postgresql {:mvn/version "9.4.1212.jre7"} + com.impossibl.pgjdbc-ng/pgjdbc-ng {:mvn/version "0.7.1"} + org.xerial/sqlite-jdbc {:mvn/version "3.16.1"} + ;; Note: Assumes Java 8; there's a .jre7 version as well + com.microsoft.sqlserver/mssql-jdbc {:mvn/version "6.2.2.jre8"}}} + :1.7 {:override-deps {org.clojure/clojure {:mvn/version "1.7.0"}}} + :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} + :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} + :master {:override-deps {org.clojure/clojure {:mvn/version "1.10.0-master-SNAPSHOT"}}} + :perf {:extra-paths ["src/perf/clojure"] + :extra-deps {criterium {:mvn/version "0.4.4"}} + :jvm-opts ["-server" + "-Xmx4096m" + "-Dclojure.compiler.direct-linking=true"]} + :runner + {:extra-deps {com.cognitect/test-runner + {:git/url "https://github.com/cognitect-labs/test-runner" + :sha "637c14437ba31c92a9168a65b1a787ad8713919c"}} + :main-opts ["-m" "cognitect.test-runner" + "-d" "src/test/clojure"]}}} diff --git a/project.clj b/project.clj deleted file mode 100644 index c25fcaa8..00000000 --- a/project.clj +++ /dev/null @@ -1,48 +0,0 @@ -;; NOTE: This project.clj file exists purely to make it easier to -;; develop and test java.jdbc locally. The pom.xml file is the -;; "system of record" as far as the project version is concerned. - -(defproject org.clojure/java.jdbc "0.7.6-SNAPSHOT" - :description "A low-level Clojure wrapper for JDBC-based access to databases." - :parent [org.clojure/pom.contrib "0.1.2"] - :url "https://github.com/clojure/java.jdbc" - :license {:name "Eclipse Public License" - :url "http://www.eclipse.org/legal/epl-v10.html"} - :source-paths ["src/main/clojure"] - :test-paths ["src/test/clojure"] - :dependencies [[org.clojure/clojure "1.9.0"] - ;; These are just the versions most recently test against - ;; for your own projects, use whatever version is most - ;; appropriate for you. Again, note that this project.clj - ;; file exists for convenience -- the pom.xml file is the - ;; "system of record" as far as dependencies go! - ;; Note: 1.12.1.1 is used in pom.xml for Java 6/7 compat - [org.apache.derby/derby "10.13.1.1"] - [org.hsqldb/hsqldb "2.3.4"] - ;; Note: 1.4.191 is used in pom.xml for Java 6 compat - [com.h2database/h2 "1.4.193"] - [net.sourceforge.jtds/jtds "1.3.1"] - ;; Tests fail with 6.0.2 driver: - [mysql/mysql-connector-java "5.1.41"] - [org.postgresql/postgresql "9.4.1212.jre7"] - [com.impossibl.pgjdbc-ng/pgjdbc-ng "0.7.1"] - [org.xerial/sqlite-jdbc "3.16.1"] - ;; Assumes Java 8; there's a .jre7 version as well: - [com.microsoft.sqlserver/mssql-jdbc "6.2.2.jre8"]] - - :profiles {:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} - :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} - :master {:dependencies [[org.clojure/clojure "1.10.0-master-SNAPSHOT"]]} - :dev {:dependencies [[org.clojure/test.check "0.9.0"] - [criterium "0.4.4"]]} - :perf {:test-paths ["src/perf/clojure"] - :jvm-opts ^:replace ["-server" - "-Xmx4096m" - "-Dclojure.compiler.direct-linking=true"]}} - :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} - ;; include dev profile with 1.9+ to pull in test.check - :aliases {"test-all" ["with-profile" - "dev,test,master:dev,test:test,1.8:test,1.7" - "test"] - "perf" ["with-profile" "default,dev,perf"]} - :min-lein-version "2.0.0") diff --git a/run-tests.sh b/run-tests.sh new file mode 100755 index 00000000..526c30e6 --- /dev/null +++ b/run-tests.sh @@ -0,0 +1,56 @@ +#!/bin/sh +# +# Run this shell script with a list of databases you want to test against: +# +# ./run-tests.sh mysql postgres +# +# The default list of derby h2 hsqldb sqlite are always tested against. +# +# Additionally you can specify: mssql jtds postgres pgsql mysql +# +# Alternatives to mysql (a db-spec) are mysql-str and mysql-jdbc-str which use +# connection strings instead. You may only specify one of these! +# +# Note: for mysql, postgres, and pgsql, the tests assume a database schema +# called clojure_test that is accesible by a user clojure_test with the +# password # clojure_test (currently hardcoded in the tests, sorry!). +# This will eventually change... +# +# For postgres or pgsql, you can set the following environment variables +# to override the defaults of 127.0.0.1 and 5432: +# +# TEST_POSTGRES_HOST TEST_POSTGRES_PORT +# +# Currently you may only specify one of postgres or pgsql! +# +# For mssql, you can set the following environment variables to override the +# defaults of 127.0.0.1\\SQLEXPRESS, 1433, clojure_test, sa, (empty string): +# +# TEST_MSSQL_HOST TEST_MSSQL_PORT TEST_MSSQL_NAME TEST_MSSQL_USER TEST_MSSQL_PASS +# +# For jtds, you can set the following environment variables (defaults per above): +# +# TEST_JTDS_HOST TEST_JTDS_PORT TEST_JTDS_NAME TEST_JTDS_USER TEST_JTDS_PASS +# +# Note: if you specify both mssql and jtds, make sure they're pointing at +# different database names or the tests will fail! +# +# Default set of databases to test: +dbs=sqlite,derby,hsqldb,h2 +# Can also specify: mssql,jtds,postgres,pgsql +# +while test "x$1" != "x" +do + dbs=${dbs},$1 + shift +done + +# Start with clean databases each time to avoid slowdown +rm -rf clojure_test_* + +versions="1.7 1.8 1.9 master" +for v in $versions +do + echo "\nRunning tests for Clojure $v" + TEST_DBS=$dbs time clj -A:test -A:$v -A:runner +done diff --git a/src/perf/clojure/clojure/java/perf_jdbc.clj b/src/perf/clojure/clojure/java/perf_jdbc.clj index 3554ed12..854254fb 100644 --- a/src/perf/clojure/clojure/java/perf_jdbc.clj +++ b/src/perf/clojure/clojure/java/perf_jdbc.clj @@ -10,9 +10,20 @@ (ns clojure.java.perf-jdbc "Performance tests for parts of clojure.java.jdbc. - Start a REPL with `lein perf repl` - Require this namespace and then run `(calibrate)` - followed by `(test-dummy)` and `(test-h2)` + Here's how to run these tests: + + $ clj -A:test -A:perf + Clojure 1.9.0 + user=> (p/calibrate) + ... + nil + user=> (p/test-dummy) + ... + nil + user=> (p/test-h2) + ... + nil + user=> These test compare the raw performance (against an in-memory H2 database) for hand-crafted Java JDBC calls and various `query` and `reducible-query` From cd1d9f05d79d4deb2324fd0eb13d93ebe4872be2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 16:48:32 -0800 Subject: [PATCH 531/630] Clean up how the tests are run Uses spaces instead of commas so the command line list of DB types can just be passed straight through. Print Clojure version under test from inside JDBC test to confirm exact version being run. --- README.md | 2 +- run-tests.sh | 15 +++++---------- src/test/clojure/clojure/java/test_jdbc.clj | 3 ++- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 77014295..1cc46500 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ Developer Information * Then run the tests with the TEST_DBS environment variable: - $ TEST_DBS=mysql,postgres mvn test + $ TEST_DBS="mysql postgres" mvn test * Also see the `run-tests.sh` shell script which uses the `clj` CLI and `deps.edn` for multi-version testing! diff --git a/run-tests.sh b/run-tests.sh index 526c30e6..dd41b4ea 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -32,18 +32,14 @@ # # TEST_JTDS_HOST TEST_JTDS_PORT TEST_JTDS_NAME TEST_JTDS_USER TEST_JTDS_PASS # +# For jtds you can just specify the IP address or hostname, you do not need +# the \\SQLEXPRESS part. +# # Note: if you specify both mssql and jtds, make sure they're pointing at # different database names or the tests will fail! # # Default set of databases to test: -dbs=sqlite,derby,hsqldb,h2 -# Can also specify: mssql,jtds,postgres,pgsql -# -while test "x$1" != "x" -do - dbs=${dbs},$1 - shift -done +dbs="derby h2 hsqldb sqlite" # Start with clean databases each time to avoid slowdown rm -rf clojure_test_* @@ -51,6 +47,5 @@ rm -rf clojure_test_* versions="1.7 1.8 1.9 master" for v in $versions do - echo "\nRunning tests for Clojure $v" - TEST_DBS=$dbs time clj -A:test -A:$v -A:runner + TEST_DBS="$dbs $*" time clj -A:test -A:$v -A:runner done diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 1130be3b..6f818456 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -25,6 +25,7 @@ [clojure.java.jdbc :as sql] [clojure.string :as str])) +(println "\nTesting with Clojure" (clojure-version)) (def with-spec? (try (require 'clojure.java.jdbc.spec) (require 'clojure.spec.test.alpha) @@ -42,7 +43,7 @@ ;; Apache Derby and HSQLDB can run without an external setup. (def test-databases (if-let [dbs (System/getenv "TEST_DBS")] - (map keyword (.split dbs ",")) + (map keyword (.split dbs " ")) ;; enable more by default once the build server is equipped? [:derby :hsqldb :h2 :sqlite])) From 8d32a56e7691d64cbcdcbcf83f325b19e3f90968 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 16:51:09 -0800 Subject: [PATCH 532/630] Noted switch from Leiningen to CLI/deps in Change Log --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 420b9022..ee97153f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.6 + +* Switched local test infrastructure over to CLI and `deps.edn` (from Leiningen) as an example of multi-version testing without a "build tool". + Changes in 0.7.5 * Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://dev.clojure.org/jira/browse/JDBC-163). From 7ee07ca5e80de665b022683920ada28b8bbe252b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 17:55:45 -0800 Subject: [PATCH 533/630] Add warn-on-reflection to ensure no reflection creeps in --- src/main/clojure/clojure/java/jdbc.clj | 2 ++ src/main/clojure/clojure/java/jdbc/spec.clj | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e79b72c0..28011d94 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -50,6 +50,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (java.util Hashtable Map Properties) (javax.sql DataSource))) +(set! *warn-on-reflection* true) + (defn as-sql-name "Given a naming strategy function and a keyword or string, return a string per that naming strategy. diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 9a4dfb03..be4b104d 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -17,6 +17,8 @@ (:require [clojure.spec.alpha :as s] [clojure.java.jdbc :as sql])) +(set! *warn-on-reflection* true) + ;; basic java.sql types -- cannot be generated! (s/def ::connection #(instance? java.sql.Connection %)) From 3d636725ba42fbfecc4a6be561baf37158638efc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 17:56:12 -0800 Subject: [PATCH 534/630] Add missing spec for db-spec being a URI object --- src/main/clojure/clojure/java/jdbc/spec.clj | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index be4b104d..9c7e9fee 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -26,6 +26,7 @@ (s/def ::prepared-statement #(instance? java.sql.PreparedStatement %)) (s/def ::result-set #(instance? java.sql.ResultSet %)) (s/def ::result-set-metadata #(instance? java.sql.ResultSetMetaData %)) +(s/def ::uri #(instance? java.net.URI %)) ;; database specification (connection description) @@ -73,6 +74,7 @@ (s/def ::db-spec-jndi (s/keys :req-un [::name] :opt-un [::environment])) (s/def ::db-spec-string string?) +(s/def ::db-spec-uri ::uri) (s/def ::db-spec (s/or :connection ::db-spec-connection :friendly ::db-spec-friendly :raw ::db-spec-raw @@ -80,7 +82,8 @@ :factory ::db-spec-factory :datasource ::db-spec-data-source :jndi ::db-spec-jndi - :uri ::db-spec-string)) + :uri-str ::db-spec-string + :uri-obj ::db-spec-uri)) ;; naming From c61346dadf7cf123f64cd048c5e4f1a45926b1e9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 17:56:41 -0800 Subject: [PATCH 535/630] Correct :connection-string to :connection-uri in add-connection --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 28011d94..5eef88ca 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -137,7 +137,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (extend-protocol Connectable String - (add-connection [s connection] {:connection connection :level 0 :connection-string s}) + (add-connection [s connection] {:connection connection :level 0 :connection-uri s}) (get-level [_] 0) clojure.lang.Associative From 4a996d2e9d37a1e79a8f0e4991e9071acdb4b7d4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 17:58:56 -0800 Subject: [PATCH 536/630] Update tests so they work again with a db-spec string --- src/test/clojure/clojure/java/test_jdbc.clj | 80 +++++++++++++-------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index 6f818456..c98c51fb 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -146,41 +146,63 @@ ;; necessary for it to do its job, and populate it as needed... (defn- derby? [db] - (if (string? db) - (re-find #"derby:" db) - (= "derby" (or (:subprotocol db) (:dbtype db))))) + (cond (string? db) + (re-find #"derby:" db) + (:connection-uri db) + (re-find #"derby:" (:connection-uri db)) + :else + (= "derby" (or (:subprotocol db) (:dbtype db))))) (defn- hsqldb? [db] - (if (string? db) - (re-find #"hsqldb:" db) - (#{"hsql" "hsqldb"} (or (:subprotocol db) (:dbtype db))))) + (cond (string? db) + (re-find #"hsqldb:" db) + (:connection-uri db) + (re-find #"hsqldb:" (:connection-uri db)) + :else + (#{"hsql" "hsqldb"} (or (:subprotocol db) (:dbtype db))))) (defn- mssql? [db] - (if (string? db) - (re-find #"sqlserver" db) - (#{"jtds" "jtds:sqlserver" "mssql" "sqlserver"} - (or (:subprotocol db) (:dbtype db))))) + (cond (string? db) + (re-find #"sqlserver" db) + (:connection-uri db) + (re-find #"sqlserver" (:connection-uri db)) + :else + (#{"jtds" "jtds:sqlserver" "mssql" "sqlserver"} + (or (:subprotocol db) (:dbtype db))))) (defn- mysql? [db] - (if (string? db) - (re-find #"mysql:" db) - (= "mysql" (or (:subprotocol db) (:dbtype db))))) + (cond (string? db) + (re-find #"mysql:" db) + (:connection-uri db) + (re-find #"mysql:" (:connection-uri db)) + :else + (= "mysql" (or (:subprotocol db) (:dbtype db))))) (defn- postgres? [db] - (if (string? db) - (or (re-find #"postgres" db) (re-find #"pgsql")) - (or (re-find #"postgres" (or (:subprotocol db) (:dbtype db))) - (re-find #"pgsql" (or (:subprotocol db) (:dbtype db)))))) + (cond (string? db) + (or (re-find #"postgres" db) (re-find #"pgsql" db)) + (:connection-uri db) + (or (re-find #"postgres" (:connection-uri db)) + (re-find #"pgsql" (:connection-uri db))) + :else + (or (re-find #"postgres" (or (:subprotocol db) (:dbtype db))) + (re-find #"pgsql" (or (:subprotocol db) (:dbtype db)))))) (defn- pgsql? [db] - (if (string? db) - (re-find #"pgsql") - (re-find #"pgsql" (or (:subprotocol db) (:dbtype db))))) + (cond (string? db) + (re-find #"pgsql" db) + (:connection-uri db) + (re-find #"pgsql" (:connection-uri db)) + :else + (re-find #"pgsql" (or (:subprotocol db) (:dbtype db))))) (defn- sqlite? [db] - (if (string? db) - (re-find #"sqlite:" db) - (= "sqlite" (or (:subprotocol db) (:dbtype db))))) + (cond (string? db) + (re-find #"sqlite:" db) + (:connection-uri db) + (re-find #"sqlite:" (:connection-uri db)) + :else + (= "sqlite" (or (:subprotocol db) (:dbtype db))))) (defmulti create-test-table "Create a standard test table. Uses db-do-commands. @@ -980,8 +1002,9 @@ (sql/query db ["SELECT * FROM fruit"]))) (is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}] (sql/query db ["SELECT * FROM fruit"] {:identifiers str/upper-case}))) - (is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}] - (sql/query (assoc db :identifiers str/upper-case) ["SELECT * FROM fruit"]))) + (when (map? db) + (is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}] + (sql/query (assoc db :identifiers str/upper-case) ["SELECT * FROM fruit"])))) (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil :fruit/grade nil :fruit/cost nil}] (sql/query db ["SELECT * FROM fruit"] {:qualifier "fruit"}))) @@ -991,9 +1014,10 @@ (is (= [{:name "Apple"}] (sql/query db ["SELECT name FROM fruit"] {:identifiers (comp keyword str/lower-case)}))) - (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil - :fruit/grade nil :fruit/cost nil}] - (sql/query (assoc db :qualifier "fruit") ["SELECT * FROM fruit"]))) + (when (map? db) + (is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil + :fruit/grade nil :fruit/cost nil}] + (sql/query (assoc db :qualifier "fruit") ["SELECT * FROM fruit"])))) (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}] (with-open [con (sql/get-connection db)] (sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")])))) From e70af1ef373fe1ba8335fe18cbe63d21125df263 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 18:00:18 -0800 Subject: [PATCH 537/630] Update to reflect today's changes --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index ee97153f..005982d1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,9 @@ Changes coming in 0.7.6 +* Add missing spec for `db-spec` being a `java.net.URI` object. +* Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). +* Update tests so they work properly with string `db-spec` test databases. +* Ensure no reflection warnings are present. * Switched local test infrastructure over to CLI and `deps.edn` (from Leiningen) as an example of multi-version testing without a "build tool". Changes in 0.7.5 From 64a79366fa464be75bdf4bdda133441b9d1efb26 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 18:22:00 -0800 Subject: [PATCH 538/630] More test clean up for string db-spec handling --- src/test/clojure/clojure/java/test_jdbc.clj | 77 ++++++--------------- 1 file changed, 23 insertions(+), 54 deletions(-) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/test_jdbc.clj index c98c51fb..f388003b 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/test_jdbc.clj @@ -145,64 +145,34 @@ ;; We start with all tables dropped and each test has to create the tables ;; necessary for it to do its job, and populate it as needed... +(defn- string->type [db] + (last (re-find #"^(jdbc:)?([^:]+):" db))) + +(defn- db-type [db] + (or (:subprotocol db) (:dbtype db) + (and (string? db) (string->type db)) + (and (:connection-uri db) (string->type (:connection-uri db))))) + (defn- derby? [db] - (cond (string? db) - (re-find #"derby:" db) - (:connection-uri db) - (re-find #"derby:" (:connection-uri db)) - :else - (= "derby" (or (:subprotocol db) (:dbtype db))))) + (= "derby" (db-type db))) (defn- hsqldb? [db] - (cond (string? db) - (re-find #"hsqldb:" db) - (:connection-uri db) - (re-find #"hsqldb:" (:connection-uri db)) - :else - (#{"hsql" "hsqldb"} (or (:subprotocol db) (:dbtype db))))) + (#{"hsql" "hsqldb"} (db-type db))) (defn- mssql? [db] - (cond (string? db) - (re-find #"sqlserver" db) - (:connection-uri db) - (re-find #"sqlserver" (:connection-uri db)) - :else - (#{"jtds" "jtds:sqlserver" "mssql" "sqlserver"} - (or (:subprotocol db) (:dbtype db))))) + (#{"jtds" "jtds:sqlserver" "mssql" "sqlserver"} (db-type db))) (defn- mysql? [db] - (cond (string? db) - (re-find #"mysql:" db) - (:connection-uri db) - (re-find #"mysql:" (:connection-uri db)) - :else - (= "mysql" (or (:subprotocol db) (:dbtype db))))) + (= "mysql" (db-type db))) (defn- postgres? [db] - (cond (string? db) - (or (re-find #"postgres" db) (re-find #"pgsql" db)) - (:connection-uri db) - (or (re-find #"postgres" (:connection-uri db)) - (re-find #"pgsql" (:connection-uri db))) - :else - (or (re-find #"postgres" (or (:subprotocol db) (:dbtype db))) - (re-find #"pgsql" (or (:subprotocol db) (:dbtype db)))))) + (#{"postgres" "pgsql"} (db-type db))) (defn- pgsql? [db] - (cond (string? db) - (re-find #"pgsql" db) - (:connection-uri db) - (re-find #"pgsql" (:connection-uri db)) - :else - (re-find #"pgsql" (or (:subprotocol db) (:dbtype db))))) + (= "pgsql" (db-type db))) (defn- sqlite? [db] - (cond (string? db) - (re-find #"sqlite:" db) - (:connection-uri db) - (re-find #"sqlite:" (:connection-uri db)) - :else - (= "sqlite" (or (:subprotocol db) (:dbtype db))))) + (= "sqlite" (db-type db))) (defmulti create-test-table "Create a standard test table. Uses db-do-commands. @@ -267,7 +237,7 @@ "mysql://clojure_test:clojure_test@localhost:3306/clojure_test"))))) (defn- returned-key [db k] - (case (or (:subprotocol db) (:dbtype db)) + (case (db-type db) "derby" {(keyword "1") nil} ("hsql" "hsqldb") nil "h2" nil @@ -281,12 +251,12 @@ k)) (defn- select-key [db] - (case (or (:subprotocol db) (:dbtype db)) + (case (db-type db) ("postgres" "postgresql" "pgsql") :id identity)) (defn- generated-key [db k] - (case (or (:subprotocol db) (:dbtype db)) + (case (db-type db) "derby" 0 ("hsql" "hsqldb") 0 "h2" 0 @@ -296,7 +266,7 @@ k)) (defn- float-or-double [db v] - (case (or (:subprotocol db) (:dbtype db)) + (case (db-type db) "derby" (Float. v) "h2" (Float. v) ("jtds" "jtds:sqlserver") (Float. v) @@ -405,7 +375,7 @@ (deftest test-do-prepared1e (doseq [db (test-specs)] ;; Derby/SQL Server does not have auto-generated id column which we're testing here - (when-not (#{"derby" "jtds" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (when-not (#{"derby" "jtds" "jtds:sqlserver"} (db-type db)) (create-test-table :fruit db) (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" @@ -578,7 +548,7 @@ (deftest execute-with-prepared-statement-return-keys (doseq [db (test-specs)] ;; Derby/SQL Server does not have auto-generated id column which we're testing here - (when-not (#{"derby" "jtds" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db))) + (when-not (#{"derby" "jtds" "jtds:sqlserver"} (db-type db)) (create-test-table :fruit db) (sql/with-db-connection [conn db] (let [connection (:connection conn) @@ -938,14 +908,13 @@ {:return-keys true :multi? true})) new-keys (map (select-key db) - (if (#{"jtds" "jtds:sqlserver"} - (or (:subprotocol db) (:dbtype db))) + (if (#{"jtds" "jtds:sqlserver"} (db-type db)) (do (is (thrown? java.sql.BatchUpdateException (execute-multi-insert db))) []) (execute-multi-insert db)))] - (case (or (:subprotocol db) (:dbtype db)) + (case (db-type db) ;; SQLite only returns the last key inserted in a batch "sqlite" (is (= [(returned-key db 2)] new-keys)) ;; Derby returns a single row count From 05d06a3784a66390073c30a5c075f057d5f6d797 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 22 Feb 2018 18:43:12 -0800 Subject: [PATCH 539/630] Clean up clj alias usage/instructions --- deps.edn | 2 +- run-tests.sh | 2 +- src/perf/clojure/clojure/java/perf_jdbc.clj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/deps.edn b/deps.edn index 5cc4b181..d8929853 100644 --- a/deps.edn +++ b/deps.edn @@ -1,4 +1,4 @@ -;; You can run clojure.java.jdbc tests with: clj -A:test -A:runner +;; You can run clojure.java.jdbc tests with: clj -A:test:runner ;; You can also specify an alias to select which version of Clojure to test ;; against: :1.7 :1.8 :1.9 :master diff --git a/run-tests.sh b/run-tests.sh index dd41b4ea..715fc84d 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -47,5 +47,5 @@ rm -rf clojure_test_* versions="1.7 1.8 1.9 master" for v in $versions do - TEST_DBS="$dbs $*" time clj -A:test -A:$v -A:runner + TEST_DBS="$dbs $*" time clj -A:test:runner:$v done diff --git a/src/perf/clojure/clojure/java/perf_jdbc.clj b/src/perf/clojure/clojure/java/perf_jdbc.clj index 854254fb..f104db4b 100644 --- a/src/perf/clojure/clojure/java/perf_jdbc.clj +++ b/src/perf/clojure/clojure/java/perf_jdbc.clj @@ -12,7 +12,7 @@ Here's how to run these tests: - $ clj -A:test -A:perf + $ clj -A:test:perf Clojure 1.9.0 user=> (p/calibrate) ... From 932f6c7137dbc227c4a6aa4f77155cd1f6429114 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 3 Mar 2018 14:58:26 -0800 Subject: [PATCH 540/630] Update to latest test-runner Move and rename tests to reflect more standard -test namespace approach. --- .gitignore | 1 + deps.edn | 2 +- .../java/{test_utilities.clj => jdbc/utilities_test.clj} | 2 +- .../clojure/clojure/java/{test_jdbc.clj => jdbc_test.clj} | 4 ++-- 4 files changed, 5 insertions(+), 4 deletions(-) rename src/test/clojure/clojure/java/{test_utilities.clj => jdbc/utilities_test.clj} (99%) rename src/test/clojure/clojure/java/{test_jdbc.clj => jdbc_test.clj} (99%) diff --git a/.gitignore b/.gitignore index c1878206..b3db9d32 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ /.lein-failures /.lein-repl-history /.nrepl-port +/build.boot /clojure_test_* bin classes diff --git a/deps.edn b/deps.edn index d8929853..e7bb6946 100644 --- a/deps.edn +++ b/deps.edn @@ -31,6 +31,6 @@ :runner {:extra-deps {com.cognitect/test-runner {:git/url "https://github.com/cognitect-labs/test-runner" - :sha "637c14437ba31c92a9168a65b1a787ad8713919c"}} + :sha "5f2b5c2efb444df76fb5252102b33f542ebf7f58"}} :main-opts ["-m" "cognitect.test-runner" "-d" "src/test/clojure"]}}} diff --git a/src/test/clojure/clojure/java/test_utilities.clj b/src/test/clojure/clojure/java/jdbc/utilities_test.clj similarity index 99% rename from src/test/clojure/clojure/java/test_utilities.clj rename to src/test/clojure/clojure/java/jdbc/utilities_test.clj index 02d7ba27..886b7cfa 100644 --- a/src/test/clojure/clojure/java/test_utilities.clj +++ b/src/test/clojure/clojure/java/jdbc/utilities_test.clj @@ -18,7 +18,7 @@ ;; seancorfield (gmail) ;; Migrated from clojure.contrib.test-sql 17 April 2011 -(ns clojure.java.test-utilities +(ns clojure.java.jdbc.utilities-test (:use clojure.test) (:require [clojure.java.jdbc :as sql])) diff --git a/src/test/clojure/clojure/java/test_jdbc.clj b/src/test/clojure/clojure/java/jdbc_test.clj similarity index 99% rename from src/test/clojure/clojure/java/test_jdbc.clj rename to src/test/clojure/clojure/java/jdbc_test.clj index f388003b..74ffdfa6 100644 --- a/src/test/clojure/clojure/java/test_jdbc.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -20,7 +20,7 @@ ;; seancorfield (gmail) ;; Migrated from clojure.contrib.test-sql 17 April 2011 -(ns clojure.java.test-jdbc +(ns clojure.java.jdbc-test (:require [clojure.test :refer :all] [clojure.java.jdbc :as sql] [clojure.string :as str])) @@ -125,7 +125,7 @@ "Return a sequence of db-spec maps that should be used for tests" [] (for [db test-databases] - @(ns-resolve 'clojure.java.test-jdbc (symbol (str (name db) "-db"))))) + @(ns-resolve 'clojure.java.jdbc-test (symbol (str (name db) "-db"))))) (defn- clean-up "Attempt to drop any test tables before we start a test." From ff778ad8b5eab7554995895a110342bd370544a2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 3 Mar 2018 21:30:46 -0800 Subject: [PATCH 541/630] Bump to latest test-runner --- deps.edn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deps.edn b/deps.edn index e7bb6946..4f47ceda 100644 --- a/deps.edn +++ b/deps.edn @@ -31,6 +31,6 @@ :runner {:extra-deps {com.cognitect/test-runner {:git/url "https://github.com/cognitect-labs/test-runner" - :sha "5f2b5c2efb444df76fb5252102b33f542ebf7f58"}} + :sha "76568540e7f40268ad2b646110f237a60295fa3c"}} :main-opts ["-m" "cognitect.test-runner" "-d" "src/test/clojure"]}}} From c74de0b65f94ba88e33710fd8f51921f8948412a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 4 Mar 2018 18:19:48 -0800 Subject: [PATCH 542/630] JDBC-165 fix specs for with-db-* functions --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc/spec.clj | 9 +++++---- src/test/clojure/clojure/java/jdbc_test.clj | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 005982d1..8adcd7f8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,7 @@ Changes coming in 0.7.6 * Add missing spec for `db-spec` being a `java.net.URI` object. * Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). +* Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://dev.clojure.org/jira/browse/JDBC-165). * Update tests so they work properly with string `db-spec` test databases. * Ensure no reflection warnings are present. * Switched local test infrastructure over to CLI and `deps.edn` (from Leiningen) as an example of multi-version testing without a "build tool". diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 9c7e9fee..dd77989c 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -276,15 +276,16 @@ :args (s/cat :binding ::transaction-binding :body (s/* any?))) -(s/def ::simple-binding (s/spec (s/cat :con-db simple-symbol? - :db-spec any?))) +(s/def ::connection-binding (s/spec (s/cat :con-db simple-symbol? + :db-spec any? + :opts (s/? any?)))) (s/fdef sql/with-db-connection - :args (s/cat :binding ::simple-binding + :args (s/cat :binding ::connection-binding :body (s/* any?))) (s/fdef sql/with-db-metadata - :args (s/cat :binding ::simple-binding + :args (s/cat :binding ::connection-binding :body (s/* any?))) (s/fdef sql/metadata-result diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 74ffdfa6..68fc4647 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -420,7 +420,7 @@ [4 "Orange" "juicy" 139 88.6]])] (is (= '(1 1 1 1) r))) (is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) - (is (= 4 (sql/with-db-connection [con db] + (is (= 4 (sql/with-db-connection [con db {}] (sql/query con (sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit") {:result-set-fn count})))) (when-not (pgsql? db) ;; maxRows does not appear to be supported on Impossibl pgsql? @@ -840,7 +840,7 @@ (deftest test-metadata-managed (doseq [db (test-specs)] (create-test-table :fruit db) - (sql/with-db-metadata [metadata db] + (sql/with-db-metadata [metadata db {}] (let [table-info (sql/metadata-query (.getTables metadata nil nil nil (into-array ["TABLE" "VIEW"])))] From 37587dc32a29ea39ace9d944a250445619f528a3 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 6 Mar 2018 15:14:37 -0800 Subject: [PATCH 543/630] Appease Eastwood! --- src/main/clojure/clojure/java/jdbc.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5eef88ca..ff45fb3b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -804,7 +804,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (with-db-connection [con-db db-spec opts] ... con-db ...)" [binding & body] - `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + `(let [db-spec# ~(second binding) opts# ~(or (second (rest binding)) {})] (with-open [con# (get-connection db-spec# opts#)] (let [~(first binding) (add-connection db-spec# con#)] ~@body)))) @@ -816,7 +816,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (with-db-metadata [md db-spec opts] ... md ...)" [binding & body] - `(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})] + `(let [db-spec# ~(second binding) opts# ~(or (second (rest binding)) {})] (with-open [con# (get-connection db-spec# opts#)] (let [~(first binding) (.getMetaData con#)] ~@body)))) From 412580cebfd699aa5b1814a29ff384aee955a8ed Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 23 Apr 2018 14:37:18 -0700 Subject: [PATCH 544/630] Add built-in :dbtype h2:mem support --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 18 +++++++++++------- src/main/clojure/clojure/java/jdbc/spec.clj | 2 +- src/test/clojure/clojure/java/jdbc_test.clj | 13 +++++++------ 4 files changed, 20 insertions(+), 14 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 8adcd7f8..997c7ec7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.6 +* Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). * Add missing spec for `db-spec` being a `java.net.URI` object. * Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). * Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://dev.clojure.org/jira/browse/JDBC-165). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ff45fb3b..957e76c6 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -153,6 +153,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} The subprotocols map below provides aliases for dbtype." {"derby" "org.apache.derby.jdbc.EmbeddedDriver" "h2" "org.h2.Driver" + "h2:mem" "org.h2.Driver" "hsqldb" "org.hsqldb.jdbcDriver" "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" "mysql" "com.mysql.jdbc.Driver" @@ -335,13 +336,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "sqlserver" 1433 nil)) db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") - url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) - (str "jdbc:" subprotocol ":" dbname) - (str "jdbc:" subprotocol ":" - (host-prefixes subprotocol "//") - host - (when port (str ":" port)) - db-sep dbname)) + url (cond (= "h2:mem" dbtype) + (str "jdbc:" subprotocol ":" dbname ";DB_CLOSE_DELAY=-1") + (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) + (str "jdbc:" subprotocol ":" dbname) + :else + (str "jdbc:" subprotocol ":" + (host-prefixes subprotocol "//") + host + (when port (str ":" port)) + db-sep dbname)) etc (dissoc db-spec :dbtype :dbname)] (if-let [class-name (or classname (classnames subprotocol))] (do diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index dd77989c..2a93a059 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -30,7 +30,7 @@ ;; database specification (connection description) -(s/def ::subprotocol-base #{"derby" "h2" "hsqldb" "jtds:sqlserver" "mysql" +(s/def ::subprotocol-base #{"derby" "h2" "h2:mem" "hsqldb" "jtds:sqlserver" "mysql" "oracle:oci" "oracle:thin" "pgsql" "postgresql" "redshift" "sqlite" "sqlserver"}) (s/def ::subprotocol-alias #{"hsql" "jtds" "mssql" "oracle" "postgres"}) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 68fc4647..f6e2874d 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -77,8 +77,9 @@ (def hsqldb-db {:dbtype "hsql" :dbname "clojure_test_hsqldb"}) -(def h2-db {:dbtype "h2" - :dbname "./clojure_test_h2"}) +;; test with new (0.7.6) in-memory H2 database +(def h2-db {:dbtype "h2:mem" + :dbname "clojure_test_h2"}) (def sqlite-db {:dbtype "sqlite" :dbname "clojure_test_sqlite"}) @@ -240,7 +241,7 @@ (case (db-type db) "derby" {(keyword "1") nil} ("hsql" "hsqldb") nil - "h2" nil + ("h2" "h2:mem") nil "mysql" {:generated_key k} nil (if (mysql? db) ; string-based tests {:generated_key k} @@ -259,7 +260,7 @@ (case (db-type db) "derby" 0 ("hsql" "hsqldb") 0 - "h2" 0 + ("h2" "h2:mem") 0 ("jtds" "jtds:sqlserver") 0 ("mssql" "sqlserver") 0 "sqlite" 0 @@ -268,7 +269,7 @@ (defn- float-or-double [db v] (case (db-type db) "derby" (Float. v) - "h2" (Float. v) + ("h2" "h2:mem") (Float. v) ("jtds" "jtds:sqlserver") (Float. v) ("mssql" "sqlserver") (Float. v) ("postgres" "postgresql" "pgsql") (Float. v) @@ -920,7 +921,7 @@ ;; Derby returns a single row count "derby" (is (= [(returned-key db 1)] new-keys)) ;; H2 returns nothing useful - "h2" (is (= [] new-keys)) + ("h2" "h2:mem") (is (= [] new-keys)) ;; HSQL returns nothing useful "hsql" (is (= [] new-keys)) ;; MS SQL returns row counts From 51b7260696c35b53ad9802199f7fe62dc97330be Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 23 Apr 2018 21:29:42 -0700 Subject: [PATCH 545/630] JDBC-166 execute! :return-keys col names support --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 7 +++++-- src/test/clojure/clojure/java/jdbc_test.clj | 22 ++++++++++++++++++++- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 997c7ec7..c1ffdb5d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.6 +* `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). * Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). * Add missing spec for `db-spec` being a `java.net.URI` object. * Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 957e76c6..c08af2eb 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -938,12 +938,15 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (db-do-prepared-return-keys db true transaction? sql-params) (db-do-prepared-return-keys db transaction? sql-params {}))) ([db transaction? sql-params opts] - (let [opts (merge (when (map? db) db) opts)] + (let [opts (merge (when (map? db) db) opts) + return-keys (or (:return-keys opts) true)] (if-let [con (db-find-connection db)] (let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (if (instance? PreparedStatement sql) (db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?)) - (with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))] + (with-open [^PreparedStatement stmt (prepare-statement + con sql + (assoc opts :return-keys return-keys))] (db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?))))) (with-open [con (get-connection db opts)] (db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts)))))) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index f6e2874d..dc7a2095 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -546,13 +546,16 @@ (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] {:row-fn :name :result-set-fn first}))))) -(deftest execute-with-prepared-statement-return-keys +(deftest execute-with-prepared-statement-with-return-keys (doseq [db (test-specs)] ;; Derby/SQL Server does not have auto-generated id column which we're testing here (when-not (#{"derby" "jtds" "jtds:sqlserver"} (db-type db)) (create-test-table :fruit db) (sql/with-db-connection [conn db] (let [connection (:connection conn) + ;; although we ask for keys to come back, execute! cannot see into + ;; the PreparedStatement so it doesn't know to call things in a + ;; different way, so we get affected row counts instead! prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) " "VALUES ( ?, ?, ? )") {:return-keys ["id"]})] @@ -563,6 +566,23 @@ (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] {:row-fn :name :result-set-fn first})))))) +(deftest execute-with-return-keys-option + (doseq [db (test-specs)] + ;; Derby/SQL Server does not have auto-generated id column which we're testing here + (when-not (#{"derby" "jtds" "jtds:sqlserver"} (db-type db)) + (create-test-table :fruit db) + (sql/with-db-connection [conn db] + (let [connection (:connection conn) + sql-stmt (str "INSERT INTO fruit ( name, appearance, cost ) " + "VALUES ( ?, ?, ? )")] + (is (= (returned-key db 1) (sql/execute! db [sql-stmt "Apple" "Green" 75] + {:return-keys ["id"]}))) + (is (= (returned-key db 2) (sql/execute! db [sql-stmt "Pear" "Yellow" 99] + {:return-keys ["id"]}))))) + (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) + (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] + {:row-fn :name :result-set-fn first})))))) + (deftest test-update-values (doseq [db (test-specs)] (create-test-table :fruit db) From 4de9aba0003358f663f1da77570006b30d51855f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 24 Apr 2018 20:49:17 -0700 Subject: [PATCH 546/630] Prep for 0.7.6 release --- CHANGES.md | 2 +- README.md | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c1ffdb5d..384393e1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.6 +Changes in 0.7.6 * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). * Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). diff --git a/README.md b/README.md index 1cc46500..56643a7c 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.5 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.6 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -32,14 +32,14 @@ Latest stable release: 0.7.5 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.5"] +[org.clojure/java.jdbc "0.7.6"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.5 + 0.7.6 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -138,6 +138,16 @@ Developer Information Change Log ==================== +* Release 0.7.6 on 2018-04-24 + * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). + * Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). + * Add missing spec for `db-spec` being a `java.net.URI` object. + * Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). + * Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://dev.clojure.org/jira/browse/JDBC-165). + * Update tests so they work properly with string `db-spec` test databases. + * Ensure no reflection warnings are present. + * Switched local test infrastructure over to CLI and `deps.edn` (from Leiningen) as an example of multi-version testing without a "build tool". + * Release 0.7.5 on 2017-12-29 * Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://dev.clojure.org/jira/browse/JDBC-163). From a12b7202b61bfbb5f35c51e977c942252bd607ea Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 24 Apr 2018 22:51:55 -0500 Subject: [PATCH 547/630] [maven-release-plugin] prepare release java.jdbc-0.7.6 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b047a1cf..547cb6a3 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.6-SNAPSHOT + 0.7.6 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.6 From 1320e630ba41ac6ef33abc178af9e7d1aeaeddb9 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 24 Apr 2018 22:51:55 -0500 Subject: [PATCH 548/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 547cb6a3..d8b4d4e5 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.6 + 0.7.7-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.6 + HEAD From 70224905f79c3523fb4803e1b9854efa47ac7bfb Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 9 May 2018 10:48:18 -0700 Subject: [PATCH 549/630] Clarify use of get-connection --- src/main/clojure/clojure/java/jdbc.clj | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index c08af2eb..e44b08bf 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2008-2018 Sean Corfield, Stephen C. Gilardi. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be @@ -228,8 +228,22 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (defn get-connection "Creates a connection to a database. db-spec is usually a map containing connection - parameters but can also be a URI or a String. The various possibilities are described - below: + parameters but can also be a URI or a String. + + The only time you should call this function is when you need a Connection for + prepare-statement -- no other public functions in clojure.java.jdbc accept a + raw Connection object: they all expect a db-spec (either a raw db-spec or one + obtained via with-db-connection or with-db-transaction). + + The correct usage of get-connection for prepare-statement is: + + (with-open [conn (jdbc/get-connection db-spec)] + ... (jdbc/prepare-statement conn sql-statement options) ...) + + Any connection obtained via calling get-connection directly must be closed + explicitly (via with-open or a direct call to .close on the Connection object). + + The various possibilities are described below: DriverManager (preferred): :dbtype (required) a String, the type of the database (the jdbc subprotocol) @@ -1006,6 +1020,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "Given a db-spec, a SQL statement (or a prepared statement), a set of parameters, a result set processing function and options, execute the query." [db sql params func opts] + #_(println "\nquery" sql params) (if (instance? PreparedStatement sql) (let [^PreparedStatement stmt sql] (execute-query-with-params From 2c3175affe073fc51ffbf5a34c7fa9a8029066e8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 9 May 2018 11:22:29 -0700 Subject: [PATCH 550/630] Add custom exception for misuse of Connection where db-spec is expected --- src/main/clojure/clojure/java/jdbc.clj | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e44b08bf..5a33ba08 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -395,6 +395,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} name) db-spec))) + ;; passing a raw Connection object to a function expecting a db-spec is + ;; usually a confusion over how/when to use get-connection and deserves + ;; a custom error message: + (instance? java.sql.Connection db-spec) + (let [^String msg (str "db-spec is a raw Connection object!\n" + "Did you call get-connection in the wrong context?\n" + "You should only call that to pass a Connection into prepare-statement.\n" + "(and don't forget to close it via with-open or .close)")] + (throw (IllegalArgumentException. msg))) + :else (let [^String msg (format "db-spec %s is missing a required parameter" db-spec)] (throw (IllegalArgumentException. msg)))))) From b560db958d3aef1fb404c5f05377a2915b5c3327 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 9 May 2018 11:26:21 -0700 Subject: [PATCH 551/630] Note the enhanced exception message for misuse of get-connection --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 384393e1..fac5edbe 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.7 + +* `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). + Changes in 0.7.6 * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). From 29cde7211d6e2edd451b6034ac0909e914b48dbc Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 25 May 2018 09:35:02 -0700 Subject: [PATCH 552/630] Fix execute! :return-keys test for Postgres Because I always forget that Postgres returns rows, not just values. --- src/test/clojure/clojure/java/jdbc_test.clj | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index dc7a2095..58ec6566 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -574,11 +574,14 @@ (sql/with-db-connection [conn db] (let [connection (:connection conn) sql-stmt (str "INSERT INTO fruit ( name, appearance, cost ) " - "VALUES ( ?, ?, ? )")] - (is (= (returned-key db 1) (sql/execute! db [sql-stmt "Apple" "Green" 75] - {:return-keys ["id"]}))) - (is (= (returned-key db 2) (sql/execute! db [sql-stmt "Pear" "Yellow" 99] - {:return-keys ["id"]}))))) + "VALUES ( ?, ?, ? )") + selector (select-key db)] + (is (= (returned-key db 1) + (selector (sql/execute! db [sql-stmt "Apple" "Green" 75] + {:return-keys ["id"]})))) + (is (= (returned-key db 2) + (selector (sql/execute! db [sql-stmt "Pear" "Yellow" 99] + {:return-keys ["id"]})))))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] {:row-fn :name :result-set-fn first})))))) From f71bf4ec9c71d4c7931282c0a18639f1a4389487 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 25 May 2018 09:38:02 -0700 Subject: [PATCH 553/630] Illustrate qualified-keyword usage on query/insert! --- src/test/clojure/clojure/java/jdbc_test.clj | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 58ec6566..ed634ba3 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -1059,13 +1059,20 @@ (is (= rows inserted))))) (deftest insert-two-by-map-and-query-as-arrays + ;; this test also serves to illustrate qualified keyword usage (doseq [db (test-specs)] - (create-test-table :fruit db) - (let [new-keys (map (select-key db) (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}])) + ;; qualifier on table name ignored by default + (create-test-table :table/fruit db) + (let [new-keys (map (select-key db) + ;; insert ignores namespace qualifier by default + (sql/insert-multi! db :table/fruit + [{:fruit/name "Apple"} + {:fruit/name "Pear"}])) rows (sql/query db ["SELECT * FROM fruit ORDER BY name"] - {:as-arrays? :cols-as-is})] + {:as-arrays? :cols-as-is + :qualifier "fruit"})] (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) - (is (= [[:id :name :appearance :cost :grade] + (is (= [[:fruit/id :fruit/name :fruit/appearance :fruit/cost :fruit/grade] [(generated-key db 1) "Apple" nil nil nil] [(generated-key db 2) "Pear" nil nil nil]] rows))))) From 0f3350be73d513fa6fd35ab82944dc9e796e2fe7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 21 Jun 2018 20:21:29 -0700 Subject: [PATCH 554/630] JDBC-169 refactoring to standardize result set handling Currently :as-arrays? true :multi? false :return-keys true may return strange results -- need to add tests to confirm edge case behavior here. --- src/main/clojure/clojure/java/jdbc.clj | 82 +++++++++++++------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5a33ba08..abe687bb 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -849,28 +849,31 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [~(first binding) (.getMetaData con#)] ~@body)))) +(defn- process-result-set + "Given a Java ResultSet and options, produce a processed result-set-seq, + honoring as-arrays?, result-set-fn, and row-fn from opts." + [rset opts] + (let [{:keys [as-arrays? result-set-fn row-fn]} + (merge {:row-fn identity} opts) + result-set-fn (or result-set-fn (if as-arrays? vec doall))] + (if as-arrays? + ((^:once fn* [rs] + (result-set-fn (cons (first rs) + (map row-fn (rest rs))))) + (result-set-seq rset opts)) + (result-set-fn (map row-fn (result-set-seq rset opts)))))) + (defn metadata-result "If the argument is a java.sql.ResultSet, turn it into a result-set-seq, else return it as-is. This makes working with metadata easier. Also accepts an option map containing :identifiers, :keywordize?, :qualifier, - :as-arrays?, :row-fn,and :result-set-fn to control how the ResultSet is + :as-arrays?, :row-fn, and :result-set-fn to control how the ResultSet is transformed and returned. See query for more details." ([rs-or-value] (metadata-result rs-or-value {})) ([rs-or-value opts] - (let [{:keys [as-arrays? result-set-fn row-fn] :as opts} - (merge {:identifiers str/lower-case - :keywordize? true - :read-columns dft-read-columns - :row-fn identity} opts) - result-set-fn (or result-set-fn (if as-arrays? vec doall))] - (if (instance? java.sql.ResultSet rs-or-value) - ((^{:once true} fn* [rs] - (result-set-fn (if as-arrays? - (cons (first rs) - (map row-fn (rest rs))) - (map row-fn rs)))) - (result-set-seq rs-or-value opts)) - rs-or-value)))) + (if (instance? java.sql.ResultSet rs-or-value) + (process-result-set rs-or-value opts) + rs-or-value))) (defmacro metadata-query "Given a Java expression that extracts metadata (in the context of with-db-metadata), @@ -911,9 +914,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} Supports :multi? which causes a full result set sequence of keys to be returned, and assumes the param-group is a sequence of parameter lists, - rather than a single sequence of parameters." + rather than a single sequence of parameters. + + Also supports :row-fn and, if :multi? is truthy, :result-set-fn" [db ^PreparedStatement stmt param-group opts] - (let [{:keys [transaction? multi?] :as opts} (merge (when (map? db) db) opts) + (let [{:keys [as-arrays? multi? row-fn transaction?] :as opts} + (merge {:row-fn identity} (when (map? db) db) opts) exec-and-return-keys (^{:once true} fn* [] (let [counts (if multi? @@ -921,10 +927,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (.executeUpdate stmt))] (try (let [rs (.getGeneratedKeys stmt) - rss (result-set-seq rs opts) - result (if multi? - (doall rss) - (first rss))] + result (cond multi? + (process-result-set rs opts) + as-arrays? + ((^:once fn* [rs] + (list (first rs) + (row-fn (second rs)))) + ;; not quite: as-arrays? will yield entire rs? + (result-set-seq rs opts)) + :else + (row-fn (first (result-set-seq rs opts))))] ;; sqlite (and maybe others?) requires ;; record set to be closed (.close rs) @@ -1096,13 +1108,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} See also prepare-statement for additional options." ([db sql-params] (query db sql-params {})) ([db sql-params opts] - (let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts} - (merge {:explain-fn println :identifiers str/lower-case - :keywordize? true - :read-columns dft-read-columns :row-fn identity} - (when (map? db) db) - opts) - result-set-fn (or result-set-fn (if as-arrays? vec doall)) + (let [{:keys [explain? explain-fn] :as opts} + (merge {:explain-fn println} (when (map? db) db) opts) [sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))] (when-not (sql-stmt? sql) (let [^Class sql-class (class sql) @@ -1122,15 +1129,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (dissoc :explain? :result-set-fn :row-fn) (assoc :result-set-fn explain-fn)))) (db-query-with-resultset* db sql params - (if as-arrays? - (^{:once true} fn* [rset] - ((^{:once true} fn* [rs] - (result-set-fn (cons (first rs) - (map row-fn (rest rs))))) - (result-set-seq rset opts))) - (^{:once true} fn* [rset] - (result-set-fn (map row-fn - (result-set-seq rset opts))))) + (^:once fn* [rset] + (process-result-set rset opts)) opts)))) (defn- get-rs-columns @@ -1409,7 +1409,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} db-do-prepared) execute-helper (^{:once true} fn* [db] (db-do-helper db transaction? sql-params opts))] - (if-let [con (db-find-connection db)] + (if (db-find-connection db) (execute-helper db) (with-open [con (get-connection db opts)] (execute-helper (add-connection db con))))))) @@ -1442,7 +1442,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} inserts), run a prepared statement on each and return any generated keys. Note: we are eager so an unrealized lazy-seq cannot escape from the connection." [db stmts opts] - (doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts))) + (doall (map (fn [stmt] (db-do-prepared-return-keys db false stmt opts)) stmts))) (defn- insert-helper "Given a (connected) database connection, a transaction flag and some SQL statements @@ -1506,7 +1506,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (when-not (map? row) (throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row"))) (insert-single-row-sql table row entities)) rows)] - (if-let [con (db-find-connection db)] + (if (db-find-connection db) (insert-helper db transaction? sql-params opts) (with-open [con (get-connection db opts)] (insert-helper (add-connection db con) transaction? sql-params opts))))) @@ -1519,7 +1519,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [{:keys [entities transaction?] :as opts} (merge {:entities identity :transaction? true} (when (map? db) db) opts) sql-params (insert-multi-row-sql table cols values entities)] - (if-let [con (db-find-connection db)] + (if (db-find-connection db) (db-do-prepared db transaction? sql-params (assoc opts :multi? true)) (with-open [con (get-connection db opts)] (db-do-prepared (add-connection db con) transaction? sql-params From b8c7b5b69cb0a835b1721722298f962b188d8787 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Jun 2018 16:15:44 -0700 Subject: [PATCH 555/630] run-tests.sh should "fail fast" If tests fail on an early version of Clojure, later versions should not be tested --- run-tests.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/run-tests.sh b/run-tests.sh index 715fc84d..c628aa48 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -47,5 +47,9 @@ rm -rf clojure_test_* versions="1.7 1.8 1.9 master" for v in $versions do - TEST_DBS="$dbs $*" time clj -A:test:runner:$v + TEST_DBS="$dbs $*" clj -A:test:runner:$v + if test $? -ne 0 + then + exit $? + fi done From 4dd036d368964da9561634cb69ce730269e3de78 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Jun 2018 16:18:06 -0700 Subject: [PATCH 556/630] JDBC-169 apply result-set-fn more consistently Apply it to row counts when a DB cannot return generated keys. Apply it to multiple generated keys returned (by db-do-prepared-return-keys in an insert-multi!). Apply it to homogeneous as-arrays? generated keys. --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 24 +++++++- src/test/clojure/clojure/java/jdbc_test.clj | 65 +++++++++++++++++++-- 3 files changed, 83 insertions(+), 7 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index fac5edbe..e326cdeb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.7 +* Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). Changes in 0.7.6 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index abe687bb..fbcf21ef 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -933,7 +933,6 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ((^:once fn* [rs] (list (first rs) (row-fn (second rs)))) - ;; not quite: as-arrays? will yield entire rs? (result-set-seq rs opts)) :else (row-fn (first (result-set-seq rs opts))))] @@ -943,7 +942,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} result) (catch Exception _ ;; assume generated keys is unsupported and return counts instead: - counts))))] + (let [result-set-fn (or (:result-set-fn opts) doall)] + (result-set-fn (map row-fn counts)))))))] (if multi? (doseq [params param-group] ((:set-parameters opts dft-set-parameters) stmt params) @@ -1442,7 +1442,25 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} inserts), run a prepared statement on each and return any generated keys. Note: we are eager so an unrealized lazy-seq cannot escape from the connection." [db stmts opts] - (doall (map (fn [stmt] (db-do-prepared-return-keys db false stmt opts)) stmts))) + (let [{:keys [as-arrays? result-set-fn]} (merge (when (map? db) db) opts) + per-statement (fn [stmt] + (db-do-prepared-return-keys db false stmt opts))] + (if as-arrays? + (let [rs (map per-statement stmts)] + (cond (apply = (map first rs)) + ;; all the columns are the same, rearrange to cols + rows format + ((or result-set-fn vec) + (cons (ffirst rs) + (map second rs))) + result-set-fn + (throw (ex-info (str "Cannot apply result-set-fn to" + " non-homogeneous generated keys array") rs)) + :else + ;; non-non-homogeneous generated keys array - return as-is + rs)) + (if result-set-fn + (result-set-fn (map per-statement stmts)) + (seq (mapv per-statement stmts)))))) (defn- insert-helper "Given a (connected) database connection, a transaction flag and some SQL statements diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index ed634ba3..18ca8f32 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -572,16 +572,16 @@ (when-not (#{"derby" "jtds" "jtds:sqlserver"} (db-type db)) (create-test-table :fruit db) (sql/with-db-connection [conn db] - (let [connection (:connection conn) - sql-stmt (str "INSERT INTO fruit ( name, appearance, cost ) " + (let [sql-stmt (str "INSERT INTO fruit ( name, appearance, cost ) " "VALUES ( ?, ?, ? )") selector (select-key db)] (is (= (returned-key db 1) (selector (sql/execute! db [sql-stmt "Apple" "Green" 75] {:return-keys ["id"]})))) (is (= (returned-key db 2) - (selector (sql/execute! db [sql-stmt "Pear" "Yellow" 99] - {:return-keys ["id"]})))))) + (sql/execute! db [sql-stmt "Pear" "Yellow" 99] + {:return-keys ["id"] + :row-fn selector}))))) (is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))) (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] {:row-fn :name :result-set-fn first})))))) @@ -960,6 +960,44 @@ (returned-key db 2)] new-keys))))))) +(deftest insert-two-via-execute-result-set-fn + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [execute-multi-insert + (fn [db] + (sql/execute! db [(str "INSERT INTO fruit ( name )" + " VALUES ( ? )") + ["Apple"] + ["Orange"]] + {:return-keys true + :multi? true + :result-set-fn count})) + n (if (#{"jtds" "jtds:sqlserver"} (db-type db)) + (do + (is (thrown? java.sql.BatchUpdateException + (execute-multi-insert db))) + 0) + (execute-multi-insert db))] + (case (db-type db) + ;; SQLite only returns the last key inserted in a batch + "sqlite" (is (= 1 n)) + ;; Derby returns a single row count + "derby" (is (= 1 n)) + ;; H2 returns nothing useful + ("h2" "h2:mem") (is (= 0 n)) + ;; HSQL returns nothing useful + "hsql" (is (= 0 n)) + ;; MS SQL returns row counts (we still apply result-set-fn) + "mssql" (is (= 2 n)) + ;; jTDS disallows batch updates returning keys (handled above) + ("jtds" "jtds:sqlserver") + (is (= 0 n)) + ;; otherwise expect two rows with the correct keys + (do + (when-not (= 2 n) + (println "FAIL FOR" db)) + (is (= 2 n))))))) + (deftest insert-one-row (doseq [db (test-specs)] (create-test-table :fruit db) @@ -972,6 +1010,12 @@ (let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"} {}))] (is (= [(returned-key db 1)] new-keys))))) +(deftest insert-one-row-opts-row-fn + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert! db :fruit {:name "Apple"} {:row-fn (select-key db)})] + (is (= [(returned-key db 1)] new-keys))))) + (deftest insert-one-col-val (doseq [db (test-specs)] (create-test-table :fruit db) @@ -1034,6 +1078,19 @@ (is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil} {:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows))))) +(deftest insert-two-by-map-row-fn + (doseq [db (test-specs)] + (create-test-table :fruit db) + (let [new-keys (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}] + {:row-fn (select-key db)})] + (is (= [(returned-key db 1) (returned-key db 2)] new-keys))))) + +(deftest insert-two-by-map-result-set-fn + (doseq [db (test-specs)] + (create-test-table :fruit db) + (is (= 2 (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}] + {:result-set-fn count}))))) + (deftest insert-identifiers-respected-1 (doseq [db (filter postgres? (test-specs))] (create-test-table :fruit db) From ecbd64c92185b1b399053580ad61a70bda6f25ac Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Jun 2018 16:22:18 -0700 Subject: [PATCH 557/630] JDBC-169 improve execute! docstring --- src/main/clojure/clojure/java/jdbc.clj | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index fbcf21ef..ca805140 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1396,7 +1396,9 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} If :return-keys is provided, db-do-prepared-return-keys will be called instead of db-do-prepared, and the result will be a sequence of maps - containing the generated keys. + containing the generated keys. If present, :row-fn will be applied. If :multi? + then :result-set-fn will also be applied if present. :as-arrays? may also be + specified (which will affect what :result-set-fn is passed). If there are no parameters specified, executeUpdate will be used, otherwise executeBatch will be used. This may affect what SQL you can run via execute!" From cb8f51bf0bf3a9c77e68fd410650e3d3b7ddf30f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 23 Jun 2018 16:30:31 -0700 Subject: [PATCH 558/630] Prep for 0.7.7 --- CHANGES.md | 2 +- README.md | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index e326cdeb..0590d2f4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.7 +Changes in 0.7.7 * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). diff --git a/README.md b/README.md index 56643a7c..80e8f0f5 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.6 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.7 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -32,14 +32,14 @@ Latest stable release: 0.7.6 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.6"] +[org.clojure/java.jdbc "0.7.7"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.6 + 0.7.7 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -138,6 +138,10 @@ Developer Information Change Log ==================== +* Release 0.7.7 on 2018-06-23 + * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). + * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). + * Release 0.7.6 on 2018-04-24 * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). * Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). From ad6929799fcedc675f1c515077fd79413e7db4e0 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 23 Jun 2018 18:35:54 -0500 Subject: [PATCH 559/630] [maven-release-plugin] prepare release java.jdbc-0.7.7 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d8b4d4e5..82c847c8 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.7-SNAPSHOT + 0.7.7 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.7 From 3f2e197373cd1a8dcd45274671022c2a8b1e96a6 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 23 Jun 2018 18:35:54 -0500 Subject: [PATCH 560/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 82c847c8..72e15556 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.7 + 0.7.8-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.7 + HEAD From d8a35b9531b76a772467ca24b2d866b7bc29b6c6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 28 Jun 2018 10:26:32 -0700 Subject: [PATCH 561/630] Update tested versions of JDBC drivers (and tests) Java 8 compatibility (mostly). --- deps.edn | 12 +++++------- pom.xml | 10 +++++----- src/test/clojure/clojure/java/jdbc_test.clj | 21 +++++++++++++-------- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/deps.edn b/deps.edn index 4f47ceda..1dfbff85 100644 --- a/deps.edn +++ b/deps.edn @@ -6,17 +6,15 @@ :aliases {:test {:extra-paths ["src/test/clojure"] :extra-deps {org.clojure/test.check {:mvn/version "0.9.0"} - ;; Note: 1.12.1.1 is used in pom.xml for Java 6/7 compat - org.apache.derby/derby {:mvn/version "10.13.1.1"} - org.hsqldb/hsqldb {:mvn/version "2.3.4"} - ;; Note: 1.4.191 is used in pom.xml for Java 6 compat - com.h2database/h2 {:mvn/version "1.4.193"} + org.apache.derby/derby {:mvn/version "10.14.2.0"} + org.hsqldb/hsqldb {:mvn/version "2.4.1"} + com.h2database/h2 {:mvn/version "1.4.197"} net.sourceforge.jtds/jtds {:mvn/version "1.3.1"} ;; Note: Tests fail with 6.0.2+ driver mysql/mysql-connector-java {:mvn/version "5.1.41"} - org.postgresql/postgresql {:mvn/version "9.4.1212.jre7"} + org.postgresql/postgresql {:mvn/version "42.2.2.jre7"} com.impossibl.pgjdbc-ng/pgjdbc-ng {:mvn/version "0.7.1"} - org.xerial/sqlite-jdbc {:mvn/version "3.16.1"} + org.xerial/sqlite-jdbc {:mvn/version "3.23.1"} ;; Note: Assumes Java 8; there's a .jre7 version as well com.microsoft.sqlserver/mssql-jdbc {:mvn/version "6.2.2.jre8"}}} :1.7 {:override-deps {org.clojure/clojure {:mvn/version "1.7.0"}}} diff --git a/pom.xml b/pom.xml index 72e15556..0bba63c8 100644 --- a/pom.xml +++ b/pom.xml @@ -72,31 +72,31 @@ org.apache.derby derby - 10.12.1.1 + 10.14.2.0 test org.hsqldb hsqldb - 2.3.4 + 2.4.1 test com.h2database h2 - 1.4.191 + 1.4.197 test org.postgresql postgresql - 9.4.1212.jre7 + 42.2.2.jre7 test org.xerial sqlite-jdbc - 3.16.1 + 3.23.1 test diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 18ca8f32..9d3668ee 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -241,7 +241,7 @@ (case (db-type db) "derby" {(keyword "1") nil} ("hsql" "hsqldb") nil - ("h2" "h2:mem") nil + ("h2" "h2:mem") {:id 0} "mysql" {:generated_key k} nil (if (mysql? db) ; string-based tests {:generated_key k} @@ -381,7 +381,9 @@ (with-open [con (sql/get-connection db)] (let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )" {:return-keys ["id"]})] - (is (= (returned-key db 1) ((select-key db) (sql/db-do-prepared-return-keys db stmt)))))) + ;; HSQLDB returns the named key if you ask + (is (= (if (hsqldb? db) {:id 0} (returned-key db 1)) + ((select-key db) (sql/db-do-prepared-return-keys db stmt)))))) (is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))) (deftest test-do-prepared2 @@ -575,10 +577,12 @@ (let [sql-stmt (str "INSERT INTO fruit ( name, appearance, cost ) " "VALUES ( ?, ?, ? )") selector (select-key db)] - (is (= (returned-key db 1) + ;; HSQLDB returns the named key if you ask + (is (= (if (hsqldb? db) {:id 0} (returned-key db 1)) (selector (sql/execute! db [sql-stmt "Apple" "Green" 75] {:return-keys ["id"]})))) - (is (= (returned-key db 2) + ;; HSQLDB returns the named key if you ask + (is (= (if (hsqldb? db) {:id 0} (returned-key db 2)) (sql/execute! db [sql-stmt "Pear" "Yellow" 99] {:return-keys ["id"] :row-fn selector}))))) @@ -943,8 +947,9 @@ "sqlite" (is (= [(returned-key db 2)] new-keys)) ;; Derby returns a single row count "derby" (is (= [(returned-key db 1)] new-keys)) - ;; H2 returns nothing useful - ("h2" "h2:mem") (is (= [] new-keys)) + ;; H2 returns dummy keys + ("h2" "h2:mem") + (is (= [(returned-key db 1) (returned-key db 2)] new-keys)) ;; HSQL returns nothing useful "hsql" (is (= [] new-keys)) ;; MS SQL returns row counts @@ -983,8 +988,8 @@ "sqlite" (is (= 1 n)) ;; Derby returns a single row count "derby" (is (= 1 n)) - ;; H2 returns nothing useful - ("h2" "h2:mem") (is (= 0 n)) + ;; H2 returns (zero) keys now + ("h2" "h2:mem") (is (= 2 n)) ;; HSQL returns nothing useful "hsql" (is (= 0 n)) ;; MS SQL returns row counts (we still apply result-set-fn) From 1482f8388b1e680c5fbda8698fa84ce12fcd98af Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 3 Jul 2018 11:15:05 -0700 Subject: [PATCH 562/630] Remove misleading portion of namespace docstring --- src/main/clojure/clojure/java/jdbc.clj | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index ca805140..5973b24f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -32,9 +32,7 @@ data. Results can be processed using any standard sequence operations. For most operations, Java's PreparedStatement is used so your SQL and parameters can be represented as simple vectors where the first element is the SQL string, with ? for each parameter, and the remaining elements -are the parameter values to be substituted. In general, operations return -the number of rows affected, except for a single record insert where any -generated keys are returned (as a map). +are the parameter values to be substituted. For more documentation, see: From ee1ebac6ffbe09810659541c6e68d3b1b190cd55 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 10 Aug 2018 20:29:59 -0700 Subject: [PATCH 563/630] JDBC-171 allow with-db-connection/with-db-metadata to be nested --- CHANGES.md | 4 +++ README.md | 4 +-- src/main/clojure/clojure/java/jdbc.clj | 16 +++++++---- src/test/clojure/clojure/java/jdbc_test.clj | 32 ++++++++++++++++++++- 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0590d2f4..98edbc05 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.8 + +* Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). + Changes in 0.7.7 * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). diff --git a/README.md b/README.md index 80e8f0f5..c3124ae3 100644 --- a/README.md +++ b/README.md @@ -139,8 +139,8 @@ Change Log ==================== * Release 0.7.7 on 2018-06-23 - * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). - * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). + * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). + * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). * Release 0.7.6 on 2018-04-24 * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5973b24f..08b85f2f 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -831,9 +831,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ... con-db ...)" [binding & body] `(let [db-spec# ~(second binding) opts# ~(or (second (rest binding)) {})] - (with-open [con# (get-connection db-spec# opts#)] - (let [~(first binding) (add-connection db-spec# con#)] - ~@body)))) + (if (db-find-connection db-spec#) + (let [~(first binding) db-spec#] + ~@body) + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (add-connection db-spec# con#)] + ~@body))))) (defmacro with-db-metadata "Evaluates body in the context of an active connection with metadata bound @@ -843,9 +846,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ... md ...)" [binding & body] `(let [db-spec# ~(second binding) opts# ~(or (second (rest binding)) {})] - (with-open [con# (get-connection db-spec# opts#)] + (if-let [con# (db-find-connection db-spec#)] (let [~(first binding) (.getMetaData con#)] - ~@body)))) + ~@body) + (with-open [con# (get-connection db-spec# opts#)] + (let [~(first binding) (.getMetaData con#)] + ~@body))))) (defn- process-result-set "Given a Java ResultSet and options, produce a processed result-set-seq, diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 9d3668ee..03321782 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -590,6 +590,16 @@ (is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99] {:row-fn :name :result-set-fn first})))))) +(deftest test-nested-with-connection + (doseq [db (test-specs)] + (create-test-table :fruit db) + (sql/with-db-connection [conn1 db] + (sql/query conn1 "select * from fruit") + (sql/with-db-connection [conn2 conn1] + (sql/query conn2 "select * from fruit")) + ;; JDBC-171 bug: this blows up because with-db-connection won't nest + (is (= [] (sql/query conn1 "select * from fruit")))))) + (deftest test-update-values (doseq [db (test-specs)] (create-test-table :fruit db) @@ -876,7 +886,27 @@ (is (= "fruit" (-> table-info first :table_name - clojure.string/lower-case))))))) + clojure.string/lower-case))))) + (sql/with-db-connection [conn db] + (sql/with-db-metadata [metadata conn {}] + (let [table-info (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case))))) + ;; JDBC-171 this used to blow up because the connnection is closed + (sql/with-db-metadata [metadata conn {}] + (let [table-info (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case)))))))) (deftest test-metadata-managed-computed (doseq [db (test-specs)] From fb5e44a399974311710519537fcb3e0d88c75d04 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 12 Aug 2018 16:40:56 -0700 Subject: [PATCH 564/630] JDBC-172 support updated MySQL driver --- src/main/clojure/clojure/java/jdbc.clj | 56 +++++++++++++++++--------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5973b24f..462189b4 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -148,13 +148,19 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (def ^:private classnames "Map of subprotocols to classnames. dbtype specifies one of these keys. - The subprotocols map below provides aliases for dbtype." + + The subprotocols map below provides aliases for dbtype. + + Most databases have just a single class name for their driver but we + support a sequence of class names to try in order to allow for drivers + that change their names over time (e.g., MySQL)." {"derby" "org.apache.derby.jdbc.EmbeddedDriver" "h2" "org.h2.Driver" "h2:mem" "org.h2.Driver" "hsqldb" "org.hsqldb.jdbcDriver" "jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver" - "mysql" "com.mysql.jdbc.Driver" + "mysql" ["com.mysql.cj.jdbc.Driver" + "com.mysql.jdbc.Driver"] "oracle:oci" "oracle.jdbc.OracleDriver" "oracle:thin" "oracle.jdbc.OracleDriver" "postgresql" "org.postgresql.Driver" @@ -224,6 +230,30 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (.setReadOnly connection (boolean (:read-only? opts)))) connection) +(defn- get-driver-connection + "Common logic for loading the DriverManager and the designed JDBC driver + class and obtaining the appropriate Connection object." + [classname subprotocol db-spec url etc opts error-msg] + (if-let [class-name (or classname (classnames subprotocol))] + (do + ;; force DriverManager to be loaded + (DriverManager/getLoginTimeout) + (if (string? class-name) + (clojure.lang.RT/loadClassForName class-name) + (loop [[clazz & more] class-name] + (when-let [load-failure + (try + (clojure.lang.RT/loadClassForName clazz) + nil + (catch Exception e + e))] + (if (seq more) + (recur more) + (throw load-failure)))))) + (throw (ex-info error-msg db-spec))) + (-> (DriverManager/getConnection url (as-properties etc)) + (modify-connection opts))) + (defn get-connection "Creates a connection to a database. db-spec is usually a map containing connection parameters but can also be a URI or a String. @@ -359,28 +389,18 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (when port (str ":" port)) db-sep dbname)) etc (dissoc db-spec :dbtype :dbname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown dbtype: " dbtype) db-spec))) - (-> (DriverManager/getConnection url (as-properties etc)) - (modify-connection opts))) + (get-driver-connection classname subprotocol db-spec + url etc opts + (str "Unknown dbtype: " dbtype))) (and subprotocol subname) (let [;; allow aliases for subprotocols subprotocol (subprotocols subprotocol subprotocol) url (format "jdbc:%s:%s" subprotocol subname) etc (dissoc db-spec :classname :subprotocol :subname)] - (if-let [class-name (or classname (classnames subprotocol))] - (do - ;; force DriverManager to be loaded - (DriverManager/getLoginTimeout) - (clojure.lang.RT/loadClassForName class-name)) - (throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec))) - (-> (DriverManager/getConnection url (as-properties etc)) - (modify-connection opts))) + (get-driver-connection classname subprotocol db-spec + url etc opts + (str "Unknown subprotocol: " subprotocol))) name (or (when-available javax.naming.InitialContext From f9d480a1ad9f2ffe4218e2d460bfd90a60d18192 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 12 Aug 2018 16:47:53 -0700 Subject: [PATCH 565/630] JDBC-172 update changes --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 98edbc05..749da619 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.8 +* Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). * Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). Changes in 0.7.7 From d19865ee1811d17db8aac1820ebc8996c55b54c1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 13 Aug 2018 10:26:13 -0700 Subject: [PATCH 566/630] Prep for 0.7.8 release --- CHANGES.md | 2 +- README.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 749da619..f455fa84 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.8 +Changes in 0.7.8 * Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). * Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). diff --git a/README.md b/README.md index c3124ae3..8ac755c8 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,10 @@ Developer Information Change Log ==================== +* Release 0.7.8 on 2018-08-13 + * Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). + * Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). + * Release 0.7.7 on 2018-06-23 * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). From f79a5ae4d22a20441fb3b2f0cf52341d4b727e8a Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 13 Aug 2018 10:28:46 -0700 Subject: [PATCH 567/630] Update README for 0.7.8 release --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8ac755c8..23c13ceb 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.7 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.8 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -32,14 +32,14 @@ Latest stable release: 0.7.7 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.7"] +[org.clojure/java.jdbc "0.7.8"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.7 + 0.7.8 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ From 49a033aef3254e46d23fe916e1aff04300143ebd Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 13 Aug 2018 12:29:57 -0500 Subject: [PATCH 568/630] [maven-release-plugin] prepare release java.jdbc-0.7.8 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0bba63c8..917e69e0 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.8-SNAPSHOT + 0.7.8 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.8 From f5ce75b8fb0370a2a4763524e9de5a0b9174835d Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 13 Aug 2018 12:29:57 -0500 Subject: [PATCH 569/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 917e69e0..52846e16 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.8 + 0.7.9-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.8 + HEAD From efe67919d532fda028c7f051f7f57991afba4bf2 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 28 Oct 2018 13:01:42 -0700 Subject: [PATCH 570/630] JDBC-173 oracle:sid support Cleans up port and dbname separator lookup. --- src/main/clojure/clojure/java/jdbc.clj | 38 ++++++++++++++++---------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a83ee1b8..a2a0b378 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -171,11 +171,12 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (def ^:private subprotocols "Map of schemes to subprotocols. Used to provide aliases for dbtype." - {"hsql" "hsqldb" - "jtds" "jtds:sqlserver" - "mssql" "sqlserver" - "oracle" "oracle:thin" - "postgres" "postgresql"}) + {"hsql" "hsqldb" + "jtds" "jtds:sqlserver" + "mssql" "sqlserver" + "oracle" "oracle:thin" + "oracle:sid" "oracle:thin" + "postgres" "postgresql"}) (def ^:private host-prefixes "Map of subprotocols to non-standard host-prefixes. @@ -183,6 +184,22 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} {"oracle:oci" "@" "oracle:thin" "@"}) +(def ^:private ports + "Map of subprotocols to ports." + {"jtds:sqlserver" 1433 + "mysql" 3306 + "oracle:oci" 1521 + "oracle:sid" 1521 + "oracle:thin" 1521 + "postgresql" 5432 + "sqlserver" 1433}) + +(def ^:private dbname-separators + "Map of schemes to separators. The default is / but a couple are different." + {"mssql" ";DATABASENAME=" + "sqlserver" ";DATABASENAME=" + "oracle:sid" ":"}) + (defn- parse-properties-uri [^URI uri] (let [host (.getHost uri) port (if (pos? (.getPort uri)) (.getPort uri)) @@ -369,15 +386,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (let [;; allow aliases for dbtype subprotocol (subprotocols dbtype dbtype) host (or host "127.0.0.1") - port (or port (condp = subprotocol - "jtds:sqlserver" 1433 - "mysql" 3306 - "oracle:oci" 1521 - "oracle:thin" 1521 - "postgresql" 5432 - "sqlserver" 1433 - nil)) - db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/") + port (or port (ports subprotocol)) + db-sep (dbname-separators dbtype "/") url (cond (= "h2:mem" dbtype) (str "jdbc:" subprotocol ":" dbname ";DB_CLOSE_DELAY=-1") (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol) From 2fc16eb17f6af621dca12e60a094d4acb1d59b64 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 28 Oct 2018 13:05:47 -0700 Subject: [PATCH 571/630] Document upcoming JDBC-173 fix --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index f455fa84..8bdcdb71 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.9 + +* Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://dev.clojure.org/jira/browse/JDBC-173). + Changes in 0.7.8 * Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). From e5d6183395e23c9b7b78fa20ac6d0ddba6074807 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 29 Oct 2018 17:57:17 -0700 Subject: [PATCH 572/630] Add Pull Request Template --- .github/PULL_REQUEST_TEMPLATE | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE new file mode 100644 index 00000000..0a5c486a --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE @@ -0,0 +1,14 @@ +Hi! Thanks for your interest in contributing to this project. + +Clojure contrib projects do not use GitHub issues or pull requests, and +require a signed Contributor Agreement. If you would like to contribute, +please read more about the CA and sign that first (this can be done online). + +Then go to this project's issue tracker in JIRA to create tickets, update +tickets, or submit patches. For help in creating tickets and patches, +please see: + +- Signing the CA: https://dev.clojure.org/display/community/Contributing+FAQ +- Creating Tickets: https://dev.clojure.org/display/community/Creating+Tickets +- Developing Patches: https://dev.clojure.org/display/community/Developing+Patches +- Contributing FAQ: https://dev.clojure.org/display/community/Contributing+FAQ From ccf9be463e0c4073646423e239a32009da48b24b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 30 Nov 2018 11:18:16 -0800 Subject: [PATCH 573/630] Add clojure.java.jdbc.datafy --- src/main/clojure/clojure/java/jdbc/datafy.clj | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 src/main/clojure/clojure/java/jdbc/datafy.clj diff --git a/src/main/clojure/clojure/java/jdbc/datafy.clj b/src/main/clojure/clojure/java/jdbc/datafy.clj new file mode 100644 index 00000000..a68ca747 --- /dev/null +++ b/src/main/clojure/clojure/java/jdbc/datafy.clj @@ -0,0 +1,143 @@ +;; Copyright (c) 2008-2018 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; The use and distribution terms for this software are covered by +;; the Eclipse Public License 1.0 +;; (http://opensource.org/licenses/eclipse-1.0.php) which can be +;; found in the file epl-v10.html at the root of this distribution. +;; By using this software in any fashion, you are agreeing to be +;; bound by the terms of this license. You must not remove this +;; notice, or any other, from this software. +;; +;; datafy.clj +;; +;; Exploring datafy and nav for JDBC databases + +(ns + ^{:author "Sean Corfield", + :doc "Variants of 'query' functions from clojure.java.jdbc that support + the new clojure.datafy functionality in Clojure 1.10."} + clojure.java.jdbc.datafy + (:require [clojure.core.protocols :as p] + [clojure.datafy :as d] + [clojure.java.jdbc :as jdbc])) + +(declare datafy-result-set) +(declare datafy-row) + +(defn- default-schema + "The default schema lookup rule for column names. + + If a column name ends with _id or id, it is assumed to be a foreign key + into the table identified by the first part of the column name." + [col] + (let [[_ table] (re-find #"^(.*)_?id$" (name col))] + (when table + [(keyword table) :id]))) + +(defn- schema-opt + "Returns the schema 'option'. + + As with other clojure.java.jdbc options, it can be provided in the db-spec + hash map or in the options for a particular function call. + + A schema can a simple map from column names to pairs of table name and + the key column to be used in that table. A schema can also be a function + that is called with column names and should return nil if the column is + not to be treated as a foreign key, or a pair of table name and the key + column within that table." + [db-spec opts] + (:schema (merge {:schema default-schema} + (when (map? db-spec) db-spec) + opts))) + +(defn- navize-row [db-spec opts row] + "Given a db-spec, a map of options, and a row -- a hash map -- return the + row with metadata that provides navigation via foreign keys." + (let [schema (schema-opt db-spec opts)] + (with-meta row + {`p/nav (fn [coll k v] + (let [[table fk cardinality] (schema k)] + (if fk + (if (= :many cardinality) + (datafy-result-set db-spec opts + (jdbc/find-by-keys db-spec table {fk v})) + (datafy-row db-spec opts + (jdbc/get-by-id db-spec table v fk))) + v)))}))) + +(defn- datafy-row [db-spec opts row] + "Given a db-spec, a map of options, and a row -- a hash map -- return the + row with metadata that provides datafication (which in turn provides). + navigation)." + (with-meta row {`p/datafy (partial navize-row db-spec opts)})) + +(defn- datafy-result-set [db-spec opts rs] + "Given a db-spec, a map of options, and a result set -- a sequence of hash + maps that represent rows -- return a sequence of datafiable rows." + (mapv (partial datafy-row db-spec opts) rs)) + +(defn get-by-id + "Given a database connection, a table name, a primary key value, an + optional primary key column name, and an optional options map, return + a single matching row, or nil. + The primary key column name defaults to :id." + ([db table pk-value] (get-by-id db table pk-value :id {})) + ([db table pk-value pk-name-or-opts] + (if (map? pk-name-or-opts) + (get-by-id db table pk-value :id pk-name-or-opts) + (get-by-id db table pk-value pk-name-or-opts {}))) + ([db table pk-value pk-name opts] + (datafy-row db opts + (jdbc/get-by-id db table pk-value pk-name opts)))) + +(defn find-by-keys + "Given a database connection, a table name, a map of column name/value + pairs, and an optional options map, return any matching rows. + + An :order-by option may be supplied to sort the rows, e.g., + + {:order-by [{:name :asc} {:age :desc} {:income :asc}]} + ;; equivalent to: + {:order-by [:name {:age :desc} :income]} + + The :order-by value is a sequence of column names (to sort in ascending + order) and/or maps from column names to directions (:asc or :desc). The + directions may be strings or keywords and are not case-sensitive. They + are mapped to ASC or DESC in the generated SQL. + + Note: if a ordering map has more than one key, the order of the columns + in the generated SQL ORDER BY clause is unspecified (so such maps should + only contain one key/value pair)." + ([db table columns] (find-by-keys db table columns {})) + ([db table columns opts] + (datafy-result-set db opts + (jdbc/find-by-keys db table columns opts)))) + +(defn query + "Given a database connection and a vector containing SQL and optional parameters, + perform a simple database query. The options specify how to construct the result + set (and are also passed to prepare-statement as needed): + :as-arrays? - return the results as a set of arrays, default false. + :identifiers - applied to each column name in the result set, default lower-case + :keywordize? - defaults to true, can be false to opt-out of converting + identifiers to keywords + :qualifier - optionally provides the namespace qualifier for identifiers + :result-set-fn - applied to the entire result set, default doall / vec + if :as-arrays? true, :result-set-fn will default to vec + if :as-arrays? false, :result-set-fn will default to doall + :row-fn - applied to each row as the result set is constructed, default identity + The second argument is a vector containing a SQL string or PreparedStatement, followed + by any parameters it needs. + See also prepare-statement for additional options." + ([db sql-params] (query db sql-params {})) + ([db sql-params opts] + (datafy-result-set db opts + (jdbc/query db sql-params opts)))) + +(comment + (def db-spec {:dbtype "derby" :dbname "datafy" :create true}) + (jdbc/db-do-commands db-spec (jdbc/create-table-ddl :fruit [[:id :int] [:name "varchar(256)"]])) + (jdbc/db-do-commands db-spec (jdbc/create-table-ddl :fruit2 [[:fruitid :int] [:name "varchar(256)"]])) + (jdbc/insert! db-spec :fruit {:id 1 :name "First fruit"}) + (jdbc/insert! db-spec :fruit2 {:fruitid 1 :name "First fruit"}) + (jdbc/insert! db-spec :fruit {:id 2 :name "Second fruit"}) + (jdbc/insert! db-spec :fruit2 {:fruitid 2 :name "More fruit"})) From 742b52674ed66427d9f5d9b8c2591ddd219db476 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 30 Nov 2018 11:22:52 -0800 Subject: [PATCH 574/630] Make nav operation more robust --- src/main/clojure/clojure/java/jdbc/datafy.clj | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/datafy.clj b/src/main/clojure/clojure/java/jdbc/datafy.clj index a68ca747..fd4af004 100644 --- a/src/main/clojure/clojure/java/jdbc/datafy.clj +++ b/src/main/clojure/clojure/java/jdbc/datafy.clj @@ -57,11 +57,16 @@ {`p/nav (fn [coll k v] (let [[table fk cardinality] (schema k)] (if fk - (if (= :many cardinality) - (datafy-result-set db-spec opts - (jdbc/find-by-keys db-spec table {fk v})) - (datafy-row db-spec opts - (jdbc/get-by-id db-spec table v fk))) + (try + (if (= :many cardinality) + (datafy-result-set db-spec opts + (jdbc/find-by-keys db-spec table {fk v})) + (datafy-row db-spec opts + (jdbc/get-by-id db-spec table v fk))) + (catch Exception _ + ;; assume an exception means we just cannot + ;; navigate anywhere, so return just the value + v)) v)))}))) (defn- datafy-row [db-spec opts row] From e066db9bc51e92dd3c798db863347d1a095ab19c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 30 Nov 2018 12:17:33 -0800 Subject: [PATCH 575/630] Expand ns docstring to provide guidance/caveats on the schema 'lookup' machinery --- src/main/clojure/clojure/java/jdbc/datafy.clj | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/main/clojure/clojure/java/jdbc/datafy.clj b/src/main/clojure/clojure/java/jdbc/datafy.clj index fd4af004..9d4481a9 100644 --- a/src/main/clojure/clojure/java/jdbc/datafy.clj +++ b/src/main/clojure/clojure/java/jdbc/datafy.clj @@ -14,10 +14,32 @@ (ns ^{:author "Sean Corfield", :doc "Variants of 'query' functions from clojure.java.jdbc that support - the new clojure.datafy functionality in Clojure 1.10."} + the new clojure.datafy functionality in Clojure 1.10. + + The whole schema/column lookup piece is very likely to change! + + Currently, the :schema option for a 'query' function is a mapping + from column name to a tuple of table name, key column, and optionally + the cardinality (:one -- the default -- or :many). The cardinality + determines whether navigation should produce a single row (hash map) + or a result set. + + One of the problems is that the general case -- query -- doesn't + have any concept of an associated table name (and may of course + join across multiple tables), so there's no good way to take the + table name into account when mapping a column to another table. + + For find-by-keys and get-by-id, you do have the starting table + name so you could map [table1 column1] to [table2 column2] and have + table-specific mappings. + + The obvious, logical thing would be to use SQL metadata to figure + out actual foreign key constraints but not everyone uses them, for + a variety of reasons. For folks who do use them, they can build + their schema structure from the database, and pass the relevant + part of it to the functions below (via :schema in options)."} clojure.java.jdbc.datafy (:require [clojure.core.protocols :as p] - [clojure.datafy :as d] [clojure.java.jdbc :as jdbc])) (declare datafy-result-set) @@ -137,12 +159,3 @@ ([db sql-params opts] (datafy-result-set db opts (jdbc/query db sql-params opts)))) - -(comment - (def db-spec {:dbtype "derby" :dbname "datafy" :create true}) - (jdbc/db-do-commands db-spec (jdbc/create-table-ddl :fruit [[:id :int] [:name "varchar(256)"]])) - (jdbc/db-do-commands db-spec (jdbc/create-table-ddl :fruit2 [[:fruitid :int] [:name "varchar(256)"]])) - (jdbc/insert! db-spec :fruit {:id 1 :name "First fruit"}) - (jdbc/insert! db-spec :fruit2 {:fruitid 1 :name "First fruit"}) - (jdbc/insert! db-spec :fruit {:id 2 :name "Second fruit"}) - (jdbc/insert! db-spec :fruit2 {:fruitid 2 :name "More fruit"})) From 3e0e693d620c98aa80eda417a69d405e65cf808e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 2 Dec 2018 17:59:31 -0800 Subject: [PATCH 576/630] Update copyright --- src/main/clojure/clojure/java/jdbc/datafy.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/datafy.clj b/src/main/clojure/clojure/java/jdbc/datafy.clj index 9d4481a9..720520e3 100644 --- a/src/main/clojure/clojure/java/jdbc/datafy.clj +++ b/src/main/clojure/clojure/java/jdbc/datafy.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2018 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2018 Sean Corfield. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be From 79ad004b42e9234d2bbf54df6a254c22b1c68c72 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 10 Dec 2018 14:14:58 -0800 Subject: [PATCH 577/630] Fix JDBC-175 Make regex non-greedy --- src/main/clojure/clojure/java/jdbc/datafy.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc/datafy.clj b/src/main/clojure/clojure/java/jdbc/datafy.clj index 720520e3..10d61adc 100644 --- a/src/main/clojure/clojure/java/jdbc/datafy.clj +++ b/src/main/clojure/clojure/java/jdbc/datafy.clj @@ -51,7 +51,7 @@ If a column name ends with _id or id, it is assumed to be a foreign key into the table identified by the first part of the column name." [col] - (let [[_ table] (re-find #"^(.*)_?id$" (name col))] + (let [[_ table] (re-find #"^(.*?)_?id$" (name col))] (when table [(keyword table) :id]))) From cbe253f6644589c413bd94d540d27398d3f64dd1 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 10 Dec 2018 14:15:30 -0800 Subject: [PATCH 578/630] Remove old debug code --- src/main/clojure/clojure/java/jdbc.clj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index a2a0b378..efcf4fba 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1076,7 +1076,6 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} "Given a db-spec, a SQL statement (or a prepared statement), a set of parameters, a result set processing function and options, execute the query." [db sql params func opts] - #_(println "\nquery" sql params) (if (instance? PreparedStatement sql) (let [^PreparedStatement stmt sql] (execute-query-with-params From 4a4bab03cf665246223d09e763c6f04d027a7d63 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 7 Jan 2019 13:33:58 -0800 Subject: [PATCH 579/630] Fix JDBC-176 --- CHANGES.md | 1 + deps.edn | 3 ++- run-tests.sh | 2 +- src/main/clojure/clojure/java/jdbc.clj | 2 +- src/test/clojure/clojure/java/jdbc_test.clj | 3 ++- 5 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 8bdcdb71..0bb5c9ea 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.9 +* Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://dev.clojure.org/jira/browse/JDBC-176). * Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://dev.clojure.org/jira/browse/JDBC-173). Changes in 0.7.8 diff --git a/deps.edn b/deps.edn index 1dfbff85..b09bc738 100644 --- a/deps.edn +++ b/deps.edn @@ -20,7 +20,8 @@ :1.7 {:override-deps {org.clojure/clojure {:mvn/version "1.7.0"}}} :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} - :master {:override-deps {org.clojure/clojure {:mvn/version "1.10.0-master-SNAPSHOT"}}} + :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.0"}}} + :master {:override-deps {org.clojure/clojure {:mvn/version "1.11.0-master-SNAPSHOT"}}} :perf {:extra-paths ["src/perf/clojure"] :extra-deps {criterium {:mvn/version "0.4.4"}} :jvm-opts ["-server" diff --git a/run-tests.sh b/run-tests.sh index c628aa48..f4325f09 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -44,7 +44,7 @@ dbs="derby h2 hsqldb sqlite" # Start with clean databases each time to avoid slowdown rm -rf clojure_test_* -versions="1.7 1.8 1.9 master" +versions="1.7 1.8 1.9 1.10 master" for v in $versions do TEST_DBS="$dbs $*" clj -A:test:runner:$v diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index efcf4fba..95ffc27c 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -958,7 +958,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (^{:once true} fn* [] (let [counts (if multi? (.executeBatch stmt) - (.executeUpdate stmt))] + (vector (.executeUpdate stmt)))] (try (let [rs (.getGeneratedKeys stmt) result (cond multi? diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 03321782..3f3607ba 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -68,7 +68,8 @@ (def mysql-db {:dbtype "mysql" :dbname "clojure_test" :user "clojure_test" - :password "clojure_test"}) + :password "clojure_test" + :useSSL false}) (def derby-db {:dbtype "derby" :dbname "clojure_test_derby" From 022a1fdcac870f4b39f27603d30d82e815f84a3b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 21 Feb 2019 10:09:04 -0800 Subject: [PATCH 580/630] Minor tweak to perf tests Add another baseline test with a `PreparedStatement`. --- src/perf/clojure/clojure/java/perf_jdbc.clj | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/perf/clojure/clojure/java/perf_jdbc.clj b/src/perf/clojure/clojure/java/perf_jdbc.clj index f104db4b..7e2cdffd 100644 --- a/src/perf/clojure/clojure/java/perf_jdbc.clj +++ b/src/perf/clojure/clojure/java/perf_jdbc.clj @@ -14,6 +14,8 @@ $ clj -A:test:perf Clojure 1.9.0 + user=> (require '[clojure.java.perf-jdbc :as p]) + nil user=> (p/calibrate) ... nil @@ -140,11 +142,16 @@ (assert (= "Apple" (select db))) (cc/quick-bench (select db))) + (println "Basic select first rs...") + (let [db db] + (cc/quick-bench (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] + {:result-set-fn first :qualifier "fruit"}))) + (println "Select with prepared statement...") (let [con (:connection db)] (with-open [ps (sql/prepare-statement con "SELECT * FROM fruit WHERE appearance = ?")] (assert (= "Apple" (select-p db ps))) - (cc/quick-bench (select db)))) + (cc/quick-bench (select-p db ps)))) (println "Reducible query...") (let [db db From 8deaebc87b1c6ce20e1481a835d11158cbb2e3f6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 21 Feb 2019 10:23:03 -0800 Subject: [PATCH 581/630] JDBC-174 and JDBC-175 added to CHANGES.md Documents rewrite batched statement options in `insert-multi!` and new `clojure.java.jdbc.datafy` namespace (experimental). --- CHANGES.md | 4 +++- src/main/clojure/clojure/java/jdbc.clj | 15 +++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0bb5c9ea..e6d39412 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ -Changes coming in 0.7.9 +Changes in 0.7.9 * Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://dev.clojure.org/jira/browse/JDBC-176). +* Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://dev.clojure.org/jira/browse/JDBC-175). +* Add note about rewriting batched operations to `insert-multi!` for some drivers [JDBC-174](https://dev.clojure.org/jira/browse/JDBC-174). * Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://dev.clojure.org/jira/browse/JDBC-173). Changes in 0.7.8 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 95ffc27c..6b75b8de 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2008-2018 Sean Corfield, Stephen C. Gilardi. All rights reserved. +;; Copyright (c) 2008-2019 Sean Corfield, Stephen C. Gilardi. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be @@ -1612,9 +1612,16 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} When inserting rows as a sequence of lists of column values, the result is a sequence of the counts of rows affected (a sequence of 1's), if available. Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch! - A single database operation is used to insert all the rows at once. This may - be much faster than inserting a sequence of rows (which performs an insert for - each map in the sequence). + A single database operation should be used to insert all the rows at once. + This may be much faster than inserting a sequence of rows (which performs an + insert for each map in the sequence). + + Note: some database drivers need to be told to rewrite the SQL for this to + be performed as a single, batched operation. In particular, PostgreSQL + requires :reWriteBatchedInserts true and My SQL requires + :rewriteBatchedStatement true (both non-standard JDBC options, of course!). + These options should be passed into the driver when the connection is + created (however that is done in your program). The :transaction? option specifies whether to run in a transaction or not. The default is true (use a transaction). The :entities option specifies how From b2b7c70a39887ba00ef71c11ece5905192df5b87 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 21 Feb 2019 10:30:26 -0800 Subject: [PATCH 582/630] Prep for 0.7.9 release --- README.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 23c13ceb..0124a8ac 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.8 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.9 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -32,14 +32,14 @@ Latest stable release: 0.7.8 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.8"] +[org.clojure/java.jdbc "0.7.9"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.8 + 0.7.9 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -138,6 +138,12 @@ Developer Information Change Log ==================== +* Release 0.7.9 on 2019-02-21 + * Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://dev.clojure.org/jira/browse/JDBC-176). + * Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://dev.clojure.org/jira/browse/JDBC-175). + * Add note about rewriting batched operations to `insert-multi!` for some drivers [JDBC-174](https://dev.clojure.org/jira/browse/JDBC-174). + * Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://dev.clojure.org/jira/browse/JDBC-173). + * Release 0.7.8 on 2018-08-13 * Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). * Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). From ae39e94c71ddbe40c42f740a81c181a83b380b6a Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 21 Feb 2019 12:33:50 -0600 Subject: [PATCH 583/630] [maven-release-plugin] prepare release java.jdbc-0.7.9 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 52846e16..608d1fbc 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.9-SNAPSHOT + 0.7.9 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.9 From 8495acde705949a3f85409973b3c7eedc65628d7 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Thu, 21 Feb 2019 12:33:50 -0600 Subject: [PATCH 584/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 608d1fbc..2e00343f 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.9 + 0.7.10-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.9 + HEAD From 2374ea2dd85b2895dd98bc1d5a04aa0699e41d8d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 1 Mar 2019 14:12:38 -0800 Subject: [PATCH 585/630] JDBC-177 allow numbers in column specs in create-table-ddl --- .joker | 3 ++ CHANGES.md | 4 ++ src/main/clojure/clojure/java/jdbc.clj | 3 +- src/main/clojure/clojure/java/jdbc/spec.clj | 6 ++- src/test/clojure/clojure/java/jdbc_test.clj | 60 +++++++++++++-------- 5 files changed, 51 insertions(+), 25 deletions(-) create mode 100644 .joker diff --git a/.joker b/.joker new file mode 100644 index 00000000..0fd26273 --- /dev/null +++ b/.joker @@ -0,0 +1,3 @@ +{:known-macros [clojure.java.jdbc/with-db-connection + clojure.java.jdbc/with-db-metadata + clojure.java.jdbc/with-db-transaction]} diff --git a/CHANGES.md b/CHANGES.md index e6d39412..fc546d6c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes coming in 0.7.10 + +* Relax restriction on `create-table-ddl` column specs to allow numbers (as well as keywords and strings) [JDBC-177](https://dev.clojure.org/jira/browse/JDBC-177). + Changes in 0.7.9 * Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://dev.clojure.org/jira/browse/JDBC-176). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 6b75b8de..903e814d 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -1692,10 +1692,11 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} entities (:entities opts identity) table-name (as-sql-name entities table) table-spec-str (or (and table-spec (str " " table-spec)) "") + stringify (fn [x] (if (keyword? x) (name x) (str x))) spec-to-string (fn [spec] (try (str/join " " (cons (as-sql-name entities (first spec)) - (map name (rest spec)))) + (map stringify (rest spec)))) (catch Exception _ (throw (IllegalArgumentException. "column spec is not a sequence of keywords / strings")))))] diff --git a/src/main/clojure/clojure/java/jdbc/spec.clj b/src/main/clojure/clojure/java/jdbc/spec.clj index 2a93a059..eca21eaa 100644 --- a/src/main/clojure/clojure/java/jdbc/spec.clj +++ b/src/main/clojure/clojure/java/jdbc/spec.clj @@ -1,4 +1,4 @@ -;; Copyright (c) 2016-2017 Sean Corfield. All rights reserved. +;; Copyright (c) 2016-2019 Sean Corfield. All rights reserved. ;; The use and distribution terms for this software are covered by ;; the Eclipse Public License 1.0 ;; (http://opensource.org/licenses/eclipse-1.0.php) which can be @@ -407,7 +407,9 @@ :opts (s/? ::exec-sql-options)) :ret ::execute-result) -(s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword? :str string?)))) +(s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword? + :str string? + :num number?)))) (s/fdef sql/create-table-ddl :args (s/cat :table ::identifier diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 3f3607ba..f01de14c 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -21,7 +21,7 @@ ;; Migrated from clojure.contrib.test-sql 17 April 2011 (ns clojure.java.jdbc-test - (:require [clojure.test :refer :all] + (:require [clojure.test :refer [deftest is use-fixtures]] [clojure.java.jdbc :as sql] [clojure.string :as str])) @@ -887,27 +887,27 @@ (is (= "fruit" (-> table-info first :table_name - clojure.string/lower-case))))) - (sql/with-db-connection [conn db] - (sql/with-db-metadata [metadata conn {}] - (let [table-info (sql/metadata-query (.getTables metadata - nil nil nil - (into-array ["TABLE" "VIEW"])))] - (is (not= [] table-info)) - (is (= "fruit" (-> table-info - first - :table_name - clojure.string/lower-case))))) - ;; JDBC-171 this used to blow up because the connnection is closed - (sql/with-db-metadata [metadata conn {}] - (let [table-info (sql/metadata-query (.getTables metadata - nil nil nil - (into-array ["TABLE" "VIEW"])))] - (is (not= [] table-info)) - (is (= "fruit" (-> table-info - first - :table_name - clojure.string/lower-case)))))))) + clojure.string/lower-case)))) + (sql/with-db-connection [conn db] + (sql/with-db-metadata [metadata conn {}] + (let [table-info (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case))))) + ;; JDBC-171 this used to blow up because the connnection is closed + (sql/with-db-metadata [metadata conn {}] + (let [table-info (sql/metadata-query (.getTables metadata + nil nil nil + (into-array ["TABLE" "VIEW"])))] + (is (not= [] table-info)) + (is (= "fruit" (-> table-info + first + :table_name + clojure.string/lower-case))))))))) (deftest test-metadata-managed-computed (doseq [db (test-specs)] @@ -1254,6 +1254,22 @@ {:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil} {:id (generated-key db 2) :name "Pear" :appearance "yellow" :cost nil :grade nil}] rows))))) +(deftest test-create-table-ddl + (is (re-find #"`foo` int default 0" + (sql/create-table-ddl :table + [[:foo :int :default 0]] + {:entities (sql/quoted :mysql)})))) + +(comment + db (sql/create-table-ddl + table + [[:id :int "PRIMARY KEY AUTO_INCREMENT"] + [:name "VARCHAR(32)"] + [:appearance "VARCHAR(32)"] + [:cost :int] + [:grade :real]] + {:table-spec "ENGINE=InnoDB"})) + (deftest test-resultset-read-column (extend-protocol sql/IResultSetReadColumn String From 93ff83e1aeb23a3b4a9a635c3f60f235a2eedc74 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 28 Apr 2019 15:01:18 -0700 Subject: [PATCH 586/630] Fix Clojure wiki links Point to clojure.org pages for CONTRIBUTING and PULL_REQUEST_TEMPLATE --- .github/PULL_REQUEST_TEMPLATE | 10 +++++----- .gitignore | 1 + CONTRIBUTING.md | 8 +++----- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE index 0a5c486a..686625a4 100644 --- a/.github/PULL_REQUEST_TEMPLATE +++ b/.github/PULL_REQUEST_TEMPLATE @@ -1,6 +1,6 @@ Hi! Thanks for your interest in contributing to this project. -Clojure contrib projects do not use GitHub issues or pull requests, and +Clojure contrib projects do not use GitHub issues or pull requests, and require a signed Contributor Agreement. If you would like to contribute, please read more about the CA and sign that first (this can be done online). @@ -8,7 +8,7 @@ Then go to this project's issue tracker in JIRA to create tickets, update tickets, or submit patches. For help in creating tickets and patches, please see: -- Signing the CA: https://dev.clojure.org/display/community/Contributing+FAQ -- Creating Tickets: https://dev.clojure.org/display/community/Creating+Tickets -- Developing Patches: https://dev.clojure.org/display/community/Developing+Patches -- Contributing FAQ: https://dev.clojure.org/display/community/Contributing+FAQ +- Signing the CA: https://clojure.org/community/contributing +- Creating Tickets: https://clojure.org/community/creating_tickets +- Developing Patches: https://clojure.org/community/developing_patches +- Contributing FAQ: https://clojure.org/community/contributing diff --git a/.gitignore b/.gitignore index b3db9d32..51cb74c5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .classpath .cpcache .project +.rebl .settings /.lein-failures /.lein-repl-history diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 512917d6..820a2754 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,12 +3,10 @@ This is a [Clojure contrib] project. Under the Clojure contrib [guidelines], this project cannot accept pull requests. All patches must be submitted via [JIRA]. -See [Contributing] and the [FAQ] on the Clojure development [wiki] for +See [Contributing] on the Clojure website for more information on how to contribute. -[Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib +[Clojure contrib]: https://clojure.org/community/contrib_libs [Contributing]: https://clojure.org/community/contributing -[FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ [JIRA]: http://dev.clojure.org/jira/browse/JDBC -[guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers -[wiki]: http://dev.clojure.org/ +[guidelines]: https://clojure.org/community/contrib_howto From 0801bc07ce2f01984f6a6bc03504fef73ac02197 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 28 Apr 2019 15:37:19 -0700 Subject: [PATCH 587/630] Fix typo in as-properties docstring --- src/main/clojure/clojure/java/jdbc.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 903e814d..b0a6e936 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -108,7 +108,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ks vs)) (defn- ^Properties as-properties - "Convert any seq of pairs to a java.utils.Properties instance. + "Convert any seq of pairs to a java.util.Properties instance. Uses as-sql-name to convert both keys and values into strings." [m] (let [p (Properties.)] From 4138b0322715aff7ca5b8009e847d74cd3913da8 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 5 May 2019 00:16:41 -0700 Subject: [PATCH 588/630] Fix JDBC-178 by cleaning up properties hash map --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index fc546d6c..3e5a38e0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.10 +* Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://dev.clojure.org/jira/browse/JDBC-178). * Relax restriction on `create-table-ddl` column specs to allow numbers (as well as keywords and strings) [JDBC-177](https://dev.clojure.org/jira/browse/JDBC-177). Changes in 0.7.9 diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index b0a6e936..7193c18e 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -398,7 +398,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} host (when port (str ":" port)) db-sep dbname)) - etc (dissoc db-spec :dbtype :dbname)] + etc (dissoc db-spec :dbtype :dbname :host :port :classname)] (get-driver-connection classname subprotocol db-spec url etc opts (str "Unknown dbtype: " dbtype))) From 28e19994fea8eeeaad1abe12ee6b2c42f7c87051 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 18 May 2019 12:17:39 -0700 Subject: [PATCH 589/630] JIRA migration --- CHANGES.md | 240 +++++++++++++++++++++++------------------------ CONTRIBUTING.md | 2 +- README.md | 244 ++++++++++++++++++++++++------------------------ 3 files changed, 243 insertions(+), 243 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3e5a38e0..0cc5737a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,43 +1,43 @@ Changes coming in 0.7.10 -* Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://dev.clojure.org/jira/browse/JDBC-178). -* Relax restriction on `create-table-ddl` column specs to allow numbers (as well as keywords and strings) [JDBC-177](https://dev.clojure.org/jira/browse/JDBC-177). +* Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://clojure.atlassian.net/browse/JDBC-178). +* Relax restriction on `create-table-ddl` column specs to allow numbers (as well as keywords and strings) [JDBC-177](https://clojure.atlassian.net/browse/JDBC-177). Changes in 0.7.9 -* Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://dev.clojure.org/jira/browse/JDBC-176). -* Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://dev.clojure.org/jira/browse/JDBC-175). -* Add note about rewriting batched operations to `insert-multi!` for some drivers [JDBC-174](https://dev.clojure.org/jira/browse/JDBC-174). -* Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://dev.clojure.org/jira/browse/JDBC-173). +* Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://clojure.atlassian.net/browse/JDBC-176). +* Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://clojure.atlassian.net/browse/JDBC-175). +* Add note about rewriting batched operations to `insert-multi!` for some drivers [JDBC-174](https://clojure.atlassian.net/browse/JDBC-174). +* Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://clojure.atlassian.net/browse/JDBC-173). Changes in 0.7.8 -* Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). -* Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). +* Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://clojure.atlassian.net/browse/JDBC-172). +* Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://clojure.atlassian.net/browse/JDBC-171). Changes in 0.7.7 -* Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). +* Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://clojure.atlassian.net/browse/JDBC-169). * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). Changes in 0.7.6 -* `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). +* `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://clojure.atlassian.net/browse/JDBC-166). * Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). * Add missing spec for `db-spec` being a `java.net.URI` object. * Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). -* Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://dev.clojure.org/jira/browse/JDBC-165). +* Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://clojure.atlassian.net/browse/JDBC-165). * Update tests so they work properly with string `db-spec` test databases. * Ensure no reflection warnings are present. * Switched local test infrastructure over to CLI and `deps.edn` (from Leiningen) as an example of multi-version testing without a "build tool". Changes in 0.7.5 -* Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://dev.clojure.org/jira/browse/JDBC-163). +* Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://clojure.atlassian.net/browse/JDBC-163). Changes in 0.7.4 -* Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). +* Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://clojure.atlassian.net/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. * Performance improvements, primarily in `query` and `reducible-query`. * Experimental `:raw?` result set handling in `reducible-query`. @@ -45,18 +45,18 @@ Changes in 0.7.4 Changes in 0.7.3 -* Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). -* If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). +* Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://clojure.atlassian.net/browse/JDBC-159). +* If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://clojure.atlassian.net/browse/JDBC-158). Changes in 0.7.2 -* `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). +* `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://clojure.atlassian.net/browse/JDBC-156). * Allow for `:user` and `:password` to be passed with `:connection-uri`, so credentials can be omitted from the connection string. * Clarified docstring for `get-connection` to show where `:user` and `:password` can be passed. Changes in 0.7.1 -* Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). +* Connection strings with empty values were not parsed correctly [JDBC-155](https://clojure.atlassian.net/browse/JDBC-155). Changes in 0.7.0 @@ -65,7 +65,7 @@ Changes in 0.7.0 Changes in 0.7.0-beta5 -* `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). +* `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://clojure.atlassian.net/browse/JDBC-153). * Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`. Changes in 0.7.0-beta4 @@ -75,7 +75,7 @@ Changes in 0.7.0-beta4 Changes in 0.7.0-beta3 -* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). +* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://clojure.atlassian.net/browse/JDBC-152). Changes in 0.7.0-beta2 @@ -88,34 +88,34 @@ Changes in 0.7.0-beta1 * Support for Clojure 1.4.0 has been dropped -- breaking change. * Optional spec support now uses `clojure.spec.alpha`. -* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). +* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://clojure.atlassian.net/browse/JDBC-99). Changes in 0.7.0-alpha3 -* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). +* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://clojure.atlassian.net/browse/JDBC-151). * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. Changes in 0.7.0-alpha2 -* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). -* `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149). -* Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://dev.clojure.org/jira/browse/JDBC-148). -* Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://dev.clojure.org/jira/browse/JDBC-145). +* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://clojure.atlassian.net/browse/JDBC-150). +* `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://clojure.atlassian.net/browse/JDBC-149). +* Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://clojure.atlassian.net/browse/JDBC-148). +* Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://clojure.atlassian.net/browse/JDBC-145). Changes in 0.7.0-alpha1 -- potentially breaking changes * The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting). -* Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://dev.clojure.org/jira/browse/JDBC-147). -* All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://dev.clojure.org/jira/browse/JDBC-144). -* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141). -* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://dev.clojure.org/jira/browse/JDBC-137). +* Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://clojure.atlassian.net/browse/JDBC-147). +* All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://clojure.atlassian.net/browse/JDBC-144). +* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://clojure.atlassian.net/browse/JDBC-141). +* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://clojure.atlassian.net/browse/JDBC-137). * Expanded optional `clojure.spec` coverage to almost the whole library API. Changes in 0.6.2-alpha3 -* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140). -* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139). -* Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138). +* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://clojure.atlassian.net/browse/JDBC-140). +* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://clojure.atlassian.net/browse/JDBC-139). +* Fixed postgres / postgresql alias support [JDBC-138](http://clojure.atlassian.net/browse/JDBC-138). This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). Changes in 0.6.2-alpha2 @@ -125,46 +125,46 @@ Changes in 0.6.2-alpha2 Changes in 0.6.2-alpha1 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). -* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). -* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://dev.clojure.org/jira/browse/JDBC-135). -* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). -* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). +* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://clojure.atlassian.net/browse/JDBC-136). +* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://clojure.atlassian.net/browse/JDBC-135). +* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://clojure.atlassian.net/browse/JDBC-134). +* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://clojure.atlassian.net/browse/JDBC-133). Changes in 0.6.1 -* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. -* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129). +* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://clojure.atlassian.net/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. +* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://clojure.atlassian.net/browse/JDBC-127) and [JDBC-129](http://clojure.atlassian.net/browse/JDBC-129). Changes in 0.6.0 -* `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). +* `find-by-keys` now correctly handles `nil` values [JDBC-126](http://clojure.atlassian.net/browse/JDBC-126). * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. Changes in 0.6.0-rc2 -* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). +* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. * `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. * `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. -* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). +* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). * `find-by-keys` now accepts an `:order-by` option that specifies a sequence of orderings; an ordering is either a column (to sort ascending) or a map from column name to direct (`:asc` or `:desc`). Changes in 0.6.0-rc1 * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). -* REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). +* REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). - See alpha2 / alpha1 below for more details. Changes in 0.6.0-alpha2 -* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). +* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. -* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). -* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). +* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://clojure.atlassian.net/browse/JDBC-124). +* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://clojure.atlassian.net/browse/JDBC-123). Changes in 0.6.0-alpha1 -* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). +* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed @@ -172,73 +172,73 @@ Changes in 0.6.0-alpha1 Changes in 0.5.8 -* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. -* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. +* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. +* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. Changes in 0.5.7 -* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/browse/JDBC-121). +* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://clojure.atlassian.net/browse/JDBC-121). Changes in 0.5.6 -* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/browse/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. -* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/browse/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. +* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://clojure.atlassian.net/browse/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. +* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://clojure.atlassian.net/browse/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. * NOTE: all deprecated functionality will go away in version 0.6.0! Changes in 0.5.5 -* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. +* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://clojure.atlassian.net/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. Changes in 0.5.0 -* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). -* Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). +* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://clojure.atlassian.net/browse/JDBC-115). +* Remove exception wrapping [JDBC-114](http://clojure.atlassian.net/browse/JDBC-114). * Drop Clojure 1.3 compatibility. Changes in 0.4.2 -* Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. -* Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume. -* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). -* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). -* Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. +* Remove redundant type hints [JDBC-113](http://clojure.atlassian.net/browse/JDBC-113) - Michael Blume. +* Avoid reflection on `.prepareStatement` [JDBC-112](http://clojure.atlassian.net/browse/JDBC-112) - Michael Blume. +* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://clojure.atlassian.net/browse/JDBC-107). +* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://clojure.atlassian.net/browse/JDBC-104). +* Officially support H2 (and test against it) to support [JDBC-91](http://clojure.atlassian.net/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. Changes in 0.4.0 / 0.4.1 -* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. -* Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. -* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109). +* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://clojure.atlassian.net/browse/JDBC-111) - Stefan Kamphausen. +* Nested transaction checks isolation level is the same [JDBC-110](http://clojure.atlassian.net/browse/JDBC-110) - Donald Ball. +* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://clojure.atlassian.net/browse/JDBC-109). * Drop Clojure 1.2 compatibility. Changes in 0.3.7 * Bump all driver versions in `project.clj` and re-test. -* Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. -* Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106). -* Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. +* Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://clojure.atlassian.net/browse/JDBC-108) - Earl St Sauver. +* Remove driver versions from README and link to Maven Central [JDBC-106](http://clojure.atlassian.net/browse/JDBC-106). +* Fix links in CHANGES and README [JDBC-103](http://clojure.atlassian.net/browse/JDBC-103) - John Walker. Changes in 0.3.6 -* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102). -* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101). -* Add `:timeout` argument to `prepare-statement` [JDBC-100](http://dev.clojure.org/jira/browse/JDBC-100). +* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://clojure.atlassian.net/browse/JDBC-102). +* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://clojure.atlassian.net/browse/JDBC-101). +* Add `:timeout` argument to `prepare-statement` [JDBC-100](http://clojure.atlassian.net/browse/JDBC-100). Changes in 0.3.5 * Reflection warnings on executeUpdate addressed. -* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://dev.clojure.org/jira/browse/JDBC-94). -* Add support for readonly transactions via :read-only? [JDBC-93](http://dev.clojure.org/jira/browse/JDBC-93). +* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://clojure.atlassian.net/browse/JDBC-94). +* Add support for readonly transactions via :read-only? [JDBC-93](http://clojure.atlassian.net/browse/JDBC-93). Changes in 0.3.4 -* execute! can now accept a PreparedStatement [JDBC-96](http://dev.clojure.org/jira/browse/JDBC-96). +* execute! can now accept a PreparedStatement [JDBC-96](http://clojure.atlassian.net/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). -* Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). +* Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://clojure.atlassian.net/browse/JDBC-90). Changes in 0.3.3 -* Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89). -* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87). +* Prevent exception/crash when query called with bare SQL string [JDBC-89](http://clojure.atlassian.net/browse/JDBC-89). +* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://clojure.atlassian.net/browse/JDBC-87). * Support key/value configuration from URI (Phil Hagelberg). Changes in 0.3.2 @@ -249,25 +249,25 @@ Changes in 0.3.1 (broken) * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! -* Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86). -* Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). +* Provide better protocol for setting parameters in prepared statements [JDBC-86](http://clojure.atlassian.net/browse/JDBC-86). +* Fix parens in two deprecated tests [JDBC-85](http://clojure.atlassian.net/browse/JDBC-85). * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. Changes in 0.3.0 -* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). -* Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83). -* Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). -* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://dev.clojure.org/jira/browse/JDBC-65). +* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://clojure.atlassian.net/browse/JDBC-84). +* Rename recently introduced test to ensure unique names [JDBC-83](http://clojure.atlassian.net/browse/JDBC-83). +* Rename unused arguments in protocol implementation to support Android [JDBC-82](http://clojure.atlassian.net/browse/JDBC-82). +* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://clojure.atlassian.net/browse/JDBC-65). Changes in 0.3.0-rc1 -* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). -* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). -* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). -* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). -* Add support for :isolation in with-db-transaction [JDBC-75](http://dev.clojure.org/jira/browse/JDBC-75). -* Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). +* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://clojure.atlassian.net/browse/JDBC-81). +* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://clojure.atlassian.net/browse/JDBC-80). +* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://clojure.atlassian.net/browse/JDBC-79). +* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://clojure.atlassian.net/browse/JDBC-77). +* Add support for :isolation in with-db-transaction [JDBC-75](http://clojure.atlassian.net/browse/JDBC-75). +* Add :user as an alias for :username for DataSource connections [JDBC-74](http://clojure.atlassian.net/browse/JDBC-74). Changes in 0.3.0-beta2 @@ -276,48 +276,48 @@ Changes in 0.3.0-beta2 Changes in 0.3.0-beta1 -* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). +* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://clojure.atlassian.net/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver -* Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). -* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69). -* New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63). -* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40). +* Tests no longer use :1 literal [JDBC-71](http://clojure.atlassian.net/browse/JDBC-71). +* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://clojure.atlassian.net/browse/JDBC-69). +* New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://clojure.atlassian.net/browse/JDBC-63). +* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40). Changes in 0.3.0-alpha5 -* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). +* DDL now supports entities naming strategy [JDBC-53](http://clojure.atlassian.net/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). -* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist +* Added create-index / drop-index DDL [JDBC-62](http://clojure.atlassian.net/browse/JDBC-62) - moquist * Make transaction? boolean optional in various db-do-* functions * Create clojure.java.jdbc.ddl namespace * Add create-table, drop-table, create-index and drop-index * Deprecate create-table, create-table-ddl and drop-table in main namespace * Update README to clarify PostgreSQL instructions. -* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) -* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) -* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) +* Fix test suite for PostgreSQL [JDBC-59](http://clojure.atlassian.net/browser/JDBC-59) +* Improve hooks for Oracle data type handling [JDBC-57](http://clojure.atlassian.net/browser/JDBC-57) +* Fix reflection warnings [JDBC-55](http://clojure.atlassian.net/browser/JDBC-55) -* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). +* DDL now supports entities naming strategy [JDBC-53](http://clojure.atlassian.net/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). -* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist +* Added create-index / drop-index DDL [JDBC-62](http://clojure.atlassian.net/browse/JDBC-62) - moquist * Make transaction? boolean optional in various db-do-* functions - * It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with + * It will ultimately change to a function argument I think when [JDBC-37](http://clojure.atlassian.net/browser/JDBC-37) is dealt with * Create clojure.java.jdbc.ddl namespace * Add create-table and drop-table * Deprecate create-table, create-table-ddl and drop-table in main namespace * More DDL is coming soon * Update README to clarify PostgreSQL instructions. -* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) -* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) -* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) +* Fix test suite for PostgreSQL [JDBC-59](http://clojure.atlassian.net/browser/JDBC-59) +* Improve hooks for Oracle data type handling [JDBC-57](http://clojure.atlassian.net/browser/JDBC-57) +* Fix reflection warnings [JDBC-55](http://clojure.atlassian.net/browser/JDBC-55) Changes in 0.3.0-alpha4 -* Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) +* Fix connection leaks [JDBC-54](http://clojure.atlassian.net/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) Changes in 0.3.0-alpha3 @@ -326,10 +326,10 @@ Changes in 0.3.0-alpha3 Changes in 0.3.0-alpha2 -* Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection -* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) -* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52) -* Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) +* Address [JDBC-51](http://clojure.atlassian.net/browse/JDBC-51) by declaring get-connection returns java.sql.Connection +* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://clojure.atlassian.net/browse/JDBC-46) +* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://clojure.atlassian.net/browse/JDBC-52) +* Reverted specialized handling of NULL values (reopens [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean * Add curried version of clojure.java.jdbc.sql/as-quoted-str * Officially deprecate resultset-seq @@ -339,7 +339,7 @@ Changes in 0.3.0-alpha1 Major overhaul of the API and deprecation of most of the old API! * Add insert!, query, update!, delete! and execute! high-level API - [JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20) + [JDBC-20](http://clojure.atlassian.net/browse/JDBC-20) * Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20) * Add db- prefixed versions of low-level API * Add db-transaction macro: @@ -351,16 +351,16 @@ Major overhaul of the API and deprecation of most of the old API! * Add result-set-seq as replacement for resultset-seq (which will be deprecated) * Transaction now correctly rollback on non-Exception Throwables - [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) + [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) * Rewrite old API functions in terms of new API, and deprecate old API - [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) + [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) * Add :as-arrays to query / result-set-seq - [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) -* Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) - and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) + [JDBC-41](http://clojure.atlassian.net/browse/JDBC-41) +* Better handling of NULL values [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40) + and [JDBC-18](http://clojure.atlassian.net/browse/JDBC-18) Note: JDBC-40 has been reverted in 0.3.0-alpha2 because it introduced regressions for PostgreSQL * db-do-commands allows you to execute SQL without a transaction wrapping it - [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) + [JDBC-38](http://clojure.atlassian.net/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy @@ -368,18 +368,18 @@ Major overhaul of the API and deprecation of most of the old API! Changes in 0.2.3: * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] -* Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) +* Add :connection-uri option [JDBC-34](http://clojure.atlassian.net/browse/JDBC-34) Changes in 0.2.2: -* Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) -* Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) -* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) +* Handle Oracle unknown row count affected [JDBC-33](http://clojure.atlassian.net/browse/JDBC-33) +* Handle jdbc: prefix in string db-specs [JDBC-32](http://clojure.atlassian.net/browse/JDBC-32) +* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://clojure.atlassian.net/browse/JDBC-31) Changes in 0.2.1: -* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29) -* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30) +* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://clojure.atlassian.net/browse/JDBC-29) +* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://clojure.atlassian.net/browse/JDBC-30) Changes in 0.2.0: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 820a2754..d1017074 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,5 +8,5 @@ more information on how to contribute. [Clojure contrib]: https://clojure.org/community/contrib_libs [Contributing]: https://clojure.org/community/contributing -[JIRA]: http://dev.clojure.org/jira/browse/JDBC +[JIRA]: http://clojure.atlassian.net/browse/JDBC [guidelines]: https://clojure.org/community/contrib_howto diff --git a/README.md b/README.md index 0124a8ac..5a6e721c 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ Developer Information * [GitHub project](https://github.com/clojure/java.jdbc) -* [Bug Tracker](http://dev.clojure.org/jira/browse/JDBC) +* [Bug Tracker](http://clojure.atlassian.net/browse/JDBC) * [Continuous Integration](http://build.clojure.org/job/java.jdbc/) @@ -139,57 +139,57 @@ Change Log ==================== * Release 0.7.9 on 2019-02-21 - * Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://dev.clojure.org/jira/browse/JDBC-176). - * Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://dev.clojure.org/jira/browse/JDBC-175). - * Add note about rewriting batched operations to `insert-multi!` for some drivers [JDBC-174](https://dev.clojure.org/jira/browse/JDBC-174). - * Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://dev.clojure.org/jira/browse/JDBC-173). + * Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://clojure.atlassian.net/browse/JDBC-176). + * Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://clojure.atlassian.net/browse/JDBC-175). + * Add note about rewriting batched operations to `insert-multi!` for some drivers [JDBC-174](https://clojure.atlassian.net/browse/JDBC-174). + * Support Oracle SID style URLs (`dbtype` can be `oracle:sid` which maps to `oracle:thin` and uses `:` as the separator before the `dbname` value) [JDBC-173](https://clojure.atlassian.net/browse/JDBC-173). * Release 0.7.8 on 2018-08-13 - * Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://dev.clojure.org/jira/browse/JDBC-172). - * Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://dev.clojure.org/jira/browse/JDBC-171). + * Support multiple JDBC driver class names (MySQL introduced a new driver class name with its 6.x connector) [JDBC-172](https://clojure.atlassian.net/browse/JDBC-172). + * Allow `with-db-connection` and `with-db-metadata` to nest [JDBC-171](https://clojure.atlassian.net/browse/JDBC-171). * Release 0.7.7 on 2018-06-23 - * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://dev.clojure.org/jira/browse/JDBC-169). + * Support `:as-arrays?`, `:result-set-fn`, and `:row-fn` in operations that return generated keys as a result set (`execute!`, `insert!`, and `insert-multi!`) [JDBC-169](https://clojure.atlassian.net/browse/JDBC-169). * `get-connection` provides much better feedback if you accidentally call a function that expects a `db-spec` but pass a `java.sql.Connection` object instead (which is only required for `prepare-statement`). * Release 0.7.6 on 2018-04-24 - * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://dev.clojure.org/jira/browse/JDBC-166). + * `execute!` now supports `:return-keys` as a vector of column names, rather than just a simple Boolean value, for drivers that support that [JDBC-166](https://clojure.atlassian.net/browse/JDBC-166). * Add built-in support for H2 in-memory database (`:dbtype "h2:mem"`). * Add missing spec for `db-spec` being a `java.net.URI` object. * Fix `add-connection` handling of string `db-spec` (becomes `:connection-uri`, not `:connection-string`). - * Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://dev.clojure.org/jira/browse/JDBC-165). + * Fix specs for `with-db-*` functions, to support options in the binding form [JDBC-165](https://clojure.atlassian.net/browse/JDBC-165). * Update tests so they work properly with string `db-spec` test databases. * Ensure no reflection warnings are present. * Switched local test infrastructure over to CLI and `deps.edn` (from Leiningen) as an example of multi-version testing without a "build tool". * Release 0.7.5 on 2017-12-29 - * Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://dev.clojure.org/jira/browse/JDBC-163). + * Add support for `:return-keys` in `execute!` and `:multi?` in `db-do-prepared-return-keys` [JDBC-163](https://clojure.atlassian.net/browse/JDBC-163). * Release 0.7.4 on 2017-12-14 - * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://dev.clojure.org/jira/browse/JDBC-160). + * Improved discoverability of other `java.jdbc` documentation [JDBC-160](https://clojure.atlassian.net/browse/JDBC-160). * Optional specs updated with `:keywordize?` and `:connection-uri` changes from 0.7.2 and 0.7.3 releases. * Performance improvements, primarily in `query` and `reducible-query`. * Experimental `:raw?` result set handling in `reducible-query`. * `modify-connection` is more robust in the face of `null` connections and bad option values. * Release 0.7.3 on 2017-10-05 - * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://dev.clojure.org/jira/browse/JDBC-159). - * If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://dev.clojure.org/jira/browse/JDBC-158). + * Added `:keywordize?` option alongside `:identifiers` that defaults to `true` but can be set to `false` to opt-out of converting identifiers to keywords (so column names etc will only be processed by the function passed as `:identifiers`) [JDBC-159](https://clojure.atlassian.net/browse/JDBC-159). + * If an exception occurs during a transaction, and then rollback fails with another exception, both exceptions will now be combined into an `ex-info`. Previously the rollback exception obscured the transaction exception [JDBC-158](https://clojure.atlassian.net/browse/JDBC-158). * Release 0.7.2 on 2017-10-02 - * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://dev.clojure.org/jira/browse/JDBC-156). + * `connection-uri` was incorrectly spec'd as a `java.net.URI` but should be `string?` [JDBC-156](https://clojure.atlassian.net/browse/JDBC-156). * Allow for `:user` and `:password` to be passed with `:connection-uri`, so credentials can be omitted from the connection string. * Clarified docstring for `get-connection` to show where `:user` and `:password` can be passed. * Release 0.7.1 on 2017-08-30 - * Connection strings with empty values were not parsed correctly [JDBC-155](https://dev.clojure.org/jira/browse/JDBC-155). + * Connection strings with empty values were not parsed correctly [JDBC-155](https://clojure.atlassian.net/browse/JDBC-155). * Release 0.7.0 on 2017-07-16 * `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL). * Add better support for Oracle connections (default port to `1521`, support `:dbtype "oracle"` -- as `"oracle:thin"` -- and `:dbtype "oracle:oci"`, with `@` instead of `//` before host). * Release 0.7.0-beta5 on 2017-07-05 - * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153). + * `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://clojure.atlassian.net/browse/JDBC-153). * Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`. * Release 0.7.0-beta4 on 2017-07-04 @@ -197,7 +197,7 @@ Change Log * Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there. * Release 0.7.0-beta3 on 2017-07-04 - * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152). + * Reflection warnings removed in `reducible-result-set` [JDBC-152](https://clojure.atlassian.net/browse/JDBC-152). * Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2) * Support for Clojure 1.5 and 1.6 has been dropped -- breaking change. @@ -208,30 +208,30 @@ Change Log * Release 0.7.0-beta1 on 2017-06-29 * Support for Clojure 1.4.0 has been dropped -- breaking change. * Optional spec support now uses `clojure.spec.alpha`. - * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99). + * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://clojure.atlassian.net/browse/JDBC-99). * Release 0.7.0-alpha3 on 2017-03-23 - * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151). + * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://clojure.atlassian.net/browse/JDBC-151). * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. * Release 0.7.0-alpha2 on 2017-03-01 - * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150). - * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149). - * Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://dev.clojure.org/jira/browse/JDBC-148). - * Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://dev.clojure.org/jira/browse/JDBC-145). + * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://clojure.atlassian.net/browse/JDBC-150). + * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://clojure.atlassian.net/browse/JDBC-149). + * Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://clojure.atlassian.net/browse/JDBC-148). + * Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://clojure.atlassian.net/browse/JDBC-145). * Release 0.7.0-alpha1 on 2016-11-12 -- potentially breaking changes * The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting). - * Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://dev.clojure.org/jira/browse/JDBC-147). - * All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://dev.clojure.org/jira/browse/JDBC-144). - * Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141). - * Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://dev.clojure.org/jira/browse/JDBC-137). + * Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://clojure.atlassian.net/browse/JDBC-147). + * All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://clojure.atlassian.net/browse/JDBC-144). + * Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://clojure.atlassian.net/browse/JDBC-141). + * Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://clojure.atlassian.net/browse/JDBC-137). * Expanded optional `clojure.spec` coverage to almost the whole library API. * Release 0.6.2-alpha3 on 2016-08-25 - * Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140). - * Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139). - * Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138). + * Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://clojure.atlassian.net/browse/JDBC-140). + * Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://clojure.atlassian.net/browse/JDBC-139). + * Fixed postgres / postgresql alias support [JDBC-138](http://clojure.atlassian.net/browse/JDBC-138). This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). * Release 0.6.2-alpha2 on 2016-07-21 @@ -239,94 +239,94 @@ Change Log * Release 0.6.2-alpha1 on 2016-07-05 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). - * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136). - * `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://dev.clojure.org/jira/browse/JDBC-135). - * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134). - * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133). + * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://clojure.atlassian.net/browse/JDBC-136). + * `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://clojure.atlassian.net/browse/JDBC-135). + * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://clojure.atlassian.net/browse/JDBC-134). + * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://clojure.atlassian.net/browse/JDBC-133). * Release 0.6.1 on 2016-05-12 -- **IMPORTANT BUG FIX!** - * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. - * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129). + * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://clojure.atlassian.net/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. + * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://clojure.atlassian.net/browse/JDBC-127) and [JDBC-129](http://clojure.atlassian.net/browse/JDBC-129). * Release 0.6.0 on 2016-05-11 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** - * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). 0.6.0 / 2016-05-11. + * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://clojure.atlassian.net/browse/JDBC-126). 0.6.0 / 2016-05-11. * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. 0.6.0 / 2016-05-11. - * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. + * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. * `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. 0.6.0-rc2 / 2016-05-07. * `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. 0.6.0-rc2 / 2016-05-07. - * `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. + * `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). 0.6.0-rc1 / 2016-05-04. - `find-by-keys` accepts an `:order-by` option that expects a sequence of orderings; an ordering is a column name (keyword) or a map from column name (keyword) to direction (`:asc` or `:desc`). 0.6.0-rc2 / 2016-05-07. - * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). 0.6.0-alpha2 / 2016-04-18. - * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). 0.6.0-alpha2 / 2016-04-18. - * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). 0.6.0-alpha1 / 2016-04-13 + * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://clojure.atlassian.net/browse/JDBC-124). 0.6.0-alpha2 / 2016-04-18. + * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://clojure.atlassian.net/browse/JDBC-123). 0.6.0-alpha2 / 2016-04-18. + * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). 0.6.0-alpha1 / 2016-04-13 - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed - The `java.jdbc.deprecated` namespace has been removed * Release 0.5.8 on 2016-04-12 - * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. - * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. + * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. + * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. * Release 0.5.7 on 2016-04-10 - * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/browse/JDBC-121). + * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://clojure.atlassian.net/browse/JDBC-121). * Release 0.5.6 on 2016-04-10 - * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/browse/JDBC-120). + * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://clojure.atlassian.net/browse/JDBC-120). - If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. - * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/browse/JDBC-119). + * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://clojure.atlassian.net/browse/JDBC-119). - If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. * NOTE: all deprecated functionality will go away in version 0.6.0! * Release 0.5.5 on 2016-04-09 - * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). + * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://clojure.atlassian.net/browse/JDBC-117). - The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. * Release 0.5.0 on 2016-03-27 - * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115). - * Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114). + * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://clojure.atlassian.net/browse/JDBC-115). + * Remove exception wrapping [JDBC-114](http://clojure.atlassian.net/browse/JDBC-114). * Drop Clojure 1.3 compatibility. * Release 0.4.2 on 2015-09-15 - * Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume. - * Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume. - * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107). - * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104). - * Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. + * Remove redundant type hints [JDBC-113](http://clojure.atlassian.net/browse/JDBC-113) - Michael Blume. + * Avoid reflection on `.prepareStatement` [JDBC-112](http://clojure.atlassian.net/browse/JDBC-112) - Michael Blume. + * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://clojure.atlassian.net/browse/JDBC-107). + * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://clojure.atlassian.net/browse/JDBC-104). + * Officially support H2 (and test against it) to support [JDBC-91](http://clojure.atlassian.net/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. * Release 0.4.0 / 0.4.1 on 2015-07-26 - * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen. - * Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball. - * Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109). + * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://clojure.atlassian.net/browse/JDBC-111) - Stefan Kamphausen. + * Nested transaction checks isolation level is the same [JDBC-110](http://clojure.atlassian.net/browse/JDBC-110) - Donald Ball. + * Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://clojure.atlassian.net/browse/JDBC-109). * Drop Clojure 1.2 compatibility. * Release 0.3.7 on 2015-05-18 * Bump all driver versions in `project.clj` and re-test. - * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver. - * Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106). - * Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker. + * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://clojure.atlassian.net/browse/JDBC-108) - Earl St Sauver. + * Remove driver versions from README and link to Maven Central [JDBC-106](http://clojure.atlassian.net/browse/JDBC-106). + * Fix links in CHANGES and README [JDBC-103](http://clojure.atlassian.net/browse/JDBC-103) - John Walker. * Release 0.3.6 on 2014-10-28 - * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102). - * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101). - * Add `:timeout` argument to `prepare-statement` [JDBC-100](http://dev.clojure.org/jira/browse/JDBC-100). + * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://clojure.atlassian.net/browse/JDBC-102). + * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://clojure.atlassian.net/browse/JDBC-101). + * Add `:timeout` argument to `prepare-statement` [JDBC-100](http://clojure.atlassian.net/browse/JDBC-100). * Release 0.3.5 on 2014-08-01 * Reflection warnings on executeUpdate addressed. - * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://dev.clojure.org/jira/browse/JDBC-94). - * Add support for readonly transactions via :read-only? [JDBC-93](http://dev.clojure.org/jira/browse/JDBC-93). + * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://clojure.atlassian.net/browse/JDBC-94). + * Add support for readonly transactions via :read-only? [JDBC-93](http://clojure.atlassian.net/browse/JDBC-93). * Release 0.3.4 on 2014-06-30 - * execute! can now accept a PreparedStatement [JDBC-96](http://dev.clojure.org/jira/browse/JDBC-96). + * execute! can now accept a PreparedStatement [JDBC-96](http://clojure.atlassian.net/browse/JDBC-96). * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). - * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90). + * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://clojure.atlassian.net/browse/JDBC-90). * Release 0.3.3 on 2014-01-30 - * Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89). - * Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87). + * Prevent exception/crash when query called with bare SQL string [JDBC-89](http://clojure.atlassian.net/browse/JDBC-89). + * Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://clojure.atlassian.net/browse/JDBC-87). * Support key/value configuration from URI (Phil Hagelberg). * Release 0.3.2 on 2013-12-30 @@ -335,23 +335,23 @@ Change Log * Release 0.3.1 on 2013-12-29 (broken; use 0.3.2 instead) * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! - * Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86). - * Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85). + * Provide better protocol for setting parameters in prepared statements [JDBC-86](http://clojure.atlassian.net/browse/JDBC-86). + * Fix parens in two deprecated tests [JDBC-85](http://clojure.atlassian.net/browse/JDBC-85). * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. * Release 0.3.0 on 2013-12-16 - * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84). - * Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83). - * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82). - * Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://dev.clojure.org/jira/browse/JDBC-65). + * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://clojure.atlassian.net/browse/JDBC-84). + * Rename recently introduced test to ensure unique names [JDBC-83](http://clojure.atlassian.net/browse/JDBC-83). + * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://clojure.atlassian.net/browse/JDBC-82). + * Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://clojure.atlassian.net/browse/JDBC-65). * Release 0.3.0-rc1 on 2013-12-12 - * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81). - * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80). - * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79). - * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77). - * Add support for :isolation in with-db-transaction [JDBC-75](http://dev.clojure.org/jira/browse/JDBC-75). - * Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74). + * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://clojure.atlassian.net/browse/JDBC-81). + * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://clojure.atlassian.net/browse/JDBC-80). + * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://clojure.atlassian.net/browse/JDBC-79). + * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://clojure.atlassian.net/browse/JDBC-77). + * Add support for :isolation in with-db-transaction [JDBC-75](http://clojure.atlassian.net/browse/JDBC-75). + * Add :user as an alias for :username for DataSource connections [JDBC-74](http://clojure.atlassian.net/browse/JDBC-74). * Release 0.3.0-beta2 on 2013-11-24 * **BREAKING CHANGES!** @@ -359,40 +359,40 @@ Change Log * The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. * Release 0.3.0-beta1 on 2013-11-03 - * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72). + * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://clojure.atlassian.net/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver - * Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71). - * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69). - * New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63). - * Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40). + * Tests no longer use :1 literal [JDBC-71](http://clojure.atlassian.net/browse/JDBC-71). + * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://clojure.atlassian.net/browse/JDBC-69). + * New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://clojure.atlassian.net/browse/JDBC-63). + * Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40). * Release 0.3.0-alpha5 on 2013-09-15 - * DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53). + * DDL now supports entities naming strategy [JDBC-53](http://clojure.atlassian.net/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). - * Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist + * Added create-index / drop-index DDL [JDBC-62](http://clojure.atlassian.net/browse/JDBC-62) - moquist * Make transaction? boolean optional in various db-do-* functions * Create clojure.java.jdbc.ddl namespace * Add create-table, drop-table, create-index and drop-index * Deprecate create-table, create-table-ddl and drop-table in main namespace * Update README to clarify PostgreSQL instructions. - * Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59) - * Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57) - * Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55) + * Fix test suite for PostgreSQL [JDBC-59](http://clojure.atlassian.net/browser/JDBC-59) + * Improve hooks for Oracle data type handling [JDBC-57](http://clojure.atlassian.net/browser/JDBC-57) + * Fix reflection warnings [JDBC-55](http://clojure.atlassian.net/browser/JDBC-55) * Release 0.3.0-alpha4 on 2013-05-11 - * Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54) + * Fix connection leaks [JDBC-54](http://clojure.atlassian.net/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) * Release 0.3.0-alpha3 on 2013-05-04 * Fix macro / import interaction by fully qualifying Connection type. * Release 0.3.0-alpha2 on 2013-05-03 - * Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection - * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46) - * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52) - * Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)) + * Address [JDBC-51](http://clojure.atlassian.net/browse/JDBC-51) by declaring get-connection returns java.sql.Connection + * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://clojure.atlassian.net/browse/JDBC-46) + * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://clojure.atlassian.net/browse/JDBC-52) + * Reverted specialized handling of NULL values (reopens [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean * Add curried version of clojure.java.jdbc.sql/as-quoted-str * Officially deprecate resultset-seq @@ -401,36 +401,36 @@ Change Log * MAJOR API OVERHAUL! * Most of the old 0.2.x API has been deprecated and a new, more idiomatic API introduced, along with a minimal DSL to generate basic SQL * Specifics: - * Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20) + * Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](http://clojure.atlassian.net/browse/JDBC-20) * Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20) * Add db- prefixed versions of low-level API * Add db-transaction macro * Add result-set-seq as replacement for resultset-seq (which will be deprecated) - * Transaction now correctly rollback on non-Exception Throwables [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) - * Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43) - * Add :as-arrays to query / result-set-seq [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41) - * Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18) + * Transaction now correctly rollback on non-Exception Throwables [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) + * Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) + * Add :as-arrays to query / result-set-seq [JDBC-41](http://clojure.atlassian.net/browse/JDBC-41) + * Better handling of NULL values [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40) and [JDBC-18](http://clojure.atlassian.net/browse/JDBC-18) Note: JDBC-40 is being reverted in 0.3.0-alpha2 because it introduces regressions in PostgreSQL - * db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38) + * db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](http://clojure.atlassian.net/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy * Release 0.2.3 on 2012-06-18 * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] - * Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34) + * Add :connection-uri option [JDBC-34](http://clojure.atlassian.net/browse/JDBC-34) * Release 0.2.2 on 2012-06-10 - * Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33) - * Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32) - * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31) + * Handle Oracle unknown row count affected [JDBC-33](http://clojure.atlassian.net/browse/JDBC-33) + * Handle jdbc: prefix in string db-specs [JDBC-32](http://clojure.atlassian.net/browse/JDBC-32) + * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://clojure.atlassian.net/browse/JDBC-31) * Release 0.2.1 on 2012-05-10 - * Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29) - * Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30) + * Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://clojure.atlassian.net/browse/JDBC-29) + * Make do-prepared-return-keys (for Korma team) [JDBC-30](http://clojure.atlassian.net/browse/JDBC-30) * Release 0.2.0 on 2012-04-23 - * Merge internal namespace into main jdbc namespace [JDBC-19](http://dev.clojure.org/jira/browse/JDBC-19) + * Merge internal namespace into main jdbc namespace [JDBC-19](http://clojure.atlassian.net/browse/JDBC-19) * Release 0.1.4 on 2012-04-15 * Unwrap RTE for nested transaction exceptions (we already @@ -438,26 +438,26 @@ Change Log * Remove reflection warning unwrapping RunTimeException (Alan Malloy) * Release 0.1.3 on 2012-02-29 - * Fix generated keys inside transactions for SQLite3 [JDBC-26](http://dev.clojure.org/jira/browse/JDBC-26) + * Fix generated keys inside transactions for SQLite3 [JDBC-26](http://clojure.atlassian.net/browse/JDBC-26) * Release 0.1.2 on 2012-02-29 - * Handle prepared statement params correctly [JDBC-23](http://dev.clojure.org/jira/browse/JDBC-23) - * Add support for SQLite3 [JDBC-26](http://dev.clojure.org/jira/browse/JDBC-26) - * Replace replicate (deprecated) with repeat [JDBC-27](http://dev.clojure.org/jira/browse/JDBC-27) + * Handle prepared statement params correctly [JDBC-23](http://clojure.atlassian.net/browse/JDBC-23) + * Add support for SQLite3 [JDBC-26](http://clojure.atlassian.net/browse/JDBC-26) + * Replace replicate (deprecated) with repeat [JDBC-27](http://clojure.atlassian.net/browse/JDBC-27) * Ensure MS SQL Server passes tests with both Microsoft and jTDS drivers * Build server now tests derby, hsqldb and sqlite by default * Update README per Stuart Sierra's outline for contrib projects * Release 0.1.1 on 2011-11-02 - * Accept string or URI in connection definition [JDBC-21](http://dev.clojure.org/jira/browse/JDBC-21) - * Allow driver, port and subprotocol to be deduced [JDBC-22](http://dev.clojure.org/jira/browse/JDBC-22) + * Accept string or URI in connection definition [JDBC-21](http://clojure.atlassian.net/browse/JDBC-21) + * Allow driver, port and subprotocol to be deduced [JDBC-22](http://clojure.atlassian.net/browse/JDBC-22) * Release 0.1.0 on 2011-10-16 - * Remove dependence on deprecated structmap [JDBC-15](http://dev.clojure.org/jira/browse/JDBC-15) + * Remove dependence on deprecated structmap [JDBC-15](http://clojure.atlassian.net/browse/JDBC-15) * Release 0.0.7 on 2011-10-11 - * Rename duplicate columns [JDBC-9](http://dev.clojure.org/jira/browse/JDBC-9) - * Ensure do-preared traps invalid SQL [JDBC-16](http://dev.clojure.org/jira/browse/JDBC-16) + * Rename duplicate columns [JDBC-9](http://clojure.atlassian.net/browse/JDBC-9) + * Ensure do-preared traps invalid SQL [JDBC-16](http://clojure.atlassian.net/browse/JDBC-16) * Release 0.0.6 on 2011-08-04 * Improve exception handling (unwrap RTE) @@ -475,10 +475,10 @@ Change Log * Ensure transactions are not committed when Error occurs [JDBC-11](http://dev.clojure.org/jire/JDBC-11) * Release 0.0.3 on 2011-07-01 - * Key generation compatibility with MS SQL Server, PostgreSQL [JDBC-10](http://dev.clojure.org/jira/browse/JDBC-10) + * Key generation compatibility with MS SQL Server, PostgreSQL [JDBC-10](http://clojure.atlassian.net/browse/JDBC-10) * Release 0.0.2 on 2011-06-07 - * Clojure 1.2 compatibility [JDBC-7](http://dev.clojure.org/jira/browse/JDBC-7) + * Clojure 1.2 compatibility [JDBC-7](http://clojure.atlassian.net/browse/JDBC-7) * Release 0.0.1 on 2011-05-07 * Initial release From d0ecdb427badc3971e2a8d03ba93bd426c1c7ee9 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 26 May 2019 16:40:59 -0700 Subject: [PATCH 590/630] Add note about next.jdbc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5a6e721c..f1e0730c 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ For higher level DSLs and migration libraries that are compatible, see the [docu Formerly known as `clojure.contrib.sql`. +This library is mature and stable. It is widely used and its use is described in many books and tutorials. It will continue to get bug fixes and minor releases. Based on my experience using and maintaining this library, I've created a faster, more modern JDBC wrapper called [next.jdbc](https://github.com/seancorfield/next-jdbc). I consider it to be the "next generation" of `clojure.java.jdbc` but it exposes a different API -- a better API, I think. + Documentation ======================================== * [API Reference](http://clojure.github.com/java.jdbc/) (Autogenerated) From 1f1ff8144b4a9a4447b2a2fbb9e592f90ccd2659 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 8 Aug 2019 17:08:41 -0700 Subject: [PATCH 591/630] Address Turkish lower-case issue --- CHANGES.md | 1 + src/main/clojure/clojure/java/jdbc.clj | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0cc5737a..efab13da 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,6 @@ Changes coming in 0.7.10 +* Use a US-locale `lower-case` function to avoid problems in certain locales (e.g., Turkish). A similar issue has been fixed recently in both HoneySQL and `next.jdbc`. * Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://clojure.atlassian.net/browse/JDBC-178). * Relax restriction on `create-table-ddl` column specs to allow numbers (as well as keywords and strings) [JDBC-177](https://clojure.atlassian.net/browse/JDBC-177). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 7193c18e..477996a7 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -45,7 +45,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (java.sql BatchUpdateException DriverManager PreparedStatement ResultSet ResultSetMetaData SQLException Statement Types) - (java.util Hashtable Map Properties) + (java.util Hashtable Locale Map Properties) (javax.sql DataSource))) (set! *warn-on-reflection* true) @@ -535,6 +535,13 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} :else identifiers)) +(defn- lower-case + "Converts a string to lower case in the US locale to avoid problems in + locales where the lower case version of a character is not a valid SQL + entity name (e.g., Turkish)." + [^String s] + (.toLowerCase s (Locale/US))) + (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it @@ -551,7 +558,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ([rs] (result-set-seq rs {})) ([^ResultSet rs {:keys [as-arrays? identifiers keywordize? qualifier read-columns] - :or {identifiers str/lower-case + :or {identifiers lower-case keywordize? true read-columns dft-read-columns}}] (let [rsmeta (.getMetaData rs) @@ -1213,7 +1220,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce Note: :as-arrays? is not accepted here." [^ResultSet rs {:keys [identifiers keywordize? qualifier read-columns] - :or {identifiers str/lower-case + :or {identifiers lower-case keywordize? true read-columns dft-read-columns}}] (let [rsmeta (.getMetaData rs) @@ -1312,7 +1319,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ([db sql-params] (reducible-query db sql-params {})) ([db sql-params opts] (let [{:keys [identifiers keywordize? qualifier read-columns] :as opts} - (merge {:identifiers str/lower-case :keywordize? true + (merge {:identifiers lower-case :keywordize? true :read-columns dft-read-columns} (when (map? db) db) opts) @@ -1551,7 +1558,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} map, insert the rows into the database." [db table rows opts] (let [{:keys [entities transaction?] :as opts} - (merge {:entities identity :identifiers str/lower-case + (merge {:entities identity :identifiers lower-case :keywordize? true :transaction? true} (when (map? db) db) opts) From da5fd9d432d35c6a1d7fc7c872b1bcdd6e9a6a6c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 12 Aug 2019 10:43:15 -0700 Subject: [PATCH 592/630] Update test.check to 0.10.0 --- deps.edn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deps.edn b/deps.edn index b09bc738..540e15d9 100644 --- a/deps.edn +++ b/deps.edn @@ -5,7 +5,7 @@ {:paths ["src/main/clojure"] :aliases {:test {:extra-paths ["src/test/clojure"] - :extra-deps {org.clojure/test.check {:mvn/version "0.9.0"} + :extra-deps {org.clojure/test.check {:mvn/version "0.10.0"} org.apache.derby/derby {:mvn/version "10.14.2.0"} org.hsqldb/hsqldb {:mvn/version "2.4.1"} com.h2database/h2 {:mvn/version "1.4.197"} From 19b1e6dc6f0f4e5c6cb2a7918f73283628bf666b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 24 Aug 2019 11:29:38 -0700 Subject: [PATCH 593/630] Prep for 0.7.10 release --- CHANGES.md | 2 +- README.md | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index efab13da..9f5519cc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes coming in 0.7.10 +Changes in 0.7.10 * Use a US-locale `lower-case` function to avoid problems in certain locales (e.g., Turkish). A similar issue has been fixed recently in both HoneySQL and `next.jdbc`. * Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://clojure.atlassian.net/browse/JDBC-178). diff --git a/README.md b/README.md index f1e0730c..60ec92b3 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.9 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.10 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -34,14 +34,14 @@ Latest stable release: 0.7.9 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.9"] +[org.clojure/java.jdbc "0.7.10"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.9 + 0.7.10 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -140,6 +140,11 @@ Developer Information Change Log ==================== +* Release 0.7.10 on 2019-08-24 + * Use a US-locale `lower-case` function to avoid problems in certain locales (e.g., Turkish). A similar issue has been fixed recently in both HoneySQL and `next.jdbc`. + * Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://clojure.atlassian.net/browse/JDBC-178). + * Relax restriction on `create-table-ddl` column specs to allow numbers (as well as keywords and strings) [JDBC-177](https://clojure.atlassian.net/browse/JDBC-177). + * Release 0.7.9 on 2019-02-21 * Fix behavior of multi-inserts when database does not support generated keys [JDBC-176](https://clojure.atlassian.net/browse/JDBC-176). * Added _highly experimental_ support for `datafy`/`nav` (in `clojure.java.jdbc.datafy` namespace). This includes a convention-based approach to foreign keys with some assistance from a `:schema` option. This is subject to change and is provided mostly for informational purposes, as an example of the new functionality in Clojure 1.10. This includes a fix for the conventions from [JDBC-175](https://clojure.atlassian.net/browse/JDBC-175). From 5344e1551bffbe8d07810bd4bb06757f41d31a5b Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 24 Aug 2019 13:31:25 -0500 Subject: [PATCH 594/630] [maven-release-plugin] prepare release java.jdbc-0.7.10 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2e00343f..71db0892 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.10-SNAPSHOT + 0.7.10 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.10 From 71a85763eb2f5cfaae17d5bdf1aca05e5220fb24 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Sat, 24 Aug 2019 13:31:25 -0500 Subject: [PATCH 595/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 71db0892..7313c02d 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.10 + 0.7.11-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.10 + HEAD From 7c382525cd15fd04d706c285b756e502d53d5212 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 6 Sep 2019 01:24:04 -0700 Subject: [PATCH 596/630] Note Stable status Also note that it is superseded by `next.jdbc`. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 60ec92b3..b5ab870f 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ clojure.java.jdbc ======================================== -A low-level Clojure wrapper for JDBC-based access to databases. +A low-level Clojure wrapper for JDBC-based access to databases. This project is "Stable" (no longer "Active"). It has effectively been superseded by [seancorfield/next.jdbc](https://github.com/seancorfield/next-jdbc). For higher level DSLs and migration libraries that are compatible, see the [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). From 0cc48ceb0ad3a5064a8baabd063b3cab4a643563 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 10 Oct 2019 17:51:32 -0700 Subject: [PATCH 597/630] Add test for reported slow prepared statement code with PostgreSQL --- src/test/clojure/clojure/java/jdbc_test.clj | 26 +++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index f01de14c..94412c44 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -1254,6 +1254,32 @@ {:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil} {:id (generated-key db 2) :name "Pear" :appearance "yellow" :cost nil :grade nil}] rows))))) +(comment + (def ones (repeat 100 1)) + (def select-1 (str "select " (str/join ", " ones))) + (def select-? (into [(str "select " (str/join ", " (map (fn [_] "?") ones)))] ones)) + (time (jdbc/execute-one! (-> a :database :pooled-db :datasource) [select-1])) + (time (jdbc/execute-one! (-> a :database :pooled-db :datasource) select-?)) + (require '[clojure.java.jdbc :as j]) + (time (j/query (-> a :database :pooled-db) [select-1])) + (time (j/query (-> a :database :pooled-db) select-?))) + +(deftest check-prepared-performance + (let [ones (repeat 100 1) + select-1 [(str "select " (str/join ", " ones))] + select-? (into [(str "select " + (str/join ", " (map (fn [_] "?") ones)))] + ones)] + (println "\nSanity check on prepared statement parameter performance.") + (doseq [db (test-specs) + :when (not (or (derby? db) (hsqldb? db)))] + (println " " db) + (time (dotimes [n 100] (sql/query db select-1))) + (time (dotimes [n 100] (sql/query db select-?))) + (sql/with-db-connection [con db] + (time (dotimes [n 100] (sql/query con select-1))) + (time (dotimes [n 100] (sql/query con select-?))))))) + (deftest test-create-table-ddl (is (re-find #"`foo` int default 0" (sql/create-table-ddl :table From 47a87036376ffa69f64cfa18d1f91cbb7e301199 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 10 Oct 2019 17:53:00 -0700 Subject: [PATCH 598/630] Remove Rich Comment Form now it's a real test --- src/test/clojure/clojure/java/jdbc_test.clj | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 94412c44..80800afe 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -1254,16 +1254,6 @@ {:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil} {:id (generated-key db 2) :name "Pear" :appearance "yellow" :cost nil :grade nil}] rows))))) -(comment - (def ones (repeat 100 1)) - (def select-1 (str "select " (str/join ", " ones))) - (def select-? (into [(str "select " (str/join ", " (map (fn [_] "?") ones)))] ones)) - (time (jdbc/execute-one! (-> a :database :pooled-db :datasource) [select-1])) - (time (jdbc/execute-one! (-> a :database :pooled-db :datasource) select-?)) - (require '[clojure.java.jdbc :as j]) - (time (j/query (-> a :database :pooled-db) [select-1])) - (time (j/query (-> a :database :pooled-db) select-?))) - (deftest check-prepared-performance (let [ones (repeat 100 1) select-1 [(str "select " (str/join ", " ones))] From 2acbf2736a30634c9c75e6a1853e970ffa6bdbb4 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 24 Dec 2019 17:40:37 -0800 Subject: [PATCH 599/630] Fix JDBC-179 by only resetting auto-commit conditionally --- CHANGES.md | 4 ++++ README.md | 11 +++++++---- src/main/clojure/clojure/java/jdbc.clj | 23 +++++++++++++++++------ 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 9f5519cc..443e3252 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.7.11 + +* Address edge case in transaction rollback failure [JDBC-179](https://clojure.atlassian.net/browse/JDBC-179). + Changes in 0.7.10 * Use a US-locale `lower-case` function to avoid problems in certain locales (e.g., Turkish). A similar issue has been fixed recently in both HoneySQL and `next.jdbc`. diff --git a/README.md b/README.md index b5ab870f..2b8a38fe 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ clojure.java.jdbc ======================================== -A low-level Clojure wrapper for JDBC-based access to databases. This project is "Stable" (no longer "Active"). It has effectively been superseded by [seancorfield/next.jdbc](https://github.com/seancorfield/next-jdbc). +A low-level Clojure wrapper for JDBC-based access to databases. This project is "Stable" (no longer "Active"). It has effectively been superseded by [seancorfield/next.jdbc](https://github.com/seancorfield/next-jdbc). For higher level DSLs and migration libraries that are compatible, see the [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). @@ -26,7 +26,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.10 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.11 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -34,14 +34,14 @@ Latest stable release: 0.7.10 -- requires Clojure 1.7 or later! [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.10"] +[org.clojure/java.jdbc "0.7.11"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.10 + 0.7.11 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -140,6 +140,9 @@ Developer Information Change Log ==================== +* Release 0.7.11 on 2019-12-24 + * Address edge case in transaction rollback failure [JDBC-179](https://clojure.atlassian.net/browse/JDBC-179). + * Release 0.7.10 on 2019-08-24 * Use a US-locale `lower-case` function to avoid problems in certain locales (e.g., Turkish). A similar issue has been fixed recently in both HoneySQL and `next.jdbc`. * Clean up `db-spec` options that are passed to the JDBC connection manager as properties [JDBC-178](https://clojure.atlassian.net/browse/JDBC-178). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 477996a7..5b8fb94b 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -793,9 +793,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (if (zero? (get-level db)) (if-let [con (db-find-connection db)] (let [nested-db (inc-level db) - auto-commit (.getAutoCommit con) + auto-commit (.getAutoCommit con) old-isolation (.getTransactionIsolation con) - old-readonly (.isReadOnly con)] + old-readonly (.isReadOnly con) + restore-ac? (volatile! true)] (io! (when isolation (.setTransactionIsolation con (isolation isolation-levels))) @@ -805,12 +806,21 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (try (let [result (func nested-db)] (if (db-is-rollback-only nested-db) - (.rollback con) + (do + ;; per JDBC-179: if the rollback operation fails, we do not + ;; want to try to restore auto-commit... + (vreset! restore-ac? false) + (.rollback con) + (vreset! restore-ac? true)) (.commit con)) result) (catch Throwable t (try + ;; per JDBC-179: if the rollback operation fails, we do not + ;; want to try to restore auto-commit... + (vreset! restore-ac? false) (.rollback con) + (vreset! restore-ac? true) (catch Throwable rb ;; combine both exceptions (throw (ex-info (str "Rollback failed handling \"" @@ -825,9 +835,10 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} ;; want those to replace any exception currently being ;; handled -- and if the connection got closed, we just ;; want to ignore exceptions here anyway - (try - (.setAutoCommit con auto-commit) - (catch Exception _)) + (when @restore-ac? + (try ; only restore auto-commit if rollback did not fail + (.setAutoCommit con auto-commit) + (catch Exception _))) (when isolation (try (.setTransactionIsolation con old-isolation) From 36159f259cc51a1dcb9b64ea08f02f0e98c22b5e Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 24 Dec 2019 19:42:05 -0600 Subject: [PATCH 600/630] [maven-release-plugin] prepare release java.jdbc-0.7.11 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7313c02d..65303d76 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.11-SNAPSHOT + 0.7.11 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.11 From 54d2339e16066aed84319c0fb5111f4b2ff22611 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Tue, 24 Dec 2019 19:42:05 -0600 Subject: [PATCH 601/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 65303d76..4d3ac482 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.11 + 0.7.12-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.11 + HEAD From c5cf6719411683b86d310010a1eeca4fcc337314 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Thu, 18 Jun 2020 13:25:24 -0500 Subject: [PATCH 602/630] add LICENSE text file --- LICENSE | 205 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..e246f6a2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,205 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC +LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM +CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation + distributed under this Agreement, and +b) in the case of each subsequent Contributor: + i) changes to the Program, and + ii) additions to the Program; + + where such changes and/or additions to the Program originate from and are + distributed by that particular Contributor. A Contribution 'originates' + from a Contributor if it was added to the Program by such Contributor + itself or anyone acting on such Contributor's behalf. Contributions do not + include additions to the Program which: (i) are separate modules of + software distributed in conjunction with the Program under their own + license agreement, and (ii) are not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are +necessarily infringed by the use or sale of its Contribution alone or when +combined with the Program. + +"Program" means the Contributions distributed in accordance with this +Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, +including all Contributors. + +2. GRANT OF RIGHTS + a) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free copyright license to + reproduce, prepare derivative works of, publicly display, publicly + perform, distribute and sublicense the Contribution of such Contributor, + if any, and such derivative works, in source code and object code form. + b) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free patent license under + Licensed Patents to make, use, sell, offer to sell, import and otherwise + transfer the Contribution of such Contributor, if any, in source code and + object code form. This patent license shall apply to the combination of + the Contribution and the Program if, at the time the Contribution is + added by the Contributor, such addition of the Contribution causes such + combination to be covered by the Licensed Patents. The patent license + shall not apply to any other combinations which include the Contribution. + No hardware per se is licensed hereunder. + c) Recipient understands that although each Contributor grants the licenses + to its Contributions set forth herein, no assurances are provided by any + Contributor that the Program does not infringe the patent or other + intellectual property rights of any other entity. Each Contributor + disclaims any liability to Recipient for claims brought by any other + entity based on infringement of intellectual property rights or + otherwise. As a condition to exercising the rights and licenses granted + hereunder, each Recipient hereby assumes sole responsibility to secure + any other intellectual property rights needed, if any. For example, if a + third party patent license is required to allow Recipient to distribute + the Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + d) Each Contributor represents that to its knowledge it has sufficient + copyright rights in its Contribution, if any, to grant the copyright + license set forth in this Agreement. + +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under +its own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + b) its license agreement: + i) effectively disclaims on behalf of all Contributors all warranties + and conditions, express and implied, including warranties or + conditions of title and non-infringement, and implied warranties or + conditions of merchantability and fitness for a particular purpose; + ii) effectively excludes on behalf of all Contributors all liability for + damages, including direct, indirect, special, incidental and + consequential damages, such as lost profits; + iii) states that any provisions which differ from this Agreement are + offered by that Contributor alone and not by any other party; and + iv) states that source code for the Program is available from such + Contributor, and informs licensees how to obtain it in a reasonable + manner on or through a medium customarily used for software exchange. + +When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + b) a copy of this Agreement must be included with each copy of the Program. + Contributors may not remove or alter any copyright notices contained + within the Program. + +Each Contributor must identify itself as the originator of its Contribution, +if +any, in a manner that reasonably allows subsequent Recipients to identify the +originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with +respect to end users, business partners and the like. While this license is +intended to facilitate the commercial use of the Program, the Contributor who +includes the Program in a commercial product offering should do so in a manner +which does not create potential liability for other Contributors. Therefore, +if a Contributor includes the Program in a commercial product offering, such +Contributor ("Commercial Contributor") hereby agrees to defend and indemnify +every other Contributor ("Indemnified Contributor") against any losses, +damages and costs (collectively "Losses") arising from claims, lawsuits and +other legal actions brought by a third party against the Indemnified +Contributor to the extent caused by the acts or omissions of such Commercial +Contributor in connection with its distribution of the Program in a commercial +product offering. The obligations in this section do not apply to any claims +or Losses relating to any actual or alleged intellectual property +infringement. In order to qualify, an Indemnified Contributor must: +a) promptly notify the Commercial Contributor in writing of such claim, and +b) allow the Commercial Contributor to control, and cooperate with the +Commercial Contributor in, the defense and any related settlement +negotiations. The Indemnified Contributor may participate in any such claim at +its own expense. + +For example, a Contributor might include the Program in a commercial product +offering, Product X. That Contributor is then a Commercial Contributor. If +that Commercial Contributor then makes performance claims, or offers +warranties related to Product X, those performance claims and warranties are +such Commercial Contributor's responsibility alone. Under this section, the +Commercial Contributor would have to defend claims against the other +Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR +IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each +Recipient is solely responsible for determining the appropriateness of using +and distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement , including but not limited to the +risks and costs of program errors, compliance with applicable laws, damage to +or loss of data, programs or equipment, and unavailability or interruption of +operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY +CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION +LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE +EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of the +remainder of the terms of this Agreement, and without further action by the +parties hereto, such provision shall be reformed to the minimum extent +necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Program itself +(excluding combinations of the Program with other software or hardware) +infringes such Recipient's patent(s), then such Recipient's rights granted +under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to +comply with any of the material terms or conditions of this Agreement and does +not cure such failure in a reasonable period of time after becoming aware of +such noncompliance. If all Recipient's rights under this Agreement terminate, +Recipient agrees to cease use and distribution of the Program as soon as +reasonably practicable. However, Recipient's obligations under this Agreement +and any licenses granted by Recipient relating to the Program shall continue +and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in +order to avoid inconsistency the Agreement is copyrighted and may only be +modified in the following manner. The Agreement Steward reserves the right to +publish new versions (including revisions) of this Agreement from time to +time. No one other than the Agreement Steward has the right to modify this +Agreement. The Eclipse Foundation is the initial Agreement Steward. The +Eclipse Foundation may assign the responsibility to serve as the Agreement +Steward to a suitable separate entity. Each new version of the Agreement will +be given a distinguishing version number. The Program (including +Contributions) may always be distributed subject to the version of the +Agreement under which it was received. In addition, after a new version of the +Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly +stated in Sections 2(a) and 2(b) above, Recipient receives no rights or +licenses to the intellectual property of any Contributor under this Agreement, +whether expressly, by implication, estoppel or otherwise. All rights in the +Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the +intellectual property laws of the United States of America. No party to this +Agreement will bring a legal action under this Agreement more than one year +after the cause of action arose. Each party waives its rights to a jury trial in +any resulting litigation. + + From c99db253ea85f2ade4b71eff20476f6c6061d571 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 1 Sep 2020 13:10:26 -0700 Subject: [PATCH 603/630] Add deps.edn style coordinates --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2b8a38fe..35909d3f 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,10 @@ Latest stable release: 0.7.11 -- requires Clojure 1.7 or later! * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~) +[CLI/`deps.edn`](https://clojure.org/guides/deps_and_cli) dependency information: +```clojure +org.clojure/java.jdbc {:mvn/version "0.7.11"} +``` [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure [org.clojure/java.jdbc "0.7.11"] From 7c2cda1d8510e76408dea9a4b047233034e1d066 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Tue, 1 Sep 2020 13:19:54 -0700 Subject: [PATCH 604/630] Link to CLI/deps.edn reference --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35909d3f..cdb2ef78 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Latest stable release: 0.7.11 -- requires Clojure 1.7 or later! * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~) -[CLI/`deps.edn`](https://clojure.org/guides/deps_and_cli) dependency information: +[CLI/`deps.edn`](https://clojure.org/reference/deps_and_cli) dependency information: ```clojure org.clojure/java.jdbc {:mvn/version "0.7.11"} ``` From 21512f86a1abd0a42e2174b7239329af6e3c9d9e Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Mon, 1 Feb 2021 09:45:25 -0800 Subject: [PATCH 605/630] Prep for 0.7.12 with metadata-extensible protocols --- CHANGES.md | 4 ++++ README.md | 11 +++++++---- src/main/clojure/clojure/java/jdbc.clj | 6 +++--- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 443e3252..b0d25b80 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes in 0.7.12 + +* Make the protocols `ISQLValue`, `ISQLParameter`, and `IResultSetReadColumn` extensible via metadata. + Changes in 0.7.11 * Address edge case in transaction rollback failure [JDBC-179](https://clojure.atlassian.net/browse/JDBC-179). diff --git a/README.md b/README.md index cdb2ef78..52ea9bfa 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.11 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.12 -- requires Clojure 1.7 or later! * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) @@ -34,18 +34,18 @@ Latest stable release: 0.7.11 -- requires Clojure 1.7 or later! [CLI/`deps.edn`](https://clojure.org/reference/deps_and_cli) dependency information: ```clojure -org.clojure/java.jdbc {:mvn/version "0.7.11"} +org.clojure/java.jdbc {:mvn/version "0.7.12"} ``` [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.11"] +[org.clojure/java.jdbc "0.7.12"] ``` [Maven](http://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.11 + 0.7.12 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -144,6 +144,9 @@ Developer Information Change Log ==================== +* Release 0.7.12 on 2021-02-01 + * Make the protocols `ISQLValue`, `ISQLParameter`, and `IResultSetReadColumn` extensible via metadata. + * Release 0.7.11 on 2019-12-24 * Address edge case in transaction rollback failure [JDBC-179](https://clojure.atlassian.net/browse/JDBC-179). diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index 5b8fb94b..e90c8850 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -454,7 +454,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (vswap! seen assoc input 2) (xf result input))))))) -(defprotocol ISQLValue +(defprotocol ISQLValue :extend-via-metadata true "Protocol for creating SQL values from Clojure values. Default implementations (for Object and nil) just return the argument, but it can be extended to provide custom behavior to support @@ -468,7 +468,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} nil (sql-value [_] nil)) -(defprotocol ISQLParameter +(defprotocol ISQLParameter :extend-via-metadata true "Protocol for setting SQL parameters in statement objects, which can convert from Clojure values. The default implementation just delegates the conversion to ISQLValue's sql-value conversion and @@ -495,7 +495,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (set-parameter (first values) stmt ix) (recur (inc ix) (rest values))))) -(defprotocol IResultSetReadColumn +(defprotocol IResultSetReadColumn :extend-via-metadata true "Protocol for reading objects from the java.sql.ResultSet. Default implementations (for Object and nil) return the argument, and the Boolean implementation ensures a canonicalized true/false value, From ccf6236c2a1905cd8e4a3f7edffcf3dd18ccce12 Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 1 Feb 2021 22:02:37 -0600 Subject: [PATCH 606/630] [maven-release-plugin] prepare release java.jdbc-0.7.12 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 4d3ac482..f4049449 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.12-SNAPSHOT + 0.7.12 java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - HEAD + java.jdbc-0.7.12 From 51b1870ff7f236d47b63bca9e2e3b1b14d0128db Mon Sep 17 00:00:00 2001 From: "Hudson @ build.clojure.org" Date: Mon, 1 Feb 2021 22:02:37 -0600 Subject: [PATCH 607/630] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index f4049449..7dd53757 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 java.jdbc - 0.7.12 + 0.7.13-SNAPSHOT java.jdbc @@ -24,7 +24,7 @@ scm:git:git@github.com:clojure/java.jdbc.git scm:git:git@github.com:clojure/java.jdbc.git git@github.com:clojure/java.jdbc.git - java.jdbc-0.7.12 + HEAD From acffd9f5f216f8b8c1fc960c1d47b0b5feb56730 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Thu, 18 Feb 2021 09:31:27 -0600 Subject: [PATCH 608/630] update old links --- CHANGES.md | 214 +++++++++++++++++++++---------------------- README.md | 263 ++++++++++++++++++++++++++--------------------------- 2 files changed, 236 insertions(+), 241 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b0d25b80..4a6aba18 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -101,30 +101,30 @@ Changes in 0.7.0-beta1 Changes in 0.7.0-alpha3 -* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://clojure.atlassian.net/browse/JDBC-151). +* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](https://clojure.atlassian.net/browse/JDBC-151). * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. Changes in 0.7.0-alpha2 -* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://clojure.atlassian.net/browse/JDBC-150). -* `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://clojure.atlassian.net/browse/JDBC-149). -* Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://clojure.atlassian.net/browse/JDBC-148). -* Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://clojure.atlassian.net/browse/JDBC-145). +* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](https://clojure.atlassian.net/browse/JDBC-150). +* `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](https://clojure.atlassian.net/browse/JDBC-149). +* Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](https://clojure.atlassian.net/browse/JDBC-148). +* Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](https://clojure.atlassian.net/browse/JDBC-145). Changes in 0.7.0-alpha1 -- potentially breaking changes * The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting). -* Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://clojure.atlassian.net/browse/JDBC-147). -* All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://clojure.atlassian.net/browse/JDBC-144). -* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://clojure.atlassian.net/browse/JDBC-141). -* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://clojure.atlassian.net/browse/JDBC-137). +* Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](https://clojure.atlassian.net/browse/JDBC-147). +* All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](https://clojure.atlassian.net/browse/JDBC-144). +* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](https://clojure.atlassian.net/browse/JDBC-141). +* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](https://clojure.atlassian.net/browse/JDBC-137). * Expanded optional `clojure.spec` coverage to almost the whole library API. Changes in 0.6.2-alpha3 -* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://clojure.atlassian.net/browse/JDBC-140). -* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://clojure.atlassian.net/browse/JDBC-139). -* Fixed postgres / postgresql alias support [JDBC-138](http://clojure.atlassian.net/browse/JDBC-138). +* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](https://clojure.atlassian.net/browse/JDBC-140). +* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](https://clojure.atlassian.net/browse/JDBC-139). +* Fixed postgres / postgresql alias support [JDBC-138](https://clojure.atlassian.net/browse/JDBC-138). This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). Changes in 0.6.2-alpha2 @@ -134,46 +134,46 @@ Changes in 0.6.2-alpha2 Changes in 0.6.2-alpha1 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). -* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://clojure.atlassian.net/browse/JDBC-136). -* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://clojure.atlassian.net/browse/JDBC-135). -* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://clojure.atlassian.net/browse/JDBC-134). -* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://clojure.atlassian.net/browse/JDBC-133). +* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](https://clojure.atlassian.net/browse/JDBC-136). +* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](https://clojure.atlassian.net/browse/JDBC-135). +* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](https://clojure.atlassian.net/browse/JDBC-134). +* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](https://clojure.atlassian.net/browse/JDBC-133). Changes in 0.6.1 -* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://clojure.atlassian.net/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. -* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://clojure.atlassian.net/browse/JDBC-127) and [JDBC-129](http://clojure.atlassian.net/browse/JDBC-129). +* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](https://clojure.atlassian.net/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. +* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](https://clojure.atlassian.net/browse/JDBC-127) and [JDBC-129](https://clojure.atlassian.net/browse/JDBC-129). Changes in 0.6.0 -* `find-by-keys` now correctly handles `nil` values [JDBC-126](http://clojure.atlassian.net/browse/JDBC-126). +* `find-by-keys` now correctly handles `nil` values [JDBC-126](https://clojure.atlassian.net/browse/JDBC-126). * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. Changes in 0.6.0-rc2 -* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). +* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](https://clojure.atlassian.net/browse/JDBC-125). - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. * `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. * `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. -* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). +* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](https://clojure.atlassian.net/browse/JDBC-125). * `find-by-keys` now accepts an `:order-by` option that specifies a sequence of orderings; an ordering is either a column (to sort ascending) or a map from column name to direct (`:asc` or `:desc`). Changes in 0.6.0-rc1 * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). -* REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). +* REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](https://clojure.atlassian.net/browse/JDBC-118). - See alpha2 / alpha1 below for more details. Changes in 0.6.0-alpha2 -* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). - - This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1. -* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://clojure.atlassian.net/browse/JDBC-124). -* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://clojure.atlassian.net/browse/JDBC-123). +* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](https://clojure.atlassian.net/browse/JDBC-118). + - This removes deprecated functionality from db-do-commands and `db-do-prepared*` which should have been removed in Alpha 1. +* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](https://clojure.atlassian.net/browse/JDBC-124). +* Fix typo in `insert-multi!` argument validation exception [JDBC-123](https://clojure.atlassian.net/browse/JDBC-123). Changes in 0.6.0-alpha1 -* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). +* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](https://clojure.atlassian.net/browse/JDBC-118). - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed @@ -181,73 +181,73 @@ Changes in 0.6.0-alpha1 Changes in 0.5.8 -* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. -* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. +* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](https://clojure.atlassian.net/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. +* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](https://clojure.atlassian.net/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. Changes in 0.5.7 -* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://clojure.atlassian.net/browse/JDBC-121). +* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](https://clojure.atlassian.net/browse/JDBC-121). Changes in 0.5.6 -* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://clojure.atlassian.net/browse/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. -* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://clojure.atlassian.net/browse/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. +* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](https://clojure.atlassian.net/browse/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. +* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](https://clojure.atlassian.net/browse/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. * NOTE: all deprecated functionality will go away in version 0.6.0! Changes in 0.5.5 -* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://clojure.atlassian.net/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. +* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](https://clojure.atlassian.net/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. Changes in 0.5.0 -* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://clojure.atlassian.net/browse/JDBC-115). -* Remove exception wrapping [JDBC-114](http://clojure.atlassian.net/browse/JDBC-114). +* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](https://clojure.atlassian.net/browse/JDBC-115). +* Remove exception wrapping [JDBC-114](https://clojure.atlassian.net/browse/JDBC-114). * Drop Clojure 1.3 compatibility. Changes in 0.4.2 -* Remove redundant type hints [JDBC-113](http://clojure.atlassian.net/browse/JDBC-113) - Michael Blume. -* Avoid reflection on `.prepareStatement` [JDBC-112](http://clojure.atlassian.net/browse/JDBC-112) - Michael Blume. -* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://clojure.atlassian.net/browse/JDBC-107). -* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://clojure.atlassian.net/browse/JDBC-104). -* Officially support H2 (and test against it) to support [JDBC-91](http://clojure.atlassian.net/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. +* Remove redundant type hints [JDBC-113](https://clojure.atlassian.net/browse/JDBC-113) - Michael Blume. +* Avoid reflection on `.prepareStatement` [JDBC-112](https://clojure.atlassian.net/browse/JDBC-112) - Michael Blume. +* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](https://clojure.atlassian.net/browse/JDBC-107). +* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](https://clojure.atlassian.net/browse/JDBC-104). +* Officially support H2 (and test against it) to support [JDBC-91](https://clojure.atlassian.net/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. Changes in 0.4.0 / 0.4.1 -* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://clojure.atlassian.net/browse/JDBC-111) - Stefan Kamphausen. -* Nested transaction checks isolation level is the same [JDBC-110](http://clojure.atlassian.net/browse/JDBC-110) - Donald Ball. -* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://clojure.atlassian.net/browse/JDBC-109). +* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](https://clojure.atlassian.net/browse/JDBC-111) - Stefan Kamphausen. +* Nested transaction checks isolation level is the same [JDBC-110](https://clojure.atlassian.net/browse/JDBC-110) - Donald Ball. +* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](https://clojure.atlassian.net/browse/JDBC-109). * Drop Clojure 1.2 compatibility. Changes in 0.3.7 * Bump all driver versions in `project.clj` and re-test. -* Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://clojure.atlassian.net/browse/JDBC-108) - Earl St Sauver. -* Remove driver versions from README and link to Maven Central [JDBC-106](http://clojure.atlassian.net/browse/JDBC-106). -* Fix links in CHANGES and README [JDBC-103](http://clojure.atlassian.net/browse/JDBC-103) - John Walker. +* Remove duplicate `count` calls in `insert-sql` [JDBC-108](https://clojure.atlassian.net/browse/JDBC-108) - Earl St Sauver. +* Remove driver versions from README and link to Maven Central [JDBC-106](https://clojure.atlassian.net/browse/JDBC-106). +* Fix links in CHANGES and README [JDBC-103](https://clojure.atlassian.net/browse/JDBC-103) - John Walker. Changes in 0.3.6 -* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://clojure.atlassian.net/browse/JDBC-102). -* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://clojure.atlassian.net/browse/JDBC-101). -* Add `:timeout` argument to `prepare-statement` [JDBC-100](http://clojure.atlassian.net/browse/JDBC-100). +* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://clojure.atlassian.net/browse/JDBC-102). +* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://clojure.atlassian.net/browse/JDBC-101). +* Add `:timeout` argument to `prepare-statement` [JDBC-100](https://clojure.atlassian.net/browse/JDBC-100). Changes in 0.3.5 * Reflection warnings on executeUpdate addressed. -* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://clojure.atlassian.net/browse/JDBC-94). -* Add support for readonly transactions via :read-only? [JDBC-93](http://clojure.atlassian.net/browse/JDBC-93). +* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://clojure.atlassian.net/browse/JDBC-94). +* Add support for readonly transactions via :read-only? [JDBC-93](https://clojure.atlassian.net/browse/JDBC-93). Changes in 0.3.4 -* execute! can now accept a PreparedStatement [JDBC-96](http://clojure.atlassian.net/browse/JDBC-96). -* Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). -* Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://clojure.atlassian.net/browse/JDBC-90). +* execute! can now accept a PreparedStatement [JDBC-96](https://clojure.atlassian.net/browse/JDBC-96). +* Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](https://clojure.atlassian.net/browse/JDBC-92). +* Support oracle:oci and oracle:thin subprotocols [JDBC-90](https://clojure.atlassian.net/browse/JDBC-90). Changes in 0.3.3 -* Prevent exception/crash when query called with bare SQL string [JDBC-89](http://clojure.atlassian.net/browse/JDBC-89). -* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://clojure.atlassian.net/browse/JDBC-87). +* Prevent exception/crash when query called with bare SQL string [JDBC-89](https://clojure.atlassian.net/browse/JDBC-89). +* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](https://clojure.atlassian.net/browse/JDBC-87). * Support key/value configuration from URI (Phil Hagelberg). Changes in 0.3.2 @@ -258,25 +258,25 @@ Changes in 0.3.1 (broken) * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! -* Provide better protocol for setting parameters in prepared statements [JDBC-86](http://clojure.atlassian.net/browse/JDBC-86). -* Fix parens in two deprecated tests [JDBC-85](http://clojure.atlassian.net/browse/JDBC-85). +* Provide better protocol for setting parameters in prepared statements [JDBC-86](https://clojure.atlassian.net/browse/JDBC-86). +* Fix parens in two deprecated tests [JDBC-85](https://clojure.atlassian.net/browse/JDBC-85). * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. Changes in 0.3.0 -* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://clojure.atlassian.net/browse/JDBC-84). -* Rename recently introduced test to ensure unique names [JDBC-83](http://clojure.atlassian.net/browse/JDBC-83). -* Rename unused arguments in protocol implementation to support Android [JDBC-82](http://clojure.atlassian.net/browse/JDBC-82). -* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://clojure.atlassian.net/browse/JDBC-65). +* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](https://clojure.atlassian.net/browse/JDBC-84). +* Rename recently introduced test to ensure unique names [JDBC-83](https://clojure.atlassian.net/browse/JDBC-83). +* Rename unused arguments in protocol implementation to support Android [JDBC-82](https://clojure.atlassian.net/browse/JDBC-82). +* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](https://clojure.atlassian.net/browse/JDBC-65). Changes in 0.3.0-rc1 -* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://clojure.atlassian.net/browse/JDBC-81). -* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://clojure.atlassian.net/browse/JDBC-80). -* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://clojure.atlassian.net/browse/JDBC-79). -* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://clojure.atlassian.net/browse/JDBC-77). -* Add support for :isolation in with-db-transaction [JDBC-75](http://clojure.atlassian.net/browse/JDBC-75). -* Add :user as an alias for :username for DataSource connections [JDBC-74](http://clojure.atlassian.net/browse/JDBC-74). +* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](https://clojure.atlassian.net/browse/JDBC-81). +* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](https://clojure.atlassian.net/browse/JDBC-80). +* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](https://clojure.atlassian.net/browse/JDBC-79). +* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](https://clojure.atlassian.net/browse/JDBC-77). +* Add support for :isolation in with-db-transaction [JDBC-75](https://clojure.atlassian.net/browse/JDBC-75). +* Add :user as an alias for :username for DataSource connections [JDBC-74](https://clojure.atlassian.net/browse/JDBC-74). Changes in 0.3.0-beta2 @@ -285,48 +285,48 @@ Changes in 0.3.0-beta2 Changes in 0.3.0-beta1 -* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://clojure.atlassian.net/browse/JDBC-72). +* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](https://clojure.atlassian.net/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver -* Tests no longer use :1 literal [JDBC-71](http://clojure.atlassian.net/browse/JDBC-71). -* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://clojure.atlassian.net/browse/JDBC-69). -* New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://clojure.atlassian.net/browse/JDBC-63). -* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40). +* Tests no longer use :1 literal [JDBC-71](https://clojure.atlassian.net/browse/JDBC-71). +* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](https://clojure.atlassian.net/browse/JDBC-69). +* New db-query-with-resultset function replaces private `db-with-query-results*` and processes a raw ResultSet object [JDBC-63](https://clojure.atlassian.net/browse/JDBC-63). +* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](https://clojure.atlassian.net/browse/JDBC-40). Changes in 0.3.0-alpha5 -* DDL now supports entities naming strategy [JDBC-53](http://clojure.atlassian.net/browse/JDBC-53). +* DDL now supports entities naming strategy [JDBC-53](https://clojure.atlassian.net/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). -* Added create-index / drop-index DDL [JDBC-62](http://clojure.atlassian.net/browse/JDBC-62) - moquist -* Make transaction? boolean optional in various db-do-* functions +* Added create-index / drop-index DDL [JDBC-62](https://clojure.atlassian.net/browse/JDBC-62) - moquist +* Make transaction? boolean optional in various `db-do-*` functions * Create clojure.java.jdbc.ddl namespace * Add create-table, drop-table, create-index and drop-index * Deprecate create-table, create-table-ddl and drop-table in main namespace * Update README to clarify PostgreSQL instructions. -* Fix test suite for PostgreSQL [JDBC-59](http://clojure.atlassian.net/browser/JDBC-59) -* Improve hooks for Oracle data type handling [JDBC-57](http://clojure.atlassian.net/browser/JDBC-57) -* Fix reflection warnings [JDBC-55](http://clojure.atlassian.net/browser/JDBC-55) +* Fix test suite for PostgreSQL [JDBC-59](https://clojure.atlassian.net/browser/JDBC-59) +* Improve hooks for Oracle data type handling [JDBC-57](https://clojure.atlassian.net/browser/JDBC-57) +* Fix reflection warnings [JDBC-55](https://clojure.atlassian.net/browser/JDBC-55) -* DDL now supports entities naming strategy [JDBC-53](http://clojure.atlassian.net/browse/JDBC-53). +* DDL now supports entities naming strategy [JDBC-53](https://clojure.atlassian.net/browse/JDBC-53). * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). -* Added create-index / drop-index DDL [JDBC-62](http://clojure.atlassian.net/browse/JDBC-62) - moquist -* Make transaction? boolean optional in various db-do-* functions - * It will ultimately change to a function argument I think when [JDBC-37](http://clojure.atlassian.net/browser/JDBC-37) is dealt with +* Added create-index / drop-index DDL [JDBC-62](https://clojure.atlassian.net/browse/JDBC-62) - moquist +* Make transaction? boolean optional in various `db-do-*` functions + * It will ultimately change to a function argument I think when [JDBC-37](https://clojure.atlassian.net/browser/JDBC-37) is dealt with * Create clojure.java.jdbc.ddl namespace * Add create-table and drop-table * Deprecate create-table, create-table-ddl and drop-table in main namespace * More DDL is coming soon * Update README to clarify PostgreSQL instructions. -* Fix test suite for PostgreSQL [JDBC-59](http://clojure.atlassian.net/browser/JDBC-59) -* Improve hooks for Oracle data type handling [JDBC-57](http://clojure.atlassian.net/browser/JDBC-57) -* Fix reflection warnings [JDBC-55](http://clojure.atlassian.net/browser/JDBC-55) +* Fix test suite for PostgreSQL [JDBC-59](https://clojure.atlassian.net/browser/JDBC-59) +* Improve hooks for Oracle data type handling [JDBC-57](https://clojure.atlassian.net/browser/JDBC-57) +* Fix reflection warnings [JDBC-55](https://clojure.atlassian.net/browser/JDBC-55) Changes in 0.3.0-alpha4 -* Fix connection leaks [JDBC-54](http://clojure.atlassian.net/browser/JDBC-54) +* Fix connection leaks [JDBC-54](https://clojure.atlassian.net/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) Changes in 0.3.0-alpha3 @@ -335,10 +335,10 @@ Changes in 0.3.0-alpha3 Changes in 0.3.0-alpha2 -* Address [JDBC-51](http://clojure.atlassian.net/browse/JDBC-51) by declaring get-connection returns java.sql.Connection -* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://clojure.atlassian.net/browse/JDBC-46) -* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://clojure.atlassian.net/browse/JDBC-52) -* Reverted specialized handling of NULL values (reopens [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40)) +* Address [JDBC-51](https://clojure.atlassian.net/browse/JDBC-51) by declaring get-connection returns java.sql.Connection +* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](https://clojure.atlassian.net/browse/JDBC-46) +* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](https://clojure.atlassian.net/browse/JDBC-52) +* Reverted specialized handling of NULL values (reopens [JDBC-40](https://clojure.atlassian.net/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean * Add curried version of clojure.java.jdbc.sql/as-quoted-str * Officially deprecate resultset-seq @@ -348,7 +348,7 @@ Changes in 0.3.0-alpha1 Major overhaul of the API and deprecation of most of the old API! * Add insert!, query, update!, delete! and execute! high-level API - [JDBC-20](http://clojure.atlassian.net/browse/JDBC-20) + [JDBC-20](https://clojure.atlassian.net/browse/JDBC-20) * Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20) * Add db- prefixed versions of low-level API * Add db-transaction macro: @@ -360,16 +360,16 @@ Major overhaul of the API and deprecation of most of the old API! * Add result-set-seq as replacement for resultset-seq (which will be deprecated) * Transaction now correctly rollback on non-Exception Throwables - [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) + [JDBC-43](https://clojure.atlassian.net/browse/JDBC-43) * Rewrite old API functions in terms of new API, and deprecate old API - [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) + [JDBC-43](https://clojure.atlassian.net/browse/JDBC-43) * Add :as-arrays to query / result-set-seq - [JDBC-41](http://clojure.atlassian.net/browse/JDBC-41) -* Better handling of NULL values [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40) - and [JDBC-18](http://clojure.atlassian.net/browse/JDBC-18) + [JDBC-41](https://clojure.atlassian.net/browse/JDBC-41) +* Better handling of NULL values [JDBC-40](https://clojure.atlassian.net/browse/JDBC-40) + and [JDBC-18](https://clojure.atlassian.net/browse/JDBC-18) Note: JDBC-40 has been reverted in 0.3.0-alpha2 because it introduced regressions for PostgreSQL * db-do-commands allows you to execute SQL without a transaction wrapping it - [JDBC-38](http://clojure.atlassian.net/browse/JDBC-38) + [JDBC-38](https://clojure.atlassian.net/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy @@ -377,18 +377,18 @@ Major overhaul of the API and deprecation of most of the old API! Changes in 0.2.3: * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] -* Add :connection-uri option [JDBC-34](http://clojure.atlassian.net/browse/JDBC-34) +* Add :connection-uri option [JDBC-34](https://clojure.atlassian.net/browse/JDBC-34) Changes in 0.2.2: -* Handle Oracle unknown row count affected [JDBC-33](http://clojure.atlassian.net/browse/JDBC-33) -* Handle jdbc: prefix in string db-specs [JDBC-32](http://clojure.atlassian.net/browse/JDBC-32) -* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://clojure.atlassian.net/browse/JDBC-31) +* Handle Oracle unknown row count affected [JDBC-33](https://clojure.atlassian.net/browse/JDBC-33) +* Handle jdbc: prefix in string db-specs [JDBC-32](https://clojure.atlassian.net/browse/JDBC-32) +* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](https://clojure.atlassian.net/browse/JDBC-31) Changes in 0.2.1: -* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://clojure.atlassian.net/browse/JDBC-29) -* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://clojure.atlassian.net/browse/JDBC-30) +* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](https://clojure.atlassian.net/browse/JDBC-29) +* Make do-prepared-return-keys (for Korma team) [JDBC-30](https://clojure.atlassian.net/browse/JDBC-30) Changes in 0.2.0: @@ -462,7 +462,7 @@ Changes in 0.0.4: * Fix JDBC-8 by removing all reflection warnings * Fix JDBC-11 by no longer committing the transaction when an Error occurs * Clean up as-... functions to reduce use of (binding) -* Refactor do-prepared*, separating out return keys logic and parameter setting logic +* Refactor `do-prepared*`, separating out return keys logic and parameter setting logic - in preparation for exposing more hooks in PreparedStatement creation / manipulation Changes in 0.0.3: @@ -475,9 +475,9 @@ Changes in 0.0.2: Changes in 0.0.1 (compared to clojure.contrib.sql): -* Exposed print-... functions for exception printing; no longer writes exceptions to *out* +* Exposed print-... functions for exception printing; no longer writes exceptions to `*out*` * Add clojure.java.jdbc/resultset-seq (to replace clojure.core/resultset-seq which should be deprecated) -* Add support for naming and quoting strategies - see http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/NameMapping.html +* Add support for naming and quoting strategies - see https://clojure.github.io/java.jdbc/doc/clojure/java/jdbc/NameMapping.html - The formatting is a bit borked, Tom F knows about this and is working on an enhancement to auto-doc to improve it * Add ability to return generated keys from single insert operations, add insert-record function * Clojure 1.3 compatibility diff --git a/README.md b/README.md index 52ea9bfa..338996f7 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,7 @@ This library is mature and stable. It is widely used and its use is described in Documentation ======================================== -* [API Reference](http://clojure.github.com/java.jdbc/) (Autogenerated) - +* [API Reference](https://clojure.github.io/java.jdbc/) (Autogenerated) * [Overview](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * [Manipulating Data with SQL](http://clojure-doc.org/articles/ecosystem/java_jdbc/using_sql.html) * [How to Reuse Database Connections](http://clojure-doc.org/articles/ecosystem/java_jdbc/reusing_connections.html) @@ -28,8 +27,7 @@ Releases and Dependency Information Latest stable release: 0.7.12 -- requires Clojure 1.7 or later! -* [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) - +* [All Released Versions](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~) [CLI/`deps.edn`](https://clojure.org/reference/deps_and_cli) dependency information: @@ -40,7 +38,7 @@ org.clojure/java.jdbc {:mvn/version "0.7.12"} ```clojure [org.clojure/java.jdbc "0.7.12"] ``` -[Maven](http://maven.apache.org/) dependency information: +[Maven](https://maven.apache.org/) dependency information: ```xml org.clojure @@ -52,14 +50,14 @@ _Note: Earlier versions of Clojure are supported by older versions of `clojure.j You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with: -* [Apache Derby](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.derby%22%20AND%20a%3A%22derby%22) -* [H2](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.h2database%22%20AND%20a%3A%22h2%22) -* [HSQLDB](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22hsqldb%22%20AND%20a%3A%22hsqldb%22) -* [Microsoft SQL Server jTDS](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.jtds%22%20AND%20a%3A%22jtds%22) -* [Microsoft SQL Server -- Official MS Version](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.microsoft.sqlserver%22%20AND%20a%3A%22mssql-jdbc%22) -* [MySQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22mysql%22%20AND%20a%3A%22mysql-connector-java%22) -* [PostgreSQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.postgresql%22%20AND%20a%3A%22postgresql%22) -* [SQLite](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.xerial%22%20AND%20a%3A%22sqlite-jdbc%22) +* [Apache Derby](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.derby%22%20AND%20a%3A%22derby%22) +* [H2](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.h2database%22%20AND%20a%3A%22h2%22) +* [HSQLDB](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22hsqldb%22%20AND%20a%3A%22hsqldb%22) +* [Microsoft SQL Server jTDS](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.jtds%22%20AND%20a%3A%22jtds%22) +* [Microsoft SQL Server -- Official MS Version](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.microsoft.sqlserver%22%20AND%20a%3A%22mssql-jdbc%22) +* [MySQL](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22mysql%22%20AND%20a%3A%22mysql-connector-java%22) +* [PostgreSQL](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.postgresql%22%20AND%20a%3A%22postgresql%22) +* [SQLite](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.xerial%22%20AND%20a%3A%22sqlite-jdbc%22) Note: different versions of various database drivers have different Java/JVM version requirements. In particular, recent versions of Apache Derby require at least Java 8 and recent versions of H2 require at least Java 7. Clojure's Continuous Integration system uses older versions so tests can be run on Java 6 (see `pom.xml`); local testing is done with more recent versions on Java 8. @@ -108,18 +106,15 @@ Example Usage {:row-fn :cost}) ;; (24) ``` -For more detail see the [API reference](http://clojure.github.com/java.jdbc/) or [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). +For more detail see the [API reference](https://clojure.github.io/java.jdbc/) or [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). Developer Information ======================================== * [GitHub project](https://github.com/clojure/java.jdbc) - -* [Bug Tracker](http://clojure.atlassian.net/browse/JDBC) - -* [Continuous Integration](http://build.clojure.org/job/java.jdbc/) - -* [Compatibility Test Matrix](http://build.clojure.org/job/java.jdbc-test-matrix/) +* [Bug Tracker](https://clojure.atlassian.net/browse/JDBC) +* [Continuous Integration](https://build.clojure.org/job/java.jdbc/) +* [Compatibility Test Matrix](https://build.clojure.org/job/java.jdbc-test-matrix/) * Testing: * Currently by default tests run only against Derby and HSQLDB, the in-process databases. @@ -228,27 +223,27 @@ Change Log * `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://clojure.atlassian.net/browse/JDBC-99). * Release 0.7.0-alpha3 on 2017-03-23 - * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://clojure.atlassian.net/browse/JDBC-151). + * `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](https://clojure.atlassian.net/browse/JDBC-151). * `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name. * Release 0.7.0-alpha2 on 2017-03-01 - * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://clojure.atlassian.net/browse/JDBC-150). - * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://clojure.atlassian.net/browse/JDBC-149). - * Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://clojure.atlassian.net/browse/JDBC-148). - * Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://clojure.atlassian.net/browse/JDBC-145). + * `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](https://clojure.atlassian.net/browse/JDBC-150). + * `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](https://clojure.atlassian.net/browse/JDBC-149). + * Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](https://clojure.atlassian.net/browse/JDBC-148). + * Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](https://clojure.atlassian.net/browse/JDBC-145). * Release 0.7.0-alpha1 on 2016-11-12 -- potentially breaking changes * The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting). - * Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://clojure.atlassian.net/browse/JDBC-147). - * All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://clojure.atlassian.net/browse/JDBC-144). - * Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://clojure.atlassian.net/browse/JDBC-141). - * Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://clojure.atlassian.net/browse/JDBC-137). + * Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](https://clojure.atlassian.net/browse/JDBC-147). + * All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](https://clojure.atlassian.net/browse/JDBC-144). + * Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](https://clojure.atlassian.net/browse/JDBC-141). + * Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](https://clojure.atlassian.net/browse/JDBC-137). * Expanded optional `clojure.spec` coverage to almost the whole library API. * Release 0.6.2-alpha3 on 2016-08-25 - * Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://clojure.atlassian.net/browse/JDBC-140). - * Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://clojure.atlassian.net/browse/JDBC-139). - * Fixed postgres / postgresql alias support [JDBC-138](http://clojure.atlassian.net/browse/JDBC-138). + * Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](https://clojure.atlassian.net/browse/JDBC-140). + * Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](https://clojure.atlassian.net/browse/JDBC-139). + * Fixed postgres / postgresql alias support [JDBC-138](https://clojure.atlassian.net/browse/JDBC-138). This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb). * Release 0.6.2-alpha2 on 2016-07-21 @@ -256,94 +251,94 @@ Change Log * Release 0.6.2-alpha1 on 2016-07-05 * Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later). - * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://clojure.atlassian.net/browse/JDBC-136). - * `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://clojure.atlassian.net/browse/JDBC-135). - * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://clojure.atlassian.net/browse/JDBC-134). - * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://clojure.atlassian.net/browse/JDBC-133). + * All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](https://clojure.atlassian.net/browse/JDBC-136). + * `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](https://clojure.atlassian.net/browse/JDBC-135). + * `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](https://clojure.atlassian.net/browse/JDBC-134). + * In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](https://clojure.atlassian.net/browse/JDBC-133). * Release 0.6.1 on 2016-05-12 -- **IMPORTANT BUG FIX!** - * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://clojure.atlassian.net/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. - * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://clojure.atlassian.net/browse/JDBC-127) and [JDBC-129](http://clojure.atlassian.net/browse/JDBC-129). + * `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](https://clojure.atlassian.net/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values. + * PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](https://clojure.atlassian.net/browse/JDBC-127) and [JDBC-129](https://clojure.atlassian.net/browse/JDBC-129). * Release 0.6.0 on 2016-05-11 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!** - * `find-by-keys` now correctly handles `nil` values [JDBC-126](http://clojure.atlassian.net/browse/JDBC-126). 0.6.0 / 2016-05-11. + * `find-by-keys` now correctly handles `nil` values [JDBC-126](https://clojure.atlassian.net/browse/JDBC-126). 0.6.0 / 2016-05-11. * `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. 0.6.0 / 2016-05-11. - * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. + * `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](https://clojure.atlassian.net/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. - Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell. * `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. 0.6.0-rc2 / 2016-05-07. * `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. 0.6.0-rc2 / 2016-05-07. - * `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://clojure.atlassian.net/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. + * `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](https://clojure.atlassian.net/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07. * Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). 0.6.0-rc1 / 2016-05-04. - `find-by-keys` accepts an `:order-by` option that expects a sequence of orderings; an ordering is a column name (keyword) or a map from column name (keyword) to direction (`:asc` or `:desc`). 0.6.0-rc2 / 2016-05-07. - * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://clojure.atlassian.net/browse/JDBC-124). 0.6.0-alpha2 / 2016-04-18. - * Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://clojure.atlassian.net/browse/JDBC-123). 0.6.0-alpha2 / 2016-04-18. - * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://clojure.atlassian.net/browse/JDBC-118). 0.6.0-alpha1 / 2016-04-13 + * Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](https://clojure.atlassian.net/browse/JDBC-124). 0.6.0-alpha2 / 2016-04-18. + * Fix typo in `insert-multi!` argument validation exception [JDBC-123](https://clojure.atlassian.net/browse/JDBC-123). 0.6.0-alpha2 / 2016-04-18. + * ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](https://clojure.atlassian.net/browse/JDBC-118). 0.6.0-alpha1 / 2016-04-13 - See changes described in versions 0.5.5 through 0.5.8 for what was deprecated - Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies! - `db-transaction` (deprecated in version 0.3.0) has been removed - The `java.jdbc.deprecated` namespace has been removed * Release 0.5.8 on 2016-04-12 - * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. - * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://clojure.atlassian.net/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. + * `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](https://clojure.atlassian.net/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console. + * `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](https://clojure.atlassian.net/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console. * Release 0.5.7 on 2016-04-10 - * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://clojure.atlassian.net/browse/JDBC-121). + * `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](https://clojure.atlassian.net/browse/JDBC-121). * Release 0.5.6 on 2016-04-10 - * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://clojure.atlassian.net/browse/JDBC-120). + * `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](https://clojure.atlassian.net/browse/JDBC-120). - If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console. - * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://clojure.atlassian.net/browse/JDBC-119). + * `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](https://clojure.atlassian.net/browse/JDBC-119). - If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console. * NOTE: all deprecated functionality will go away in version 0.6.0! * Release 0.5.5 on 2016-04-09 - * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://clojure.atlassian.net/browse/JDBC-117). + * Allow options map in all calls that previously took optional keyword arguments [JDBC-117](https://clojure.atlassian.net/browse/JDBC-117). - The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0. * Release 0.5.0 on 2016-03-27 - * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://clojure.atlassian.net/browse/JDBC-115). - * Remove exception wrapping [JDBC-114](http://clojure.atlassian.net/browse/JDBC-114). + * Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](https://clojure.atlassian.net/browse/JDBC-115). + * Remove exception wrapping [JDBC-114](https://clojure.atlassian.net/browse/JDBC-114). * Drop Clojure 1.3 compatibility. * Release 0.4.2 on 2015-09-15 - * Remove redundant type hints [JDBC-113](http://clojure.atlassian.net/browse/JDBC-113) - Michael Blume. - * Avoid reflection on `.prepareStatement` [JDBC-112](http://clojure.atlassian.net/browse/JDBC-112) - Michael Blume. - * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://clojure.atlassian.net/browse/JDBC-107). - * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://clojure.atlassian.net/browse/JDBC-104). - * Officially support H2 (and test against it) to support [JDBC-91](http://clojure.atlassian.net/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. + * Remove redundant type hints [JDBC-113](https://clojure.atlassian.net/browse/JDBC-113) - Michael Blume. + * Avoid reflection on `.prepareStatement` [JDBC-112](https://clojure.atlassian.net/browse/JDBC-112) - Michael Blume. + * Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](https://clojure.atlassian.net/browse/JDBC-107). + * `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](https://clojure.atlassian.net/browse/JDBC-104). + * Officially support H2 (and test against it) to support [JDBC-91](https://clojure.atlassian.net/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL. * Release 0.4.0 / 0.4.1 on 2015-07-26 - * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://clojure.atlassian.net/browse/JDBC-111) - Stefan Kamphausen. - * Nested transaction checks isolation level is the same [JDBC-110](http://clojure.atlassian.net/browse/JDBC-110) - Donald Ball. - * Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://clojure.atlassian.net/browse/JDBC-109). + * `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](https://clojure.atlassian.net/browse/JDBC-111) - Stefan Kamphausen. + * Nested transaction checks isolation level is the same [JDBC-110](https://clojure.atlassian.net/browse/JDBC-110) - Donald Ball. + * Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](https://clojure.atlassian.net/browse/JDBC-109). * Drop Clojure 1.2 compatibility. * Release 0.3.7 on 2015-05-18 * Bump all driver versions in `project.clj` and re-test. - * Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://clojure.atlassian.net/browse/JDBC-108) - Earl St Sauver. - * Remove driver versions from README and link to Maven Central [JDBC-106](http://clojure.atlassian.net/browse/JDBC-106). - * Fix links in CHANGES and README [JDBC-103](http://clojure.atlassian.net/browse/JDBC-103) - John Walker. + * Remove duplicate `count` calls in `insert-sql` [JDBC-108](https://clojure.atlassian.net/browse/JDBC-108) - Earl St Sauver. + * Remove driver versions from README and link to Maven Central [JDBC-106](https://clojure.atlassian.net/browse/JDBC-106). + * Fix links in CHANGES and README [JDBC-103](https://clojure.atlassian.net/browse/JDBC-103) - John Walker. * Release 0.3.6 on 2014-10-28 - * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://clojure.atlassian.net/browse/JDBC-102). - * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://clojure.atlassian.net/browse/JDBC-101). - * Add `:timeout` argument to `prepare-statement` [JDBC-100](http://clojure.atlassian.net/browse/JDBC-100). + * Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](https://clojure.atlassian.net/browse/JDBC-102). + * Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](https://clojure.atlassian.net/browse/JDBC-101). + * Add `:timeout` argument to `prepare-statement` [JDBC-100](https://clojure.atlassian.net/browse/JDBC-100). * Release 0.3.5 on 2014-08-01 * Reflection warnings on executeUpdate addressed. - * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://clojure.atlassian.net/browse/JDBC-94). - * Add support for readonly transactions via :read-only? [JDBC-93](http://clojure.atlassian.net/browse/JDBC-93). + * HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](https://clojure.atlassian.net/browse/JDBC-94). + * Add support for readonly transactions via :read-only? [JDBC-93](https://clojure.atlassian.net/browse/JDBC-93). * Release 0.3.4 on 2014-06-30 - * execute! can now accept a PreparedStatement [JDBC-96](http://clojure.atlassian.net/browse/JDBC-96). - * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92). - * Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://clojure.atlassian.net/browse/JDBC-90). + * execute! can now accept a PreparedStatement [JDBC-96](https://clojure.atlassian.net/browse/JDBC-96). + * Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](https://clojure.atlassian.net/browse/JDBC-92). + * Support oracle:oci and oracle:thin subprotocols [JDBC-90](https://clojure.atlassian.net/browse/JDBC-90). * Release 0.3.3 on 2014-01-30 - * Prevent exception/crash when query called with bare SQL string [JDBC-89](http://clojure.atlassian.net/browse/JDBC-89). - * Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://clojure.atlassian.net/browse/JDBC-87). + * Prevent exception/crash when query called with bare SQL string [JDBC-89](https://clojure.atlassian.net/browse/JDBC-89). + * Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](https://clojure.atlassian.net/browse/JDBC-87). * Support key/value configuration from URI (Phil Hagelberg). * Release 0.3.2 on 2013-12-30 @@ -352,23 +347,23 @@ Change Log * Release 0.3.1 on 2013-12-29 (broken; use 0.3.2 instead) * Improve docstrings and add :arglists for better auto-generated documentation. * Make insert-sql private - technically a breaking change but it should never have been public: sorry folks! - * Provide better protocol for setting parameters in prepared statements [JDBC-86](http://clojure.atlassian.net/browse/JDBC-86). - * Fix parens in two deprecated tests [JDBC-85](http://clojure.atlassian.net/browse/JDBC-85). + * Provide better protocol for setting parameters in prepared statements [JDBC-86](https://clojure.atlassian.net/browse/JDBC-86). + * Fix parens in two deprecated tests [JDBC-85](https://clojure.atlassian.net/browse/JDBC-85). * Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected. * Release 0.3.0 on 2013-12-16 - * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://clojure.atlassian.net/browse/JDBC-84). - * Rename recently introduced test to ensure unique names [JDBC-83](http://clojure.atlassian.net/browse/JDBC-83). - * Rename unused arguments in protocol implementation to support Android [JDBC-82](http://clojure.atlassian.net/browse/JDBC-82). - * Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://clojure.atlassian.net/browse/JDBC-65). + * Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](https://clojure.atlassian.net/browse/JDBC-84). + * Rename recently introduced test to ensure unique names [JDBC-83](https://clojure.atlassian.net/browse/JDBC-83). + * Rename unused arguments in protocol implementation to support Android [JDBC-82](https://clojure.atlassian.net/browse/JDBC-82). + * Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](https://clojure.atlassian.net/browse/JDBC-65). * Release 0.3.0-rc1 on 2013-12-12 - * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://clojure.atlassian.net/browse/JDBC-81). - * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://clojure.atlassian.net/browse/JDBC-80). - * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://clojure.atlassian.net/browse/JDBC-79). - * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://clojure.atlassian.net/browse/JDBC-77). - * Add support for :isolation in with-db-transaction [JDBC-75](http://clojure.atlassian.net/browse/JDBC-75). - * Add :user as an alias for :username for DataSource connections [JDBC-74](http://clojure.atlassian.net/browse/JDBC-74). + * Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](https://clojure.atlassian.net/browse/JDBC-81). + * Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](https://clojure.atlassian.net/browse/JDBC-80). + * Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](https://clojure.atlassian.net/browse/JDBC-79). + * Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](https://clojure.atlassian.net/browse/JDBC-77). + * Add support for :isolation in with-db-transaction [JDBC-75](https://clojure.atlassian.net/browse/JDBC-75). + * Add :user as an alias for :username for DataSource connections [JDBC-74](https://clojure.atlassian.net/browse/JDBC-74). * Release 0.3.0-beta2 on 2013-11-24 * **BREAKING CHANGES!** @@ -376,40 +371,40 @@ Change Log * The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation. * Release 0.3.0-beta1 on 2013-11-03 - * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://clojure.atlassian.net/browse/JDBC-72). + * query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](https://clojure.atlassian.net/browse/JDBC-72). * "h2" is recognized as a protocol shorthand for org.h2.Driver - * Tests no longer use :1 literal [JDBC-71](http://clojure.atlassian.net/browse/JDBC-71). - * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://clojure.atlassian.net/browse/JDBC-69). - * New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://clojure.atlassian.net/browse/JDBC-63). - * Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40). + * Tests no longer use :1 literal [JDBC-71](https://clojure.atlassian.net/browse/JDBC-71). + * Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](https://clojure.atlassian.net/browse/JDBC-69). + * New db-query-with-resultset function replaces private `db-with-query-results*` and processes a raw ResultSet object [JDBC-63](https://clojure.atlassian.net/browse/JDBC-63). + * Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](https://clojure.atlassian.net/browse/JDBC-40). * Release 0.3.0-alpha5 on 2013-09-15 - * DDL now supports entities naming strategy [JDBC-53](http://clojure.atlassian.net/browse/JDBC-53). - * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). - * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) + * DDL now supports entities naming strategy [JDBC-53](https://clojure.atlassian.net/browse/JDBC-53). + * Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](https://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/). + * Documentation has moved to [Using java.jdbc on Clojure-Doc.org](https://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) * Added Leiningen support for easier development/testing (Maven is still the primary build tool). - * Added create-index / drop-index DDL [JDBC-62](http://clojure.atlassian.net/browse/JDBC-62) - moquist - * Make transaction? boolean optional in various db-do-* functions + * Added create-index / drop-index DDL [JDBC-62](https://clojure.atlassian.net/browse/JDBC-62) - moquist + * Make transaction? boolean optional in various `db-do-*` functions * Create clojure.java.jdbc.ddl namespace * Add create-table, drop-table, create-index and drop-index * Deprecate create-table, create-table-ddl and drop-table in main namespace * Update README to clarify PostgreSQL instructions. - * Fix test suite for PostgreSQL [JDBC-59](http://clojure.atlassian.net/browser/JDBC-59) - * Improve hooks for Oracle data type handling [JDBC-57](http://clojure.atlassian.net/browser/JDBC-57) - * Fix reflection warnings [JDBC-55](http://clojure.atlassian.net/browser/JDBC-55) + * Fix test suite for PostgreSQL [JDBC-59](https://clojure.atlassian.net/browser/JDBC-59) + * Improve hooks for Oracle data type handling [JDBC-57](https://clojure.atlassian.net/browser/JDBC-57) + * Fix reflection warnings [JDBC-55](https://clojure.atlassian.net/browser/JDBC-55) * Release 0.3.0-alpha4 on 2013-05-11 - * Fix connection leaks [JDBC-54](http://clojure.atlassian.net/browser/JDBC-54) + * Fix connection leaks [JDBC-54](https://clojure.atlassian.net/browser/JDBC-54) * Allow order-by to accept empty sequence (and return empty string) * Release 0.3.0-alpha3 on 2013-05-04 * Fix macro / import interaction by fully qualifying Connection type. * Release 0.3.0-alpha2 on 2013-05-03 - * Address [JDBC-51](http://clojure.atlassian.net/browse/JDBC-51) by declaring get-connection returns java.sql.Connection - * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://clojure.atlassian.net/browse/JDBC-46) - * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://clojure.atlassian.net/browse/JDBC-52) - * Reverted specialized handling of NULL values (reopens [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40)) + * Address [JDBC-51](https://clojure.atlassian.net/browse/JDBC-51) by declaring get-connection returns java.sql.Connection + * Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](https://clojure.atlassian.net/browse/JDBC-46) + * Add :multi? to execute! so it can be used for repeated operations [JDBC-52](https://clojure.atlassian.net/browse/JDBC-52) + * Reverted specialized handling of NULL values (reopens [JDBC-40](https://clojure.atlassian.net/browse/JDBC-40)) * Rename :as-arrays to :as-arrays? since it is boolean * Add curried version of clojure.java.jdbc.sql/as-quoted-str * Officially deprecate resultset-seq @@ -418,36 +413,36 @@ Change Log * MAJOR API OVERHAUL! * Most of the old 0.2.x API has been deprecated and a new, more idiomatic API introduced, along with a minimal DSL to generate basic SQL * Specifics: - * Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](http://clojure.atlassian.net/browse/JDBC-20) + * Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](https://clojure.atlassian.net/browse/JDBC-20) * Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20) * Add db- prefixed versions of low-level API * Add db-transaction macro * Add result-set-seq as replacement for resultset-seq (which will be deprecated) - * Transaction now correctly rollback on non-Exception Throwables [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) - * Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](http://clojure.atlassian.net/browse/JDBC-43) - * Add :as-arrays to query / result-set-seq [JDBC-41](http://clojure.atlassian.net/browse/JDBC-41) - * Better handling of NULL values [JDBC-40](http://clojure.atlassian.net/browse/JDBC-40) and [JDBC-18](http://clojure.atlassian.net/browse/JDBC-18) + * Transaction now correctly rollback on non-Exception Throwables [JDBC-43](https://clojure.atlassian.net/browse/JDBC-43) + * Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](https://clojure.atlassian.net/browse/JDBC-43) + * Add :as-arrays to query / result-set-seq [JDBC-41](https://clojure.atlassian.net/browse/JDBC-41) + * Better handling of NULL values [JDBC-40](https://clojure.atlassian.net/browse/JDBC-40) and [JDBC-18](https://clojure.atlassian.net/browse/JDBC-18) Note: JDBC-40 is being reverted in 0.3.0-alpha2 because it introduces regressions in PostgreSQL - * db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](http://clojure.atlassian.net/browse/JDBC-38) + * db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](https://clojure.atlassian.net/browse/JDBC-38) * Remove reflection warning from execute-batch * Add notes to README about 3rd party database driver dependencies * Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy * Release 0.2.3 on 2012-06-18 * as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b] - * Add :connection-uri option [JDBC-34](http://clojure.atlassian.net/browse/JDBC-34) + * Add :connection-uri option [JDBC-34](https://clojure.atlassian.net/browse/JDBC-34) * Release 0.2.2 on 2012-06-10 - * Handle Oracle unknown row count affected [JDBC-33](http://clojure.atlassian.net/browse/JDBC-33) - * Handle jdbc: prefix in string db-specs [JDBC-32](http://clojure.atlassian.net/browse/JDBC-32) - * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://clojure.atlassian.net/browse/JDBC-31) + * Handle Oracle unknown row count affected [JDBC-33](https://clojure.atlassian.net/browse/JDBC-33) + * Handle jdbc: prefix in string db-specs [JDBC-32](https://clojure.atlassian.net/browse/JDBC-32) + * Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](https://clojure.atlassian.net/browse/JDBC-31) * Release 0.2.1 on 2012-05-10 - * Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://clojure.atlassian.net/browse/JDBC-29) - * Make do-prepared-return-keys (for Korma team) [JDBC-30](http://clojure.atlassian.net/browse/JDBC-30) + * Result set performance enhancement (Juergen Hoetzel) [JDBC-29](https://clojure.atlassian.net/browse/JDBC-29) + * Make do-prepared-return-keys (for Korma team) [JDBC-30](https://clojure.atlassian.net/browse/JDBC-30) * Release 0.2.0 on 2012-04-23 - * Merge internal namespace into main jdbc namespace [JDBC-19](http://clojure.atlassian.net/browse/JDBC-19) + * Merge internal namespace into main jdbc namespace [JDBC-19](https://clojure.atlassian.net/browse/JDBC-19) * Release 0.1.4 on 2012-04-15 * Unwrap RTE for nested transaction exceptions (we already @@ -455,30 +450,30 @@ Change Log * Remove reflection warning unwrapping RunTimeException (Alan Malloy) * Release 0.1.3 on 2012-02-29 - * Fix generated keys inside transactions for SQLite3 [JDBC-26](http://clojure.atlassian.net/browse/JDBC-26) + * Fix generated keys inside transactions for SQLite3 [JDBC-26](https://clojure.atlassian.net/browse/JDBC-26) * Release 0.1.2 on 2012-02-29 - * Handle prepared statement params correctly [JDBC-23](http://clojure.atlassian.net/browse/JDBC-23) - * Add support for SQLite3 [JDBC-26](http://clojure.atlassian.net/browse/JDBC-26) - * Replace replicate (deprecated) with repeat [JDBC-27](http://clojure.atlassian.net/browse/JDBC-27) + * Handle prepared statement params correctly [JDBC-23](https://clojure.atlassian.net/browse/JDBC-23) + * Add support for SQLite3 [JDBC-26](https://clojure.atlassian.net/browse/JDBC-26) + * Replace replicate (deprecated) with repeat [JDBC-27](https://clojure.atlassian.net/browse/JDBC-27) * Ensure MS SQL Server passes tests with both Microsoft and jTDS drivers * Build server now tests derby, hsqldb and sqlite by default * Update README per Stuart Sierra's outline for contrib projects * Release 0.1.1 on 2011-11-02 - * Accept string or URI in connection definition [JDBC-21](http://clojure.atlassian.net/browse/JDBC-21) - * Allow driver, port and subprotocol to be deduced [JDBC-22](http://clojure.atlassian.net/browse/JDBC-22) + * Accept string or URI in connection definition [JDBC-21](https://clojure.atlassian.net/browse/JDBC-21) + * Allow driver, port and subprotocol to be deduced [JDBC-22](https://clojure.atlassian.net/browse/JDBC-22) * Release 0.1.0 on 2011-10-16 - * Remove dependence on deprecated structmap [JDBC-15](http://clojure.atlassian.net/browse/JDBC-15) + * Remove dependence on deprecated structmap [JDBC-15](https://clojure.atlassian.net/browse/JDBC-15) * Release 0.0.7 on 2011-10-11 - * Rename duplicate columns [JDBC-9](http://clojure.atlassian.net/browse/JDBC-9) - * Ensure do-preared traps invalid SQL [JDBC-16](http://clojure.atlassian.net/browse/JDBC-16) + * Rename duplicate columns [JDBC-9](https://clojure.atlassian.net/browse/JDBC-9) + * Ensure do-preared traps invalid SQL [JDBC-16](https://clojure.atlassian.net/browse/JDBC-16) * Release 0.0.6 on 2011-08-04 * Improve exception handling (unwrap RTE) - * Don't use batch for update (causes exceptions on Apache Derby) [JDBC-12](http://dev.clojure.org/jire/JDBC-12) + * Don't use batch for update (causes exceptions on Apache Derby) [JDBC-12](https://clojure.atlassian.net/browse/JDBC-12) * Add test suite * Release 0.0.5 on 2011-07-18 @@ -487,23 +482,23 @@ Change Log * Support databases that cannot return generated keys * Release 0.0.4 on 2011-07-17 - * Allow :table-spec {string} in create-table [JDBC-4](http://dev.clojure.org/jire/JDBC-4) - * Remove reflection warnings [JDBC-8](http://dev.clojure.org/jire/JDBC-8) - * Ensure transactions are not committed when Error occurs [JDBC-11](http://dev.clojure.org/jire/JDBC-11) + * Allow :table-spec {string} in create-table [JDBC-4](https://clojure.atlassian.net/browse/JDBC-4) + * Remove reflection warnings [JDBC-8](https://clojure.atlassian.net/browse/JDBC-8) + * Ensure transactions are not committed when Error occurs [JDBC-11](https://clojure.atlassian.net/browse/JDBC-11) * Release 0.0.3 on 2011-07-01 - * Key generation compatibility with MS SQL Server, PostgreSQL [JDBC-10](http://clojure.atlassian.net/browse/JDBC-10) + * Key generation compatibility with MS SQL Server, PostgreSQL [JDBC-10](https://clojure.atlassian.net/browse/JDBC-10) * Release 0.0.2 on 2011-06-07 - * Clojure 1.2 compatibility [JDBC-7](http://clojure.atlassian.net/browse/JDBC-7) + * Clojure 1.2 compatibility [JDBC-7](https://clojure.atlassian.net/browse/JDBC-7) * Release 0.0.1 on 2011-05-07 * Initial release * Changes from clojure.contrib.sql: - * Expose print-... functions; no longer write exceptions to **\*out\*** + * Expose print-... functions; no longer write exceptions to `\*out\*` * Define resultset-seq to replace clojure.core/resultset-seq - * Add naming / quoting strategies (see [name mapping documentation](http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/NameMapping.html) + * Add naming / quoting strategies (see [name mapping documentation](https://clojure.github.io/java.jdbc/doc/clojure/java/jdbc/NameMapping.html) * Return generated keys from insert operations, where possible * Add insert-record function * Clojure 1.3 compatibility @@ -513,7 +508,7 @@ Copyright and License Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2014. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public -License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can +License 1.0 (https://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any From 6d61891318dfbd9983ef6f35ee25660db3405854 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 15 Apr 2021 15:38:46 -0700 Subject: [PATCH 609/630] Update parent pom to 1.1.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7dd53757..cce28fd3 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ org.clojure pom.contrib - 0.2.2 + 1.1.0 From a0c5bd1a9d52080f320e966199d6c8446a85f1dd Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Mon, 4 Apr 2022 11:24:21 -0500 Subject: [PATCH 610/630] fix links to clojure-docs --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 338996f7..97e1c82f 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ clojure.java.jdbc A low-level Clojure wrapper for JDBC-based access to databases. This project is "Stable" (no longer "Active"). It has effectively been superseded by [seancorfield/next.jdbc](https://github.com/seancorfield/next-jdbc). -For higher level DSLs and migration libraries that are compatible, see the [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). +For higher level DSLs and migration libraries that are compatible, see the [documentation](https://clojure-doc.org/articles/ecosystem/java_jdbc/home). Formerly known as `clojure.contrib.sql`. @@ -12,10 +12,10 @@ This library is mature and stable. It is widely used and its use is described in Documentation ======================================== * [API Reference](https://clojure.github.io/java.jdbc/) (Autogenerated) -* [Overview](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) -* [Manipulating Data with SQL](http://clojure-doc.org/articles/ecosystem/java_jdbc/using_sql.html) -* [How to Reuse Database Connections](http://clojure-doc.org/articles/ecosystem/java_jdbc/reusing_connections.html) -* [Using DDL and Metadata](http://clojure-doc.org/articles/ecosystem/java_jdbc/using_ddl.html) +* [Overview](https://clojure-doc.org/articles/ecosystem/java_jdbc/home) +* [Manipulating Data with SQL](https://clojure-doc.org/articles/ecosystem/java_jdbc/using_sql) +* [How to Reuse Database Connections](https://clojure-doc.org/articles/ecosystem/java_jdbc/reusing_connections) +* [Using DDL and Metadata](https://clojure-doc.org/articles/ecosystem/java_jdbc/using_ddl) Support ======================================== @@ -106,7 +106,7 @@ Example Usage {:row-fn :cost}) ;; (24) ``` -For more detail see the [API reference](https://clojure.github.io/java.jdbc/) or [documentation](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html). +For more detail see the [API reference](https://clojure.github.io/java.jdbc/) or [documentation](https://clojure-doc.org/articles/ecosystem/java_jdbc/home). Developer Information ======================================== From af72059bdc161bde3436dab2eaefdef0c0111499 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 7 Oct 2022 07:21:21 -0700 Subject: [PATCH 611/630] ignore more dev env stuff --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 51cb74c5..1ba3bb61 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ *.jar .classpath +.clj-kondo/.cache .cpcache +.lsp/.cache +.portal .project .rebl .settings From a7f14dc607b339ca87e2d1a047be7dfefc8fb0c7 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 26 May 2023 15:21:37 -0500 Subject: [PATCH 612/630] add actions --- .github/workflows/release.yml | 19 +++++++++++++++++++ .github/workflows/snapshot.yml | 8 ++++++++ .github/workflows/test.yml | 7 +++++++ README.md | 5 ++--- 4 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/snapshot.yml create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..e2718bd3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,19 @@ +name: Release on demand + +on: + workflow_dispatch: + inputs: + releaseVersion: + description: "Version to release" + required: true + snapshotVersion: + description: "Snapshot version after release" + required: true + +jobs: + call-release: + uses: clojure/build.ci/.github/workflows/release.yml@master + with: + releaseVersion: ${{ github.event.inputs.releaseVersion }} + snapshotVersion: ${{ github.event.inputs.snapshotVersion }} + secrets: inherit \ No newline at end of file diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml new file mode 100644 index 00000000..24729578 --- /dev/null +++ b/.github/workflows/snapshot.yml @@ -0,0 +1,8 @@ +name: Snapshot on demand + +on: [workflow_dispatch] + +jobs: + call-snapshot: + uses: clojure/build.ci/.github/workflows/snapshot.yml@master + secrets: inherit diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..1fa127c9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,7 @@ +name: Test + +on: [push] + +jobs: + call-test: + uses: clojure/build.ci/.github/workflows/test.yml@master diff --git a/README.md b/README.md index 97e1c82f..69ff3ed7 100644 --- a/README.md +++ b/README.md @@ -113,8 +113,7 @@ Developer Information * [GitHub project](https://github.com/clojure/java.jdbc) * [Bug Tracker](https://clojure.atlassian.net/browse/JDBC) -* [Continuous Integration](https://build.clojure.org/job/java.jdbc/) -* [Compatibility Test Matrix](https://build.clojure.org/job/java.jdbc-test-matrix/) +* [Continuous Integration](https://github.com/clojure/java.jdbc/actions/workflows/test.yml) * Testing: * Currently by default tests run only against Derby and HSQLDB, the in-process databases. @@ -506,7 +505,7 @@ Change Log Copyright and License ======================================== -Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2014. All rights reserved. The use and +Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2023. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (https://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. From 7a374ac4f35d579f15e85866b721def9ae472e81 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 26 May 2023 15:22:35 -0500 Subject: [PATCH 613/630] bump version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cce28fd3..2527ee30 100644 --- a/pom.xml +++ b/pom.xml @@ -96,7 +96,7 @@ org.xerial sqlite-jdbc - 3.23.1 + 3.41.2.2 test From 528dd9feb3d5ea5b2e38e1d2e8285ed156a65506 Mon Sep 17 00:00:00 2001 From: JarrodCTaylor Date: Wed, 16 Aug 2023 12:45:30 -0500 Subject: [PATCH 614/630] Added github action to build api docs --- .github/workflows/doc-build.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .github/workflows/doc-build.yml diff --git a/.github/workflows/doc-build.yml b/.github/workflows/doc-build.yml new file mode 100644 index 00000000..685f14ea --- /dev/null +++ b/.github/workflows/doc-build.yml @@ -0,0 +1,10 @@ +name: Build API Docs + +on: + workflow_dispatch: + +jobs: + call-doc-build-workflow: + uses: clojure/build.ci/.github/workflows/doc-build.yml@master + with: + project: clojure/java.jdbc From 8458e4892ddb4169c67b571c75377d95cc574873 Mon Sep 17 00:00:00 2001 From: JarrodCTaylor Date: Wed, 30 Aug 2023 22:26:38 -0500 Subject: [PATCH 615/630] Fix EPL license link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 69ff3ed7..cb29432b 100644 --- a/README.md +++ b/README.md @@ -507,7 +507,7 @@ Copyright and License Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2023. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public -License 1.0 (https://opensource.org/licenses/eclipse-1.0.php) which can +License 1.0 (https://opensource.org/license/epl-1-0/) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any From 25c1bbb7e7d1d077be8b6906d87627fb8a82b8f9 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Mon, 19 Feb 2024 12:35:31 -0600 Subject: [PATCH 616/630] update parent pom and versions --- deps.edn | 8 ++++---- pom.xml | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/deps.edn b/deps.edn index 540e15d9..7d6b7e47 100644 --- a/deps.edn +++ b/deps.edn @@ -5,7 +5,7 @@ {:paths ["src/main/clojure"] :aliases {:test {:extra-paths ["src/test/clojure"] - :extra-deps {org.clojure/test.check {:mvn/version "0.10.0"} + :extra-deps {org.clojure/test.check {:mvn/version "1.1.1"} org.apache.derby/derby {:mvn/version "10.14.2.0"} org.hsqldb/hsqldb {:mvn/version "2.4.1"} com.h2database/h2 {:mvn/version "1.4.197"} @@ -20,10 +20,10 @@ :1.7 {:override-deps {org.clojure/clojure {:mvn/version "1.7.0"}}} :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} - :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.0"}}} - :master {:override-deps {org.clojure/clojure {:mvn/version "1.11.0-master-SNAPSHOT"}}} + :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} + :master {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-master-SNAPSHOT"}}} :perf {:extra-paths ["src/perf/clojure"] - :extra-deps {criterium {:mvn/version "0.4.4"}} + :extra-deps {criterium {:mvn/version "0.4.6"}} :jvm-opts ["-server" "-Xmx4096m" "-Dclojure.compiler.direct-linking=true"]} diff --git a/pom.xml b/pom.xml index 2527ee30..27a7fce3 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ org.clojure pom.contrib - 1.1.0 + 1.2.0 @@ -28,7 +28,7 @@ - 1.7.0 + 1.9.0 @@ -108,7 +108,7 @@ org.clojure test.check - 0.9.0 + 1.1.1 test From 25fcc830c70208df8827038be3c881d2517f039c Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Mon, 19 Feb 2024 12:56:09 -0600 Subject: [PATCH 617/630] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb29432b..b36cbaf9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ clojure.java.jdbc ======================================== -A low-level Clojure wrapper for JDBC-based access to databases. This project is "Stable" (no longer "Active"). It has effectively been superseded by [seancorfield/next.jdbc](https://github.com/seancorfield/next-jdbc). +A low-level Clojure wrapper for JDBC-based access to databases. This project is "Inactive". It has effectively been superseded by [seancorfield/next.jdbc](https://github.com/seancorfield/next-jdbc). For higher level DSLs and migration libraries that are compatible, see the [documentation](https://clojure-doc.org/articles/ecosystem/java_jdbc/home). From 44b9e74a2440e01469790c77a54f648f692668e6 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Wed, 27 Mar 2024 15:06:56 -0700 Subject: [PATCH 618/630] some version updates Signed-off-by: Sean Corfield --- .gitignore | 5 ++--- .joker | 3 --- CHANGES.md | 4 ++++ deps.edn | 25 ++++++++++----------- pom.xml | 7 +++--- run-tests.sh | 4 ++-- src/main/clojure/clojure/java/jdbc.clj | 5 +++-- src/test/clojure/clojure/java/jdbc_test.clj | 10 +++++---- 8 files changed, 33 insertions(+), 30 deletions(-) delete mode 100644 .joker diff --git a/.gitignore b/.gitignore index 1ba3bb61..81f14885 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -*.jar +.calva/repl.calva-repl .classpath .clj-kondo/.cache .cpcache @@ -7,6 +7,7 @@ .project .rebl .settings +*.jar /.lein-failures /.lein-repl-history /.nrepl-port @@ -18,5 +19,3 @@ derby.log settings.xml target test-all.sh -/postgres-down.sh -/postgres-up.sh diff --git a/.joker b/.joker deleted file mode 100644 index 0fd26273..00000000 --- a/.joker +++ /dev/null @@ -1,3 +0,0 @@ -{:known-macros [clojure.java.jdbc/with-db-connection - clojure.java.jdbc/with-db-metadata - clojure.java.jdbc/with-db-transaction]} diff --git a/CHANGES.md b/CHANGES.md index 4a6aba18..b0db8bea 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +Changes not yet released +* Update most testing dependencies (and update a couple of tests to match). +* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12 (Alpha 9). + Changes in 0.7.12 * Make the protocols `ISQLValue`, `ISQLParameter`, and `IResultSetReadColumn` extensible via metadata. diff --git a/deps.edn b/deps.edn index 7d6b7e47..4b1a182a 100644 --- a/deps.edn +++ b/deps.edn @@ -1,35 +1,34 @@ ;; You can run clojure.java.jdbc tests with: clj -A:test:runner ;; You can also specify an alias to select which version of Clojure to test -;; against: :1.7 :1.8 :1.9 :master +;; against: :1.8 :1.9 :1.10 :1.11 :1.12 {:paths ["src/main/clojure"] :aliases {:test {:extra-paths ["src/test/clojure"] :extra-deps {org.clojure/test.check {:mvn/version "1.1.1"} org.apache.derby/derby {:mvn/version "10.14.2.0"} - org.hsqldb/hsqldb {:mvn/version "2.4.1"} + org.hsqldb/hsqldb$jdk8 {:mvn/version "2.7.2"} com.h2database/h2 {:mvn/version "1.4.197"} net.sourceforge.jtds/jtds {:mvn/version "1.3.1"} ;; Note: Tests fail with 6.0.2+ driver mysql/mysql-connector-java {:mvn/version "5.1.41"} - org.postgresql/postgresql {:mvn/version "42.2.2.jre7"} - com.impossibl.pgjdbc-ng/pgjdbc-ng {:mvn/version "0.7.1"} - org.xerial/sqlite-jdbc {:mvn/version "3.23.1"} - ;; Note: Assumes Java 8; there's a .jre7 version as well - com.microsoft.sqlserver/mssql-jdbc {:mvn/version "6.2.2.jre8"}}} - :1.7 {:override-deps {org.clojure/clojure {:mvn/version "1.7.0"}}} + org.postgresql/postgresql {:mvn/version "42.7.3"} + com.impossibl.pgjdbc-ng/pgjdbc-ng {:mvn/version "0.8.9"} + org.xerial/sqlite-jdbc {:mvn/version "3.45.2.0"} + ;; Note: Assumes Java 8; there's a .jre11 version as well + com.microsoft.sqlserver/mssql-jdbc {:mvn/version "12.6.1.jre8"}}} :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} - :master {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-master-SNAPSHOT"}}} + :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.2"}}} + :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-alpha9"}}} :perf {:extra-paths ["src/perf/clojure"] - :extra-deps {criterium {:mvn/version "0.4.6"}} + :extra-deps {criterium/criterium {:mvn/version "0.4.6"}} :jvm-opts ["-server" "-Xmx4096m" "-Dclojure.compiler.direct-linking=true"]} :runner - {:extra-deps {com.cognitect/test-runner - {:git/url "https://github.com/cognitect-labs/test-runner" - :sha "76568540e7f40268ad2b646110f237a60295fa3c"}} + {:extra-deps {io.github.cognitect-labs/test-runner + {:git/tag "v0.5.1" :git/sha "dfb30dd"}} :main-opts ["-m" "cognitect.test-runner" "-d" "src/test/clojure"]}}} diff --git a/pom.xml b/pom.xml index 27a7fce3..9104128f 100644 --- a/pom.xml +++ b/pom.xml @@ -78,7 +78,8 @@ org.hsqldb hsqldb - 2.4.1 + 2.7.2 + jdk8 test @@ -90,13 +91,13 @@ org.postgresql postgresql - 42.2.2.jre7 + 42.7.3 test org.xerial sqlite-jdbc - 3.41.2.2 + 3.45.2.0 test diff --git a/run-tests.sh b/run-tests.sh index f4325f09..ed2a4f69 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -44,10 +44,10 @@ dbs="derby h2 hsqldb sqlite" # Start with clean databases each time to avoid slowdown rm -rf clojure_test_* -versions="1.7 1.8 1.9 1.10 master" +versions="1.8 1.9 1.10 1.11 1.12" for v in $versions do - TEST_DBS="$dbs $*" clj -A:test:runner:$v + TEST_DBS="$dbs $*" clj -M:test:runner:$v if test $? -ne 0 then exit $? diff --git a/src/main/clojure/clojure/java/jdbc.clj b/src/main/clojure/clojure/java/jdbc.clj index e90c8850..5bcf5236 100644 --- a/src/main/clojure/clojure/java/jdbc.clj +++ b/src/main/clojure/clojure/java/jdbc.clj @@ -540,7 +540,7 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} locales where the lower case version of a character is not a valid SQL entity name (e.g., Turkish)." [^String s] - (.toLowerCase s (Locale/US))) + (.toLowerCase s Locale/US)) (defn result-set-seq "Creates and returns a lazy sequence of maps corresponding to the rows in the @@ -1507,7 +1507,8 @@ http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"} (map second rs))) result-set-fn (throw (ex-info (str "Cannot apply result-set-fn to" - " non-homogeneous generated keys array") rs)) + " non-homogeneous generated keys array") + {:generated-keys rs})) :else ;; non-non-homogeneous generated keys array - return as-is rs)) diff --git a/src/test/clojure/clojure/java/jdbc_test.clj b/src/test/clojure/clojure/java/jdbc_test.clj index 80800afe..f8b11819 100644 --- a/src/test/clojure/clojure/java/jdbc_test.clj +++ b/src/test/clojure/clojure/java/jdbc_test.clj @@ -974,8 +974,8 @@ []) (execute-multi-insert db)))] (case (db-type db) - ;; SQLite only returns the last key inserted in a batch - "sqlite" (is (= [(returned-key db 2)] new-keys)) + ;; SQLite returns nothing useful now + "sqlite" (is (= [] new-keys)) ;; Derby returns a single row count "derby" (is (= [(returned-key db 1)] new-keys)) ;; H2 returns dummy keys @@ -1015,8 +1015,8 @@ 0) (execute-multi-insert db))] (case (db-type db) - ;; SQLite only returns the last key inserted in a batch - "sqlite" (is (= 1 n)) + ;; SQLite returns nothing useful now + "sqlite" (is (= 0 n)) ;; Derby returns a single row count "derby" (is (= 1 n)) ;; H2 returns (zero) keys now @@ -1215,6 +1215,7 @@ (is (= [1] delete-result)) (is (= [] rows)))))) +#_{:clj-kondo/ignore [:invalid-arity]} (deftest illegal-insert-arguments (doseq [db (test-specs)] (illegal-arg-or-spec "insert!" (sql/insert! db)) @@ -1276,6 +1277,7 @@ [[:foo :int :default 0]] {:entities (sql/quoted :mysql)})))) +#_{:clj-kondo/ignore [:unresolved-symbol]} (comment db (sql/create-table-ddl table From 507bd16f625ec2ef44d848a23c712b6174544c5b Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 23 May 2024 19:27:52 -0700 Subject: [PATCH 619/630] clojure 1.11.3, 1.12 alpha 12 Signed-off-by: Sean Corfield --- CHANGES.md | 2 +- deps.edn | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b0db8bea..f9f2310b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,6 @@ Changes not yet released * Update most testing dependencies (and update a couple of tests to match). -* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12 (Alpha 9). +* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12 (Alpha 12). Changes in 0.7.12 diff --git a/deps.edn b/deps.edn index 4b1a182a..250ebf8e 100644 --- a/deps.edn +++ b/deps.edn @@ -20,8 +20,8 @@ :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} - :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.2"}}} - :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-alpha9"}}} + :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.3"}}} + :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-alpha12"}}} :perf {:extra-paths ["src/perf/clojure"] :extra-deps {criterium/criterium {:mvn/version "0.4.6"}} :jvm-opts ["-server" From c679817ec1ed5a60a73067aedd55f882dc02187c Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 3 Aug 2024 12:31:32 -0700 Subject: [PATCH 620/630] clojure 1.11.4 & 1.12.0 rc 1 Signed-off-by: Sean Corfield --- CHANGES.md | 2 +- deps.edn | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f9f2310b..f3aa0a95 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,6 @@ Changes not yet released * Update most testing dependencies (and update a couple of tests to match). -* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12 (Alpha 12). +* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12 (RC 1). Changes in 0.7.12 diff --git a/deps.edn b/deps.edn index 250ebf8e..89393dc6 100644 --- a/deps.edn +++ b/deps.edn @@ -20,8 +20,8 @@ :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} - :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.3"}}} - :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-alpha12"}}} + :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.4"}}} + :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-rc1"}}} :perf {:extra-paths ["src/perf/clojure"] :extra-deps {criterium/criterium {:mvn/version "0.4.6"}} :jvm-opts ["-server" From 69d466e3d506d0fb360abf6449a882e96ab8743d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 5 Sep 2024 22:45:38 -0700 Subject: [PATCH 621/630] update test deps to 1.12.0 Signed-off-by: Sean Corfield --- CHANGES.md | 2 +- deps.edn | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f3aa0a95..5691aebb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,6 @@ Changes not yet released * Update most testing dependencies (and update a couple of tests to match). -* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12 (RC 1). +* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12. Changes in 0.7.12 diff --git a/deps.edn b/deps.edn index 89393dc6..d23ec9af 100644 --- a/deps.edn +++ b/deps.edn @@ -21,7 +21,7 @@ :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.4"}}} - :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0-rc1"}}} + :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0"}}} :perf {:extra-paths ["src/perf/clojure"] :extra-deps {criterium/criterium {:mvn/version "0.4.6"}} :jvm-opts ["-server" From 006901a443c8e67ecac803dd8102d38d41e02d4d Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Fri, 4 Oct 2024 13:40:11 -0700 Subject: [PATCH 622/630] update multi-version testing to match official matrix Signed-off-by: Sean Corfield --- CHANGES.md | 2 +- deps.edn | 3 +-- run-tests.sh | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 5691aebb..d6d50aab 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,6 @@ Changes not yet released * Update most testing dependencies (and update a couple of tests to match). -* Drop support for Clojure 1.7.0. Test against 1.8, 1.9, 1.10, 1.11, and 1.12. +* Drop support for Clojure 1.7 & 1.8. Test against 1.9, 1.10, 1.11, and 1.12. Changes in 0.7.12 diff --git a/deps.edn b/deps.edn index d23ec9af..48b6ef53 100644 --- a/deps.edn +++ b/deps.edn @@ -1,6 +1,6 @@ ;; You can run clojure.java.jdbc tests with: clj -A:test:runner ;; You can also specify an alias to select which version of Clojure to test -;; against: :1.8 :1.9 :1.10 :1.11 :1.12 +;; against: :1.9 :1.10 :1.11 :1.12 {:paths ["src/main/clojure"] :aliases {:test @@ -17,7 +17,6 @@ org.xerial/sqlite-jdbc {:mvn/version "3.45.2.0"} ;; Note: Assumes Java 8; there's a .jre11 version as well com.microsoft.sqlserver/mssql-jdbc {:mvn/version "12.6.1.jre8"}}} - :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.4"}}} diff --git a/run-tests.sh b/run-tests.sh index ed2a4f69..5c4032a2 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -44,7 +44,7 @@ dbs="derby h2 hsqldb sqlite" # Start with clean databases each time to avoid slowdown rm -rf clojure_test_* -versions="1.8 1.9 1.10 1.11 1.12" +versions="1.9 1.10 1.11 1.12" for v in $versions do TEST_DBS="$dbs $*" clj -M:test:runner:$v From 12503991bf08b3b0d3cd6b196920f43d0137cb70 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 30 May 2025 15:06:24 -0500 Subject: [PATCH 623/630] update to new parent pom --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9104128f..2d6da37e 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ org.clojure pom.contrib - 1.2.0 + 1.3.0 From c541f1a6c4d732baf9fa19d8dcaf6ca7e384a2a7 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Thu, 28 Aug 2025 09:36:47 -0400 Subject: [PATCH 624/630] Clarify future support for clojure.java.jdbc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b36cbaf9..e78b88ba 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ For higher level DSLs and migration libraries that are compatible, see the [docu Formerly known as `clojure.contrib.sql`. -This library is mature and stable. It is widely used and its use is described in many books and tutorials. It will continue to get bug fixes and minor releases. Based on my experience using and maintaining this library, I've created a faster, more modern JDBC wrapper called [next.jdbc](https://github.com/seancorfield/next-jdbc). I consider it to be the "next generation" of `clojure.java.jdbc` but it exposes a different API -- a better API, I think. +This library is mature and stable. It is widely used and its use is described in many books and tutorials. It will only get critical bug fixes (e.g., security). Based on my experience using and maintaining this library, I've created a faster, more modern JDBC wrapper called [next.jdbc](https://github.com/seancorfield/next-jdbc). I consider it to be the "next generation" of `clojure.java.jdbc` but it exposes a different API -- a better API, I think. Documentation ======================================== From 2b5bb19c6feb2d9e40b9d8a94d09fd32eeeee7b2 Mon Sep 17 00:00:00 2001 From: Fogus Date: Tue, 21 Oct 2025 08:19:13 -0400 Subject: [PATCH 625/630] Add description for java.jdbc pom.xml --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 2d6da37e..acfbd83a 100644 --- a/pom.xml +++ b/pom.xml @@ -4,6 +4,7 @@ java.jdbc 0.7.13-SNAPSHOT java.jdbc + JDBC utilities for Clojure. org.clojure From ef8447a58a81ba2e67fcdc875c3fe976fea879df Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 2 Jan 2026 08:41:43 -0600 Subject: [PATCH 626/630] update permissions in workflows --- .github/workflows/doc-build.yml | 3 +++ .github/workflows/release.yml | 3 +++ .github/workflows/snapshot.yml | 3 +++ .github/workflows/test.yml | 3 +++ 4 files changed, 12 insertions(+) diff --git a/.github/workflows/doc-build.yml b/.github/workflows/doc-build.yml index 685f14ea..c7a04465 100644 --- a/.github/workflows/doc-build.yml +++ b/.github/workflows/doc-build.yml @@ -1,5 +1,8 @@ name: Build API Docs +permissions: + contents: write + on: workflow_dispatch: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e2718bd3..286cf956 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,8 @@ name: Release on demand +permissions: + contents: write + on: workflow_dispatch: inputs: diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml index 24729578..9fdad8c6 100644 --- a/.github/workflows/snapshot.yml +++ b/.github/workflows/snapshot.yml @@ -1,5 +1,8 @@ name: Snapshot on demand +permissions: + contents: read + on: [workflow_dispatch] jobs: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1fa127c9..2cc441ac 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,5 +1,8 @@ name: Test +permissions: + contents: read + on: [push] jobs: From 38f9fecb6b9066ca8479fe1ac8e6b325dac5ce30 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 2 Jan 2026 08:55:14 -0600 Subject: [PATCH 627/630] update to latest parent pom --- CHANGES.md | 4 +++- README.md | 13 +++++++++---- deps.edn | 16 ++++++++-------- pom.xml | 16 ++++++++-------- 4 files changed, 28 insertions(+), 21 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d6d50aab..2becdae8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,6 @@ -Changes not yet released +Changes in 0.8.0 + +* Update to latest parent pom and Clojure 1.11.4 as dep * Update most testing dependencies (and update a couple of tests to match). * Drop support for Clojure 1.7 & 1.8. Test against 1.9, 1.10, 1.11, and 1.12. diff --git a/README.md b/README.md index e78b88ba..d06ae4fe 100644 --- a/README.md +++ b/README.md @@ -25,25 +25,25 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.7.12 -- requires Clojure 1.7 or later! +Latest stable release: 0.8.0 -- requires Clojure 1.7 or later! * [All Released Versions](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~) [CLI/`deps.edn`](https://clojure.org/reference/deps_and_cli) dependency information: ```clojure -org.clojure/java.jdbc {:mvn/version "0.7.12"} +org.clojure/java.jdbc {:mvn/version "0.8.0"} ``` [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.7.12"] +[org.clojure/java.jdbc "0.8.0"] ``` [Maven](https://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.7.12 + 0.8.0 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -138,6 +138,11 @@ Developer Information Change Log ==================== +* Release 0.8.0 on 2025-01-02 + * Update to latest parent pom and Clojure 1.11.4 as dep + * Update most testing dependencies (and update a couple of tests to match). + * Drop support for Clojure 1.7 & 1.8. Test against 1.9, 1.10, 1.11, and 1.12. + * Release 0.7.12 on 2021-02-01 * Make the protocols `ISQLValue`, `ISQLParameter`, and `IResultSetReadColumn` extensible via metadata. diff --git a/deps.edn b/deps.edn index 48b6ef53..4d8878e7 100644 --- a/deps.edn +++ b/deps.edn @@ -5,22 +5,22 @@ {:paths ["src/main/clojure"] :aliases {:test {:extra-paths ["src/test/clojure"] - :extra-deps {org.clojure/test.check {:mvn/version "1.1.1"} - org.apache.derby/derby {:mvn/version "10.14.2.0"} - org.hsqldb/hsqldb$jdk8 {:mvn/version "2.7.2"} - com.h2database/h2 {:mvn/version "1.4.197"} + :extra-deps {org.clojure/test.check {:mvn/version "1.1.3"} + org.apache.derby/derby {:mvn/version "10.17.1.0"} + org.hsqldb/hsqldb$jdk8 {:mvn/version "2.7.4"} + com.h2database/h2 {:mvn/version "2.4.240"} net.sourceforge.jtds/jtds {:mvn/version "1.3.1"} ;; Note: Tests fail with 6.0.2+ driver mysql/mysql-connector-java {:mvn/version "5.1.41"} - org.postgresql/postgresql {:mvn/version "42.7.3"} + org.postgresql/postgresql {:mvn/version "42.7.8"} com.impossibl.pgjdbc-ng/pgjdbc-ng {:mvn/version "0.8.9"} - org.xerial/sqlite-jdbc {:mvn/version "3.45.2.0"} + org.xerial/sqlite-jdbc {:mvn/version "3.51.1.0"} ;; Note: Assumes Java 8; there's a .jre11 version as well - com.microsoft.sqlserver/mssql-jdbc {:mvn/version "12.6.1.jre8"}}} + com.microsoft.sqlserver/mssql-jdbc {:mvn/version "13.2.0.jre8"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.3"}}} :1.11 {:override-deps {org.clojure/clojure {:mvn/version "1.11.4"}}} - :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.0"}}} + :1.12 {:override-deps {org.clojure/clojure {:mvn/version "1.12.4"}}} :perf {:extra-paths ["src/perf/clojure"] :extra-deps {criterium/criterium {:mvn/version "0.4.6"}} :jvm-opts ["-server" diff --git a/pom.xml b/pom.xml index acfbd83a..77993a5a 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ org.clojure pom.contrib - 1.3.0 + 1.4.0 @@ -29,7 +29,7 @@ - 1.9.0 + 1.11.4 @@ -73,32 +73,32 @@ org.apache.derby derby - 10.14.2.0 + 10.17.1.0 test org.hsqldb hsqldb - 2.7.2 + 2.7.4 jdk8 test com.h2database h2 - 1.4.197 + 2.4.240 test org.postgresql postgresql - 42.7.3 + 42.7.8 test org.xerial sqlite-jdbc - 3.45.2.0 + 3.51.1.0 test @@ -110,7 +110,7 @@ org.clojure test.check - 1.1.1 + 1.1.3 test From 8e029074acd8bff7045b1cb39573047fdf2c1647 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 2 Jan 2026 09:02:03 -0600 Subject: [PATCH 628/630] revert derby version --- deps.edn | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/deps.edn b/deps.edn index 4d8878e7..004c697a 100644 --- a/deps.edn +++ b/deps.edn @@ -6,7 +6,7 @@ :aliases {:test {:extra-paths ["src/test/clojure"] :extra-deps {org.clojure/test.check {:mvn/version "1.1.3"} - org.apache.derby/derby {:mvn/version "10.17.1.0"} + org.apache.derby/derby {:mvn/version "10.14.2.0"} org.hsqldb/hsqldb$jdk8 {:mvn/version "2.7.4"} com.h2database/h2 {:mvn/version "2.4.240"} net.sourceforge.jtds/jtds {:mvn/version "1.3.1"} diff --git a/pom.xml b/pom.xml index 77993a5a..47091809 100644 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ org.apache.derby derby - 10.17.1.0 + 10.14.2.0 test From 068ec357eef9ef514d39d75fa8e63b2c6c0b63f6 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 2 Jan 2026 09:08:15 -0600 Subject: [PATCH 629/630] revert h2 version change --- deps.edn | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/deps.edn b/deps.edn index 004c697a..4670cbee 100644 --- a/deps.edn +++ b/deps.edn @@ -8,7 +8,7 @@ :extra-deps {org.clojure/test.check {:mvn/version "1.1.3"} org.apache.derby/derby {:mvn/version "10.14.2.0"} org.hsqldb/hsqldb$jdk8 {:mvn/version "2.7.4"} - com.h2database/h2 {:mvn/version "2.4.240"} + com.h2database/h2 {:mvn/version "1.4.197"} net.sourceforge.jtds/jtds {:mvn/version "1.3.1"} ;; Note: Tests fail with 6.0.2+ driver mysql/mysql-connector-java {:mvn/version "5.1.41"} diff --git a/pom.xml b/pom.xml index 47091809..17472a63 100644 --- a/pom.xml +++ b/pom.xml @@ -86,7 +86,7 @@ com.h2database h2 - 2.4.240 + 1.4.197 test From ec2e95286b894ff81726d04d57709a75f7a22c91 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 2 Jan 2026 09:16:59 -0600 Subject: [PATCH 630/630] revert release version --- CHANGES.md | 2 +- README.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 2becdae8..6cb2c13b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -Changes in 0.8.0 +Unreleased changes * Update to latest parent pom and Clojure 1.11.4 as dep * Update most testing dependencies (and update a couple of tests to match). diff --git a/README.md b/README.md index d06ae4fe..5c4dac6f 100644 --- a/README.md +++ b/README.md @@ -25,25 +25,25 @@ Support Releases and Dependency Information ======================================== -Latest stable release: 0.8.0 -- requires Clojure 1.7 or later! +Latest stable release: 0.7.12 -- requires Clojure 1.7 or later! * [All Released Versions](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22) * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~) [CLI/`deps.edn`](https://clojure.org/reference/deps_and_cli) dependency information: ```clojure -org.clojure/java.jdbc {:mvn/version "0.8.0"} +org.clojure/java.jdbc {:mvn/version "0.7.12"} ``` [Leiningen](https://github.com/technomancy/leiningen) dependency information: ```clojure -[org.clojure/java.jdbc "0.8.0"] +[org.clojure/java.jdbc "0.7.12"] ``` [Maven](https://maven.apache.org/) dependency information: ```xml org.clojure java.jdbc - 0.8.0 + 0.7.12 ``` _Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._ @@ -138,7 +138,7 @@ Developer Information Change Log ==================== -* Release 0.8.0 on 2025-01-02 +* Unreleased changes * Update to latest parent pom and Clojure 1.11.4 as dep * Update most testing dependencies (and update a couple of tests to match). * Drop support for Clojure 1.7 & 1.8. Test against 1.9, 1.10, 1.11, and 1.12.