 (defn fetch-metadata
   "Fetch dataset metadata (everything apart from rows)"
   [tenant-conn id]
-  (if-let [dataset (dataset-by-id tenant-conn {:id id})]
+  (if-let [dataset (db.dataset/dataset-by-id tenant-conn {:id id})]
     (let [columns (remove #(get % "hidden") (:columns dataset))]
       (lib/ok
        {:id id


(defn sort-text
  [tenant-conn id column-name limit]
  (when-let [dataset (table-name-by-dataset-id tenant-conn {:id id})]
    (->> (merge {:column-name column-name :table-name (:table-name dataset)}
                (when limit {:limit limit}))
         (count-vals-by-column-name tenant-conn)
         (map (juxt :counter :coincidence)))))

(defn sort-number
  [tenant-conn id column-name]
  (when-let [dataset (table-name-by-dataset-id tenant-conn {:id id})]
    (merge (->> {:column-name column-name :table-name (:table-name dataset)}
                (count-num-vals-by-column-name tenant-conn))
           (->> {:column-name column-name :table-name (:table-name dataset)}
                (count-unique-vals-by-colum-name tenant-conn)))))

(defn delete
  [tenant-conn id]
  (if-let [dataset (dataset-by-id tenant-conn {:id id})]
    (if-let [datasets-merged-with (transformation.merge-datasets/datasets-related tenant-conn id)]
      (lib/conflict {:error (format "Cannot delete dataset. It is used in merge transformations of dataset: %s"
                                    (str/join ", " (map :title datasets-merged-with)))})
      (let [c (delete-dataset-by-id tenant-conn {:id id})]
        (if (zero? c)
          (do
            (delete-failed-job-execution-by-id tenant-conn {:id id})
            (lib/not-found {:error "Not found"}))
          (let [v (delete-maps-by-dataset-id tenant-conn {:id id})](lib/ok {:id id})))))
    (lib/not-found {:error "Not found"})))

(defn update
  [tenant-conn caddisfly import-config error-tracker dataset-id {:strs [token email]}]
  (if-let [{data-source-spec :spec
            data-source-id   :id} (data-source-by-dataset-id tenant-conn {:dataset-id dataset-id})]
    (if-let [error (transformation.merge-datasets/consistency-error? tenant-conn dataset-id)]
      (lib/conflict error)
      (if-not (= (get-in data-source-spec ["source" "kind"]) "DATA_FILE")


(defn fetch
  [tenant-conn id]
  (when-let [dataset (db.dataset/dataset-by-id tenant-conn {:id id})]
    (let [columns (remove #(get % "hidden") (:columns dataset))
          data (rest (jdbc/query tenant-conn
                                 [(select-data-sql (:table-name dataset) columns)]
                                 {:as-arrays? true}))]

      
      (-> dataset
          (select-keys [:created :id :modified :status :title :transformations :updated :author :source])
          (rename-keys {:title :name})
