diff --git a/src/dsql/pg.clj b/src/dsql/pg.clj index 6d94696..098d468 100644 --- a/src/dsql/pg.clj +++ b/src/dsql/pg.clj @@ -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") @@ -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 ")")))) diff --git a/test/dsql/pg_test.clj b/test/dsql/pg_test.clj index 9a02ec9..101823d 100644 --- a/test/dsql/pg_test.clj +++ b/test/dsql/pg_test.clj @@ -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" @@ -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