 
 ;
 ;
-;
+; Methods for providing a sql abstraction over the column store.
+;
+;
+
 
 (def ^:private field-ids-query
   (cached-statement

      (map :row)))

(defn fetch-genes [field-id values]
  (into #{} (field-genes field-id values)))

(defn fetch-indexed [fields field values]
  (let [field-id (fields field)]
    (cond
      (has-position? field-id) #{})
      (has-genes? field-id) (fetch-genes field-id values)))

(defn eval-sql [{[from] :from where :where select :select :as exp}]
  (let [{dataset-id :id N :rows} (dataset-by-name from :id :rows)
        fields (into {} (fetch-field-ids dataset-id
                                         (into (collect-fields where) select)))
        fetch (partial fetch-rows fields (atom {}))]
    ; XXX project, perhaps in sqleval
  (evaluate (range N) {:fetch fetch
                       :fetch-indexed (partial fetch-indexed fields)
                       :indexed? (partial has-index? fields)} exp)))


; Each req is a map of
;  :table "tablename"

    (fn [row]
      (apply getter (bin-offset row)))))

(def ^:private field-genes-by-row-query
  (cached-statement
    "SELECT `row`, `gene` FROM `field_gene`
    INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row`
    WHERE `field_id` = ?"
    true))

(defn field-genes-by-row [field-id rows]
  (->> (field-genes-by-row-query rows field-id)
      (map (juxt :row :gene))))

(defmethod fetch-rows :gene [cache rows field-id]
  (into {} (field-genes-by-row field-id rows)))

(def ^:private field-position-by-row-query
  (cached-statement
    "SELECT `row`, `chrom`, `chromStart`, `chromEnd` FROM `field_position`
    INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row`
    WHERE `field_id` = ?"
    true))

(defn field-position-by-row [field-id rows]
  (->> (field-position-by-row-query rows field-id)
      (map (fn [{:keys [row] :as values}] [row (dissoc values :row)]))))

(defmethod fetch-rows :position [cache rows field-id]
  (into {} (field-position-by-row field-id rows)))

; might want to use a reader literal for field names, so we
; find them w/o knowing syntax.
(defn collect-fields [exp]
