Created
January 21, 2013 07:46
-
-
Save semisight/4584333 to your computer and use it in GitHub Desktop.
These files will show a problem when using clojure's `map` with clojure.java.jdbc's (formerly known as clojure.contrib.sql) `insert-record`. To run, create a new app with lein (2) called db, then use `lein run`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns db.core | |
(:use clojure.java.jdbc) | |
(:gen-class)) | |
(def db | |
{:classname "org.sqlite.JDBC" | |
:subprotocol "sqlite" | |
:subname "test.db"}) | |
(def schema | |
[[:id :int "PRIMARY KEY"] | |
[:name :text] | |
[:age :int]]) | |
(def one-row | |
{:id 0 | |
:name "User" | |
:age 30}) | |
(def multi-row | |
[ | |
{:id 11 | |
:name "Number One" | |
:age 30} | |
{:id 12 | |
:name "Number Two" | |
:age 30} | |
{:id 13 | |
:name "Number Three" | |
:age 30} | |
]) | |
(def multi-row-fail | |
[ | |
{:id 1 | |
:name "Fail One" | |
:age 30} | |
{:id 2 | |
:name "Fail Two" | |
:age 30} | |
{:id 3 | |
:name "Fail Three" | |
:age 30} | |
]) | |
(defn -main [& args] | |
; create a test table in the db | |
(println "Creating table (and database file)") | |
(with-connection db | |
(apply create-table :test schema)) | |
; this insert will work | |
(println "Performing single row insert") | |
(with-connection db | |
(insert-record :test one-row)) | |
; ...as will this | |
(println "Performing batch insert") | |
(with-connection db | |
(apply insert-records :test multi-row)) | |
; but here, it will fail. Why? | |
(println "Performing multi insert by 'map'") | |
(with-connection db | |
(map #(insert-record :test) multi-row-fail)) | |
; this fails too: | |
; | |
; (map | |
; (fn [row] | |
; (with-connection db | |
; (insert-record :test row))) | |
; multi-row-fail) | |
; see final results: | |
(with-connection db | |
(with-query-results rows ["SELECT * FROM test"] | |
(println (map :id rows))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defproject db "0.1.0-SNAPSHOT" | |
:description "FIXME: write description" | |
:url "http://example.com/FIXME" | |
:license {:name "Eclipse Public License" | |
:url "http://www.eclipse.org/legal/epl-v10.html"} | |
:dependencies [[org.clojure/clojure "1.4.0"] | |
[org.clojure/java.jdbc "0.2.3"] | |
[org.xerial/sqlite-jdbc "3.7.2"]] | |
:main db.core) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment