Clojure.contrib.sql and REPL interaction

We have a Clojure web application that uses jndi to create a database connection. The code for querying the database looks something like this:

(def jndi-name {:name "jndi name"}) (defn query [q] (sql/with-connection {:name "jndi name"} (sql/with-query-results rs q (time (vec rs))))) 

The jndi configuration is loaded from the jetty.xml file when the berth is poured. However, this does not work in the development of REPL is somewhat impractical.

Is there a way to structure the code so that when running on the server, the db configuration is loaded from the configuration file, and not from the jetty.xml file when the jndi context is not available?

+4
source share
1 answer

The problem is that your way to connect to the database will not always be, although JNDI; for example, when testing or in REPL, you can manage your own connection pool.

I suggest you keep the db specification as var . Thus, the only change to your code is to rename the variable; because you intend to reinstall it, usually use asterisks:

 (def *db-spec* {:name "jndi name"}) (defn query [q] (sql/with-connection *db-spec* (sql/with-query-results rs q (time (vec rs))))) (query "select * from Students") 

And when testing on repl, just create your own data source, say Commons-DBCP, and reinstall its db specification.

 (def ds (doto (BasicDataSource.) (.setDriverClassName "oracle.jdbc.OracleDriver") (.setUsername "tiger") (.setPassword "scott"))) (binding [*db-spec* {:datasource ds}] (query "select * from Students")) 
+2
source

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


All Articles