开发者

Compojure + clojure.contrib.sql: SELECT query is being cached. Why?

I'm writing a Compojure TODO app and with MySQL as the primary data store. I'm using clojure.contrib.sql to interface with MySQL as follows:

(def db {:classname "com.mysql.jdbc.Driver"
         :subprotocol "mysql"
         :subname "//localhost:3306/todo"
         :user "<user>"
         :password ""})

The queries I'm using seem to work, however the results appear to be cached. For example, after running

(with-connection db
  (insert-values :todos
    [:name] [name]))

the value is successfully inserted into the database. However,

(defn sql-query [query]
  (with-connection db
    (with-query-results rows [query]
      (into [] rows))))

returns the same value, regardless of how many items are inserted. Of course, if I restart the web app, the results are up开发者_开发知识库dated, but this doesn't seem very production-friendly :).

Any idea why this would be happening? Thanks in advance.

As requested, here is the top-level form for the SELECT query:

(def home-view
  (render
    (base {:title "Clojure Todo"
           :content (apply str
             (map #(% :name)
               (sql-query "select * from todos")))})))


From the most recently added comment on the answer together with the most recent update to the question text I gather that the problem is nothing to do with clojure.contrib.sql, it's with the defroutes form.

(defroutes todo (GET "/" [] home-view)) means that requests matching this route will receive home-view as a reply. Now home-view is evaluated only once, when the (def home-view ...) form is evaluated -- and in particular, the associated SQL query is executed only once.

To fix this, rewrite home-view as a function and have the route call it, perhaps like so:

(defn home-view []
  ...the render form from your old (def home-view ...) form goes here...
  )

(defroutes todo (GET "/" [] (home-view)))

Then home-view-the-function will be called each time the route gets triggered (and execute its SQL query once per each such call).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜