From 7831ebed3898e3c30d6e3d18b4b6f906b2b685ce Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 7 Sep 2019 13:24:46 -0700 Subject: [PATCH] Fixes #128 by adding :truncate / truncate --- CHANGES.md | 1 + README.md | 8 ++++++++ src/honeysql/format.cljc | 4 ++++ src/honeysql/helpers.cljc | 7 +++++++ test/honeysql/format_test.cljc | 5 +++++ 5 files changed, 25 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 349c73f..48bea9a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ ## Changes coming in 0.9.7 * Fix #248 by treating alias as "not a subquery" when generating SQL for it. (@seancorfield) +* Fix #128 by adding `truncate` support. * Fix #99 by adding a note to the first use of `select` in the README that column names can be keywords or symbols but not strings. ## 0.9.6 diff --git a/README.md b/README.md index 0abd54b..a499771 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,14 @@ If your database supports it, you can also delete from multiple tables: "musical"] ``` +If you want to delete everything from a table, you can use `truncate`: + +```clojure +(-> (truncate :films) + sql/format) +=> ["TRUNCATE films"] +``` + Queries can be nested: ```clojure diff --git a/src/honeysql/format.cljc b/src/honeysql/format.cljc index 338ab6c..5e5dcbf 100644 --- a/src/honeysql/format.cljc +++ b/src/honeysql/format.cljc @@ -219,6 +219,7 @@ :update 70 :delete 75 :delete-from 80 + :truncate 85 :columns 90 :from 110 :join 120 @@ -629,6 +630,9 @@ (defmethod format-clause :delete [[_ tables] _] (str "DELETE " (comma-join (map to-sql tables)))) +(defmethod format-clause :truncate [[_ table] _] + (str "TRUNCATE " (to-sql table))) + (defn cte->sql [[cte-name query]] (str (binding [*subquery?* false] diff --git a/src/honeysql/helpers.cljc b/src/honeysql/helpers.cljc index 6d4149c..d177e68 100644 --- a/src/honeysql/helpers.cljc +++ b/src/honeysql/helpers.cljc @@ -279,6 +279,13 @@ ([tables] (delete nil tables)) ([m tables] (build-clause :delete m tables))) +(defmethod build-clause :truncate [_ m table] + (assoc m :truncate table)) + +(defn truncate + ([table] (truncate nil table)) + ([m table] (build-clause :truncate m table))) + (macros/usetime (defhelper with [m ctes] (assoc m :with ctes))) diff --git a/test/honeysql/format_test.cljc b/test/honeysql/format_test.cljc index 480fd8b..09459e7 100644 --- a/test/honeysql/format_test.cljc +++ b/test/honeysql/format_test.cljc @@ -228,6 +228,11 @@ :where [:= :t1.bar 42]} (format :quoting :mysql))))) +(deftest truncate-test + (is (= ["TRUNCATE `foo`"] + (-> {:truncate :foo} + (format :quoting :mysql))))) + (deftest inlined-values-are-stringified-correctly (is (= ["SELECT foo, bar, NULL"] (format {:select [(honeysql.core/inline "foo")