Skip to content

Commit

Permalink
Better errors for 1 or n unique constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Walker committed Aug 8, 2018
1 parent 4752562 commit 1c11a25
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/coast/db/errors.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
(ns coast.db.errors
(:require [coast.utils :as utils]
[clojure.string :as string]))
[clojure.string :as string]
[clojure.edn :as edn]))

(defn not-null-constraint [s]
(let [col (-> (re-find #"null value in column \"(.*)\" violates not-null constraint" s)
Expand All @@ -12,13 +13,23 @@
:db.constraints/not-null (keyword col)})))

(defn unique-constraint [s]
(let [col (-> (re-find #"(?s)duplicate key value violates unique constraint.*Detail: Key \((.*)\)=\((.*)\)" s)
(second))]
(if (nil? col)
{}
{(keyword col) (str (utils/humanize col) " is already taken")
::error :unique-constraint
:db.constraints/unique (keyword col)})))
(let [[name cs vs] (->> (re-seq #"(?s)duplicate key value violates unique constraint \"(.*)\".*Detail: Key \((.*)\)=\((.*)\)" s)
(first)
(drop 1))
table (first (string/split name #"_"))
cols (->> (string/split cs #",")
(map string/trim)
(map keyword))
msg-values (map #(str (utils/humanize %) " already exists") cols)
values (->> (string/split vs #",")
(map string/trim)
(map edn/read-string))
m (zipmap cols values)
message-map (zipmap cols msg-values)]
(merge message-map {:db.constraints/unique name
::error :unique-constraint
::value m
::message (str "That " table " already exists")})))

(defn error-map [ex]
(let [s (.getMessage ex)
Expand Down

0 comments on commit 1c11a25

Please sign in to comment.