Browse files

Extract find-by-sql from find-records, allowing the caller to run arb…

…itrary queries and still have the results given the callback treatment for a defined model.
  • Loading branch information...
1 parent c8d1248 commit 796d7e5ed1892cbcc56b5266e1c16911d0f62935 @duelinmarkers committed Jun 19, 2009
Showing with 19 additions and 3 deletions.
  1. +14 −3 src/clj_record/core.clj
  2. +5 −0 src/clj_record/test/core_test.clj
@@ -79,6 +79,17 @@
(connected (db-spec-for model-name)
(get-record model-name id))))
+(defn find-by-sql
+ "Returns a vector of matching records.
+ select-query-and-values should be something like
+ [\"SELECT id, name FROM manufacturers WHERE id = ?\" 23]
+ This allows the caller total control over the SELECT and FROM clauses, but note that callbacks are still run,
+ so if you omit columns your callbacks will have to be written to tolerate incomplete records."
+ [model-name select-query-and-values]
+ (connected (db-spec-for model-name)
+ (sql/with-query-results rows select-query-and-values
+ (doall (map #(run-callbacks (merge {} %) model-name :after-load) rows)))))
(defn find-records
"Returns a vector of matching records.
Given a where-params vector, uses it as-is. (See clojure.contrib.sql/with-query-results.)
@@ -89,9 +100,7 @@
(to-conditions attributes-or-where-params)
select-query (format "select * from %s where %s" (table-name model-name) parameterized-where)]
- (connected (db-spec-for model-name)
- (sql/with-query-results rows (apply vector select-query values)
- (doall (map #(run-callbacks (merge {} %) model-name :after-load) rows))))))
+ (find-by-sql model-name (apply vector select-query values))))
(defn update
"Updates by (partial-record :id), updating only those columns included in partial-record."
@@ -158,6 +167,8 @@
(get-record ~model-name id#))
(defn ~'find-records [attributes#]
(find-records ~model-name attributes#))
+ (defn ~'find-by-sql [select-query-and-values#]
+ (find-by-sql ~model-name select-query-and-values#))
(defn ~'create [attributes#]
(create ~model-name attributes#))
(defn ~'insert [attributes#]
@@ -38,6 +38,11 @@
other-1 (manufacturer/create (valid-manufacturer-with {:name "Some Other"}))]
(is (= [humedai] (manufacturer/find-records ["name = ?" "Humedai Motors"])))))
+(defdbtest find-by-sql-uses-a-complete-query
+ (let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))]
+ (is (= (manufacturer/find-records ["name = ?" "Humedai Motors"])
+ (manufacturer/find-by-sql ["SELECT * FROM manufacturers WHERE name = ?" "Humedai Motors"])))))
(defdbtest destroy-record-destroys-by-id-from-record
(let [humedai (manufacturer/create (valid-manufacturer-with {:name "Humedai Motors"}))]
(manufacturer/destroy-record {:id (humedai :id)})

0 comments on commit 796d7e5

Please sign in to comment.