From 6b070df52c1707d420d06854a7cc1c0f0fc6159f Mon Sep 17 00:00:00 2001 From: Sean Corfield Date: Sat, 13 Mar 2021 12:10:42 -0800 Subject: [PATCH] Finish off TOP implementation #292 --- doc/clause-reference.md | 2 ++ src/honey/sql.cljc | 4 +++- test/honey/sql/helpers_test.cljc | 15 ++++++++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/doc/clause-reference.md b/doc/clause-reference.md index 0459e21..21a0458 100644 --- a/doc/clause-reference.md +++ b/doc/clause-reference.md @@ -232,6 +232,8 @@ user=> (sql/format {:select [:id, [[:* :cost 2] :total], [:event :status]] HoneySQL does not yet support `SELECT .. INTO ..` or `SELECT .. BULK COLLECT INTO ..`. +## select-top, select-distinct-top + ## select-distinct-on Similar to `:select-distinct` above but the first element diff --git a/src/honey/sql.cljc b/src/honey/sql.cljc index 18a9f2f..a193595 100644 --- a/src/honey/sql.cljc +++ b/src/honey/sql.cljc @@ -330,7 +330,9 @@ (format-expr top) [sql' & params'] (format-selects-common - (str (sql-kw k) " " sql (str/join " " (map sql-kw parts))) + (str (sql-kw k) "(" sql ")" + (when (seq parts) " ") + (str/join " " (map sql-kw parts))) true cols)] (-> [sql'] (into params) (into params')))) diff --git a/test/honey/sql/helpers_test.cljc b/test/honey/sql/helpers_test.cljc index 583e7ce..c8e322f 100644 --- a/test/honey/sql/helpers_test.cljc +++ b/test/honey/sql/helpers_test.cljc @@ -80,7 +80,20 @@ :dialect :mysql :quoted false})))))) (deftest select-top-tests - (is true)) + (testing "Basic TOP syntax" + (is (= ["SELECT TOP(?) foo FROM bar ORDER BY quux ASC" 10] + (sql/format {:select-top [10 :foo] :from :bar :order-by [:quux]}))) + (is (= ["SELECT TOP(?) foo FROM bar ORDER BY quux ASC" 10] + (sql/format (-> (select-top 10 :foo) + (from :bar) + (order-by :quux)))))) + (testing "Expanded TOP syntax" + (is (= ["SELECT TOP(?) PERCENT WITH TIES foo, baz FROM bar ORDER BY quux ASC" 10] + (sql/format {:select-top [[10 :percent :with-ties] :foo :baz] :from :bar :order-by [:quux]}))) + (is (= ["SELECT TOP(?) PERCENT WITH TIES foo, baz FROM bar ORDER BY quux ASC" 10] + (sql/format (-> (select-top [10 :percent :with-ties] :foo :baz) + (from :bar) + (order-by :quux))))))) (deftest join-by-test (testing "Natural JOIN orders"