Source

SQLRat / src / main / clj / org / bituf / sqlrat / entity / internal.clj

(ns org.bituf.sqlrat.entity.internal
  (:import java.sql.Statement)
  (:use clojure.contrib.pprint)
  (:use [clojure.contrib.sql :as sql :only ()])
  (:use org.bituf.sqlrat.util)
  (:use org.bituf.sqlrat.clause))


(defn mypp ; My Pretty Print
  ([obj]
    (pprint obj))
  ([title obj]
    (println title)
    (pprint obj))
  ([title obj & more]
    (println title)
    (pprint obj)
    (doseq [each more] (pprint each))))


(defn do-prepared-insert
  "Executes an (optionally parameterized) SQL prepared statement on the
  open database connection. Each param-group is a seq of values for all of
  the parameters."
  [sql & param-groups]
  (with-open [stmt (.prepareStatement (sql/connection) sql
                     Statement/RETURN_GENERATED_KEYS)]
    (doseq [param-group param-groups]
      (doseq [[index value] (map vector (iterate inc 1) param-group)]
        (.setObject stmt index value))
      (.addBatch stmt))
    (sql/transaction
     (seq (.executeBatch stmt))
     (into [] (resultset-seq (.getGeneratedKeys stmt))))))


(defn update-or-insert-values-returnid
  "Updates values on selected rows in a table, or inserts a new row when no
  existing row matches the selection criteria. where-params is a vector
  containing a string providing the (optionally parameterized) selection
  criteria followed by values for any parameters. record is a map from
  strings or keywords (identifying columns) to updated values."
  [table where-params record]
  (sql/transaction
   (let [result (sql/update-values table where-params record)]
     (if (zero? (first result))
       (binding [sql/do-prepared do-prepared-insert]
         (sql/insert-values table (keys record) (vals record)))
       result))))


(defn get-original-entity
  "Find parent entity for the specified child-entity from a group of entities"
  [entities this-column rel-entity that-column]
  (let [foreign-key (that-column rel-entity)]
    (first (filter #(= (this-column %) foreign-key)
             entities))))


(defn assert-criteria
  "Assert query criteria"
  [{:keys [cols where groupby other]}]
  (assert (vector? cols))
  (assert (clause? where))
  (assert (vector? groupby))
  (assert (clause? other)))