From f4137d3fc1ecb57ddb95e7bac911aa75b97b9756 Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sun, 14 Feb 2021 20:39:32 -0800 Subject: [PATCH] Enhance insert-into; document more helpers --- src/honey/sql/helpers.cljc | 31 +++++++++++++++++++++++++++++-- test/honey/sql/helpers_test.cljc | 6 ++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/honey/sql/helpers.cljc b/src/honey/sql/helpers.cljc index d23c01a..ae719fd 100644 --- a/src/honey/sql/helpers.cljc +++ b/src/honey/sql/helpers.cljc @@ -277,18 +277,45 @@ (generic :select-distinct-on args)) (defn insert-into + "Accepts a table name or a table/alias pair. That + can optionally be followed by a collection of + column names. That can optionally be followed by + a (select) statement clause. + + (insert-into :table) + (insert-into [:table :t]) + (insert-into :table [:id :name :cost]) + (insert-into :table (-> (select :*) (from :other))) + (insert-into [:table :t] + [:id :name :cost] + (-> (select :*) (from :other)))" + {:arglists '([table] [table cols] [table statement] [table cols statement])} [& args] - (generic :insert-into args)) + (let [[table cols statement] args] + (if (and (sequential? cols) (map? statement)) + (generic :insert-into [[table cols] statement]) + (generic :insert-into args)))) (defn update + "Accepts either a table name or a table/alias pair. + + (-> (update :table) (set {:id 1 :cost 32.1}))" [& args] - (generic :update args)) + (generic-1 :update args)) (defn delete + "For deleting from multiple tables. + Accepts a collection of table names to delete from. + + (-> (delete [:films :directors]) (where [:= :id 1]))" [& args] (generic-1 :delete args)) (defn delete-from + "For deleting from a single table. + Accepts a single table name to delete from. + + (-> (delete-from :films) (where [:= :id 1]))" [& args] (generic :delete-from args)) diff --git a/test/honey/sql/helpers_test.cljc b/test/honey/sql/helpers_test.cljc index b1063d5..35274e7 100644 --- a/test/honey/sql/helpers_test.cljc +++ b/test/honey/sql/helpers_test.cljc @@ -473,4 +473,10 @@ ["INSERT INTO transport (id, name) SELECT * FROM cars"])) ;; with an alias and columns: (is (= (sql/format (insert-into ['(transport t) '(id, name)] '{select (*) from (cars)})) + ["INSERT INTO transport AS t (id, name) SELECT * FROM cars"])) + ;; three arguments with columns: + (is (= (sql/format (insert-into :transport [:id :name] '{select (*) from (cars)})) + ["INSERT INTO transport (id, name) SELECT * FROM cars"])) + ;; three arguments with an alias and columns: + (is (= (sql/format (insert-into '(transport t) '(id, name) '{select (*) from (cars)})) ["INSERT INTO transport AS t (id, name) SELECT * FROM cars"])))