Skip to content

Commit

Permalink
Added validation ns.
Browse files Browse the repository at this point in the history
  • Loading branch information
r0man committed Oct 2, 2013
1 parent 99d9973 commit 478a326
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion project.clj
Expand Up @@ -17,7 +17,7 @@
[mysql/mysql-connector-java "5.1.26"]
[slingshot "0.10.3"]
[sqlingvo "0.5.6"]]
:profiles {:dev {:dependencies [[validation-clj "0.5.5"]
:profiles {:dev {:dependencies [[validation-clj "0.5.6"]
[org.slf4j/slf4j-log4j12 "1.7.5"]
[c3p0/c3p0 "0.9.1.2"]
[com.jolbox/bonecp "0.7.1.RELEASE"]]
Expand Down
28 changes: 28 additions & 0 deletions src/datumbazo/validation.clj
@@ -0,0 +1,28 @@
(ns datumbazo.validation
(:refer-clojure :exclude [replace])
(:require [clojure.string :refer [blank?]]
[datumbazo.core :refer [select from limit run1 where]]))

(defn new-record? [record]
(blank? (str (:id record))))

(defn uniqueness-of
"Validates that the record's attributes are unique."
[db table columns & {:keys [error] :as opts}]
(fn [record]
(let [error (or error "has already been taken")
columns (if (sequential? columns) columns [columns])
vals (map record columns)
condition `(and ~@(map (fn [c v] `(= ~c ~v)) columns vals))]
(if (and (or (nil? (:if opts))
((:if opts) record))
(run1 db (select columns
(from table)
(where condition)
(limit 1))))
(reduce
(fn [record column]
(with-meta record
(assoc-in (meta record) [:errors column] error)))
record columns)
record))))
1 change: 1 addition & 0 deletions test/datumbazo/core_test.clj
Expand Up @@ -5,6 +5,7 @@
[clojure.java.io :refer [file]]
[environ.core :refer [env]]
[validation.core :refer :all]
[datumbazo.validation :refer [new-record? uniqueness-of]]
[slingshot.slingshot :refer [try+]])
(:use clojure.test
datumbazo.core
Expand Down
15 changes: 15 additions & 0 deletions test/datumbazo/validation_test.clj
@@ -0,0 +1,15 @@
(ns datumbazo.validation-test
(:require [clojure.test :refer :all]
[datumbazo.core :refer [run1]]
[datumbazo.validation :refer :all]
[slingshot.slingshot :refer [try+]]
[sqlingvo.core :refer [sql]]
[validation.core :refer :all]))

(deftest test-uniqueness-of
(with-redefs [run1 (fn [db stmt]
(is (= ["SELECT \"nick\" FROM \"users\" WHERE (\"nick\" = ?) LIMIT 1" "Bob"]
(sql stmt)))
[])]
(let [errors (:errors (meta ((uniqueness-of nil :users :nick) {:nick "Bob"})))]
(is (= "has already been taken" (:nick errors))))))

0 comments on commit 478a326

Please sign in to comment.