     (if-let [dataset (dataset-by-id conn {:id dataset-id})]
       (let [q (build-query (:columns dataset) query)]
         (if (valid-query? q)
-          (http/ok (run-query conn dataset q (filter/sql-str (:columns dataset) (:filters q))))
+          (try
+            (http/ok (apply-query conn dataset q (filter/sql-str (:columns dataset) (:filters q))))
+            (catch clojure.lang.ExceptionInfo e
+              (http/bad-request (merge {:message (.getMessage e)}
+                                       (ex-data e)))))
           (http/bad-request {"query" query})))
       (http/not-found {"datasetId" dataset-id}))))
 

                        {:as-arrays? true}))
     :columns columns}))

(defn find-column [columns column-name]
  (first (filter #(= column-name (get % "columnName"))
                 columns)))

(defn build-query
  "Replace column names with proper column metadata from the dataset"

  (def q {"categoryColumn" "c16"
          "rowColumn" "c4"
          "valueColumn" "c19"
          "aggregation" "avg"
          "filters" [{"column" "c2"
                      "columnType" "text"
                      "operation" "keep"
                      "strategy" "is"
                      "value" "Ethiopia"}]})

  (def empty-q {"categoryColumn" nil
                "rowColumn" nil
                "valueColumn" nil
                "aggregation" "count"
                "filters" []})

  (query tenant-conn dataset-id empty-q)

  (unique-categories tenant-conn dataset-id)

