Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)))))) |