Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. (ns testmultiple.core
  2. (:require
  3. [clojure.java.jdbc :as jdbc]
  4. [compojure.core :refer [defroutes GET ANY routes context]]
  5. [conman.core :as conman]
  6. [mount.core :refer [defstate]]))
  7.  
  8. (def database-urls {:DB1 "jdbc:mysql://localhost:3306/DB1?user=DB1_user&password=DB1_password"
  9. :DB2 "jdbc:mysql://localhost:3306/DB2?user=DB2_user&password=DB2_password"})
  10.  
  11. ;; Connects to all databases in pool-specs
  12. (defn connect!
  13. [pool-specs]
  14. (reduce merge (map (fn [pool-spec]
  15. {(keyword (key pool-spec)) (conman/connect! {:jdbc-url (val pool-spec)})}) pool-specs)))
  16.  
  17. ;; Disconnect from all databases in db-connections
  18. (defn disconnect!
  19. [db-connections]
  20. (map (fn [db] (conman/disconnect! (val db))) db-connections))
  21.  
  22. ;; Establish connections to all databases
  23. ;; and store connections in *dbs*
  24. (defstate ^:dynamic *dbs*
  25. :start (connect!
  26. database-urls)
  27. :stop (disconnect! *dbs*))
  28.  
  29. ;; Bind queries to *db* dynamic variable which is bound
  30. ;; to each clients database before executing queries
  31. ;; The queries file defines the query get-user which
  32. ;; returns user by user id
  33. (def ^:dynamic *db* nil)
  34. (conman/bind-connection *db* "sql/queries.sql")
  35.  
  36. (mount.core/start)
  37.  
  38. ; Define function that executes in current *db* binding
  39. (defn getuser [id] (get-user {:id id}))
  40.  
  41. ; Works, the user with Id 670 is returned from DB1
  42. (with-bindings {#'*db* (:DB1 *dbs*)} (getuser 670))
  43.  
  44. ; Works, the user with Id 670 is returned from DB2
  45. (with-bindings {#'*db* (:DB2 *dbs*)} (getuser 670))
  46.  
  47. (defn serve-page1 [] (str "page1" (getuser 670)))
  48. (defn serve-page2 [] (str "page2" (getuser 670)))
  49.  
  50. (def home-routes
  51. (context "/:project" [project]
  52. (if (contains? *dbs* (keyword project))
  53. (routes
  54. (GET "/page1" []
  55. (with-bindings {#'*db* ((keyword project) *dbs*)}
  56. (serve-page1)))
  57. (GET "/page2" []
  58. (with-bindings {#'*db* ((keyword project) *dbs*)}
  59. (serve-page2))))
  60. (ANY "*" [] (str "Project not found")))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement