Skip to content

Instantly share code, notes, and snippets.

@semisight
Created January 21, 2013 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save semisight/4584333 to your computer and use it in GitHub Desktop.
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`.
(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)))))
(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