 (defn ent
   "Get an entity by attribute value"
   [attr value]
-  (map #(d/entity (d/db db) (first %))
+  (map #(d/entity (d/db t-state/db) (first %))
        (d/q '[:find ?e
               :in $ ?attr-in ?attr
               :where [?e ?attr-in ?attr]]
-            (d/db db)
+            (d/db t-state/db)
             attr value)))
 
 (defn count-ents

            [inflections.core :refer [plural]]
            [traveler.schema :as t-schema]
            [traveler.state :as t-state]))

(def db t-state/db)

(def tx-entity! (partial hatch/tx-clean-entity! t-schema/partitions t-schema/valid-attrs))


   (d/q '[:find (count ?e)
          :in $ ?a
          :where [?e ?a]]
        (d/db t-state/db)
        attr)))

(defn ents
  "Return all entities that have specific attribute
  with option to limit or limit and offset them"
  ([attr]
   (map #(d/entity (d/db t-state/db) (first %))
        (sort (d/q '[:find ?e
                     :in $ ?a
                     :where [?e ?a]]
                   (d/db t-state/db)
                   attr))))
  ([attr limit]
   (map #(d/entity (d/db t-state/db) (first %))
        (take limit (sort (d/q '[:find ?e
                                 :in $ ?a
                                 :where [?e ?a]]
                               (d/db t-state/db)
                               attr)))))
  ([attr limit offset]
   (map #(d/entity (d/db t-state/db) (first %))
        (take limit (drop offset (sort (d/q '[:find ?e
                                              :in $ ?a
                                              :where [?e ?a]]
                                            (d/db t-state/db)
                                            attr)))))))

(defn find-ents
  "Find an entity using a case-insensitive regex match"
  [attr match]
  (map #(d/entity (d/db t-state/db) (first %))
       (d/q '[:find ?e
              :in $ ?attr ?matcher
              :where
              [?e ?attr ?ln]
              [(re-find ?matcher ?ln)]]
            (d/db t-state/db)
            attr (re-pattern (str "(?i:.*" match ".*)")))))

(defn user->db
  "Take pre-validated user map from liberator request
  and transact to database"
  [user]
  (tx-entity! t-state/db :user (hatch/slam-all user :user)))

(defn ent->map
  "Convert an entity to a map using an output-model"
