Compojure + clojure.contrib.sql: SELECT query is cached. What for?

I am writing a Compojure TODO and MySQL application as the main data warehouse. I use clojure.contrib.sql to interact with MySQL as follows:

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

The queries I use seem to work, however the results seem to be cached. For example, after starting

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

The value was successfully inserted into the database. Nonetheless,

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

returns the same value no matter how many elements are inserted. Of course, if I restart the web application, the results will be updated, but this is not very convenient for production :).

Any idea why this will happen? 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")))}))) 
+4
source share
1 answer

From the last added comment to the answer, along with the last update of the question text, I understand that the problem has nothing to do with clojure.contrib.sql , it is with the form defroutes .

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

To fix this, rewrite the home-view as a function and call its route, possibly like this:

 (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 every time the route starts (and executes its SQL query once for each such call).

+3
source

Source: https://habr.com/ru/post/1314495/


All Articles