 
 (defnk create-session
   [contact-points datacenter keyspace :as args]
-  (->AliaSession
-   keyspace
-   (create-alia-session* args)))
+  (with-context deferred-context
+    (mlet [datastax-session (create-alia-session* args)]
+      (->AliaSession
+       keyspace
+       datastax-session))))
 
 (defn mutated-tables
   [spy-session]


(defnk create-spy-session
  [contact-points datacenter keyspace {truncate-on-close nil} :as args]
  (->AliaSpySession
   keyspace
   (create-alia-session* (dissoc args :truncate-on-close))
   (atom [])
   truncate-on-close))

(defn with-spy-session-reset*
  "start an alia spy-session, call a function and truncate
  all tables which were touched during the function"
  [spy-session f]
  (try
    (f)
    (finally
      (truncate-spy-tables spy-session))))

(defmacro with-spy-session-reset
  [spy-session & body]
  `(with-spy-session-reset*
     ~spy-session
     (fn [] ~@body)))

;; a test-session is just a spy-session which will initialise it's keyspace
;; if necesary and will truncate any used tables when closed
(defnk create-test-session
  [{contact-points nil} {port nil} {datacenter nil} keyspace :as args]
  (let [session
        (create-spy-session
           (merge
            args
            {:contact-points (or contact-points ["localhost"])
             :port (or port
                       (some-> (env :cassandra-port) Integer/parseInt)
                       9042)
             :datacenter datacenter
             :init-statements
             [(str "CREATE KEYSPACE IF NOT EXISTS "
                   "  \"${keyspace}\" "
                   "WITH replication = "
                   "  {'class': 'SimpleStrategy', "
                   "   'replication_factor': '1'} "
                   " AND durable_writes = true;")]

             :truncate-on-close true}))]
    [session
     (fn [] (s/close session))]))


        _ (info "create-alia-session*" args)
        cluster (alia/cluster cluster-args)
        alia-session (alia/connect cluster)

        init-fns (for [stmt init-statements]
                   (fn [_]
                     (as-> stmt %
                       (str/replace % "${keyspace}" keyspace)
                       (alia/execute alia-session %))
                     (return deferred-context true)))]

    (with-context deferred-context
      (mlet [_ (apply >>= (return true) init-fns)
             _ (alia/execute alia-session (str "USE " keyspace ";"))]
        (return alia-session)))))

(defrecord AliaSession [keyspace alia-session]
  Session
