     (let [[query & params] results-query
           limited-query (add-limit-clause limit query)
           query-results (limited-query-to-vec limit (apply vector limited-query params))
-          results       {:result (post-process-results query-results paging-options)}]
+          results       {:result
+                          (post-process-results
+                            query-results
+                            (:order-by paging-options))}]
       (if count-query
         (assoc results :count (get-result-count count-query))
         results))))

        (comp-fn2 x y)
        val1))))

(defn- sort-on-order-by
  "Sort the results of the query based on the order by clauses."
  [query-results order-bys]
  {:pre  [(vector? query-results)
          (vector? order-bys)
          (every? map? order-bys)]
   :post [(vector? %)
          (= (count %)
             (count query-results))]}
  (let [order-bys  (mapv #(update-in % [:field] keyword) order-bys)
        comp-fns   (map build-comp-fn order-bys)
        final-comp (reduce combine-comp-fns comp-fns)
        sorted     (sort final-comp query-results)]
    (vec sorted)))

(defn- post-process-results
  "Given the results of the query and the optional order-by paging clauses,
  consolidate the results into a form appropriate for returning to the user
  and sort them based on the order-by clauses, if there are any."
  [query-results {:keys [order-by]}]
  {:pre  [(vector? query-results)
          ((some-fn nil? vector?) order-by)
          (every? map? order-by)]
   :post [(vector? %)]}
  (let [consolidated-results (consolidate-resource-params query-results)]
    (if (empty? order-by)
      consolidated-results
      (sort-on-order-by consolidated-results order-by))))

(defn limited-query-resources
  "Take a limit, a map of paging options, and a map of SQL queries as

                  (into {} (for [param params :when (:name param)]
                             [(:name param) (json/parse-string (:value param))])))))))

(defn ordered-comparator
  "Given a function and an order (:ascending or :descending),
  return a comparator function that takes two objects and compares them in
  ascending or descending order based on the value of applying the function
  to each."
  [f order]
  {:pre  [(ifn? f)
          (contains? #{:ascending :descending} order)]
   :post [(fn? %)]}
  (fn [x y]
    (if (= order :ascending)
      (compare (f x) (f y))
      (compare (f y) (f x)))))

(defn compose-comparators
  "Composes two comparator functions into a single comparator function
  which will call the first comparator and return the result if it is
  non-zero; otherwise it will call the second comparator and return
  its result."
  [comp-fn1 comp-fn2]
  {:pre  [(fn? comp-fn1)
          (fn? comp-fn2)]
