Support for RETURNING keyword

This commit is contained in:
Erik Price 2015-01-08 20:57:14 -05:00
parent 0c3f3d0403
commit 403fb33fc4
4 changed files with 30 additions and 2 deletions

View file

@ -49,7 +49,8 @@
:query-values
:update
:set
:delete-from"
:delete-from
:returning"
[& clauses]
(let [[base clauses] (if (map? (first clauses))
[(first clauses) (rest clauses)]

View file

@ -158,7 +158,7 @@
"Determines the order that clauses will be placed within generated SQL"
[:select :insert-into :update :delete-from :columns :set :from :join
:left-join :right-join :where :group-by :having :order-by :limit :offset
:values :query-values])
:values :query-values :returning])
(def known-clauses (set clause-order))
@ -359,6 +359,9 @@
(defmethod format-clause :offset [[_ offset] _]
(str "OFFSET " (to-sql offset)))
(defmethod format-clause :returning [[_ returning] _]
(str "RETURNING " (comma-join (map to-sql returning))))
(defmethod format-clause :insert-into [[_ table] _]
(str "INSERT INTO " (to-sql table)))

View file

@ -37,6 +37,14 @@
(defhelper merge-from [m tables]
(update-in m [:from] concat (collify tables)))
(defmethod build-clause :returning [_ m columns]
(if (empty? columns)
m
(assoc m :returning columns)))
(defhelper returning [m columns]
(assoc m :returning (collify columns)))
(defmethod build-clause :where [_ m pred]
(if (nil? pred)
m

View file

@ -6,6 +6,22 @@
;; TODO: more tests
(deftest test-insert
(let [m1 (-> (insert-into :t)
(columns :column_one :column_two)
(values [["one"] ["two"]])
(returning :column_one :column_two))
m2 {:insert-into :t
:columns [:column_one :column_two]
:values [["one"] ["two"]]
:returning [:column_one :column_two]}
m3 (sql/build m2)]
(testing "Various construction methods are consistent"
(is (= m1 m3)))
(testing "SQL data formats correctly"
(is (= (sql/format m1)
["INSERT INTO t (column_one, column_two) VALUES (?), (?) RETURNING column_one, column_two" "one" "two"])))))
(deftest test-select
(let [m1 (-> (select :f.* :b.baz :c.quux [:b.bla :bla-bla]
:%now (sql/raw "@x := 10"))