Skip to content

Commit

Permalink
Create table constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
Aitem committed Dec 14, 2023
1 parent d4ade21 commit 22cb4b1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
16 changes: 14 additions & 2 deletions src/dsql/pg.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1138,9 +1138,18 @@
[])
(ql/fast-join ", ")))

(defn mk-table-constraint [{:keys [primary-key] :as constraint}]
(str/join
","
(cond-> []
primary-key
(conj (str "PRIMARY KEY (" (str/join ", " (map (fn [x] (str "\"" (name x) "\"")) primary-key)) ")")))))


(defmethod ql/to-sql
:pg/create-table
[acc opts {:keys [foreign unlogged table-name columns server partition-by
constraint
partition-of for options] not-ex :if-not-exists :as node}]
(-> acc
(conj "CREATE")
Expand All @@ -1149,8 +1158,11 @@
(conj "TABLE")
(cond-> not-ex (conj "IF NOT EXISTS"))
(identifier opts table-name)
(cond-> columns (conj (str "( " (mk-columns opts columns) " )")))
(cond-> partition-of (conj "partition of" (name partition-of)))
(cond-> columns (conj "(" (mk-columns opts columns)))
(cond-> constraint (conj "," (mk-table-constraint constraint)))
(cond-> columns (conj ")"))

(cond-> partition-of (conj "partition of" (name partition-of) ))
(cond-> for (conj "for values"
(when-let [f (:from for)] (str "from (" f ")"))
(when-let [t (:to for)] (str "to (" t ")"))))
Expand Down
12 changes: 11 additions & 1 deletion test/dsql/pg_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,16 @@
:columns {:a {:type "integer" }}}
["CREATE TABLE \"MyTable\" ( \"a\" integer )"])

(format=
{:ql/type :pg/create-table
:table-name "mytable"
:columns {:id {:type "uuid"}
:partition {:type "int"}
:resource {:type "jsonb"}}
:constraint {:primary-key [:id :partition]}}

["CREATE TABLE mytable ( \"id\" uuid , \"partition\" int , \"resource\" jsonb , PRIMARY KEY (\"id\", \"partition\") )"]))

(format=
{:ql/type :pg/create-table
:table-name "mytable"
Expand Down Expand Up @@ -672,7 +682,7 @@
:partition-by {:method :range :expr :partition}
:partition-of "whole"
:for {:from 0 :to 400}}
["CREATE TABLE IF NOT EXISTS part partition of whole for values from (0) to (400) partition by range ( partition )"])))
["CREATE TABLE IF NOT EXISTS part partition of whole for values from (0) to (400) partition by range ( partition )"]))

(format=
{:ql/type :pg/drop-table
Expand Down

0 comments on commit 22cb4b1

Please sign in to comment.