Search code examples
databasepostgresqlherokuclojureheroku-postgres

Accessing a database with Clojure


Here is a simple question concerning Clojure and accessing information from a database.

The following code, inside a function of mine is working:

(defn insertNewValue []
(let [newRank
        (reduce + 1
          (map :max
            (db/query (env :database-url) ["select max(rank) from My_Table"])))
      .........

But using reduce when there is only one record resulting from the DB query does not seem very appropriate to me. So here is what I tried as a replacement:

(defn insertNewValue []
(let [dbRecord (db/query (env :database-url) ["select max(rank) from My_Table"])
      newRank (+ 1 (:max dbRecord))
      .........

which seems much cleaner, but it does not work!

Can anyone tell me what I am doing wrong?


Solution

  • It seems that dbRecord would return a list (thats why you could map over it), however, in your second attempt you are treating it as a map directly. Since it is guaranteed that you only have a single record (you are querying for the max value), perhaps you need to do

    (inc (:max (first dbRecord)))