        :columns (mapv name columns)
        :rows    (for [row results]
                   (mapv row columns))})))
+
+;; #_(require 'metabase.driver)
+;; (require 'metabase.test.data)
+;; (require 'metabase.test.data.datasets)
+;; (defn x []
+;;   (metabase.test.data.datasets/with-dataset
+;;     :postgres
+;;     (metabase.driver/process-query
+;;      {:type :query,
+;;       :database (metabase.test.data/db-id),
+;;       :query
+;;       {:source_table (metabase.test.data/id :venues),
+;;        :filter
+;;        ["INSIDE"
+;;         (metabase.test.data/id :venues :latitude)
+;;         (metabase.test.data/id :venues :longitude)
+;;         10.0649
+;;         -165.379
+;;         10.0641
+;;         -165.371],
+;;        :aggregation ["rows"],
+;;        :breakout [nil],
+;;        :limit nil}})))


;;; ## Top-Level Resolution / Ordering

(defn- resolve+order-cols [query]
  {:post [(or (sequential? %)
              (println "FAILED!\n" (u/pprint-to-str query) "\nRESULTS:" %))
          (every? map? %)]}
  (let [num-cols   (count (:result-keys query))
        cols       (vec (lvars num-cols))
        ;; A few queries take a ridiculous amount of time to order. Let's do some ghetto profiling
        start-time (System/currentTimeMillis)
        results    (first (run 1 [q]
                            (== q cols)
                            (distincto q)
                            (everyg (partial fieldo query) q)
                            (everyg (fn [i]
                                      (fields< query (cols i) (cols (inc i))))
                                    (range 0 (dec num-cols)))))
        run-time   (- (System/currentTimeMillis) start-time)]
    (when (> run-time 2000)
      (println (u/format-color 'red "This query took a STUPID LONG amount of time to order (%.1f seconds):\n%s\n%s" (/ run-time 1000.0)
                               (u/pprint-to-str query) (u/pprint-to-str results))))

(defn- breakout-fieldo [{breakout-fields :breakout} field]
  (member1o field breakout-fields))

(defn- aggregate-fieldo [field]
  (fresh [ag-field?]
    (featurec field {:ag-field? ag-field?})
    (== ag-field? true)))

(defn- explicit-fields-fieldo [{:keys [fields-is-implicit], fields-fields :fields} field]
  (all (nilo fields-is-implicit)
       (member1o field fields-fields)))

(defn- valid-nameo [{:keys [result-keys]} field]
  (fresh [field-name]
    (featurec field {:field-name field-name})
    (member1o field-name result-keys)))


;;; ## Ordering
