     (when-let [uuid (string->uuid id)]
       (sql/query
         (:connection db)
-        [" select h.*, hs.step_id
-           from histories as h
-           left join history_step as hs on h.id = hs.history_id
-           where h.id = ? and h.owner = ?
-           order by hs.created_at desc " uuid (:user staircase.resources/context)] 
+        (one-history-query uuid)
         :result-set-fn #(if (empty? %) nil (apply build-history %)))))
 
   (update [_ id doc] (staircase.sql/update-owned-entity

  Resource

  (get-all [histories]
    (into [] (sql/query (:connection db)
                        (-> (select :h.id :h.title :h.created_at :h.description :h.owner [:%count.hs.* :steps])
                            (from [:histories :h])
                            (left-join [:history_step :hs] [:= :h.id :hs.history_id])
                            (group :h.id :h.title :h.created_at :h.description :h.owner)
                            (where [:= :h.owner :?user])
                            (hsql/format :params staircase.resources/context)))))

  (exists? [_ id] (staircase.sql/exists-with-owner (:connection db) :histories id (:user staircase.resources/context)))


    (reduce f init rows)))

(def table-spec (merge schema/histories schema/history-step))

(defn- all-history-query []
  (-> (select :h.id :h.title :h.created_at :h.description :h.owner [:%count.hs.* :steps])
                    (from [:histories :h])
                    (left-join [:history_step :hs] [:= :h.id :hs.history_id])
                    (group :h.id :h.title :h.created_at :h.description :h.owner)
                    (where [:= :h.owner :?user])
                    (order-by [:h.created_at :desc])
                    (hsql/format :params staircase.resources/context)))

(defn- one-history-query [history]
  (-> (select :h.*, :hs.step_id)
      (from [:histories :h])
      (left-join [:history_step :hs] [:= :h.id :hs.history_id])
      (where [:and
              [:= :h.id :?history]
              [:= :h.owner :?user]])
      (order-by [:hs.created_at :desc])
      (hsql/format :params (assoc staircase.resources/context :history history))))

(defrecord HistoryResource [db]
  component/Lifecycle
