1. Shantanu Kumar
  2. SQLRat


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
    (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
    (doseq [param-group param-groups]
      (doseq [[index value] (map vector (iterate inc 1) param-group)]
        (.setObject stmt index value))
      (.addBatch stmt))
     (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]
   (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)))

(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)

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