Public Vars

Back

select-top (clj)

(source)

function

(select-top & args)
Accepts a TOP expression, followed by any number of column names, or column/alias pairs, or SQL expressions (optionally aliased), as for `select`. The TOP expression can be a simple numeric expression, or a sequence with a numeric expression followed by keywords (or symbols) for PERCENT and/or WITH TIES.

Examples

honeysql
(ns honey.sql.helpers-test
  (:refer-clojure :exclude [filter for group-by partition-by set update])
  (:require [clojure.test :refer [deftest is testing]]
            [honey.sql :as sql]
            [honey.sql.helpers :as h
             :refer [add-column add-index alter-table columns create-table create-table-as create-view
                     create-materialized-view drop-view drop-materialized-view
                     create-index
                     bulk-collect-into
                     cross-join do-update-set drop-column drop-index drop-table
                     filter from full-join
                     group-by having insert-into
                     join-by join lateral left-join limit offset on-conflict
                     on-duplicate-key-update
                     order-by over partition-by refresh-materialized-view
                     rename-column rename-table returning right-join
                     select select-distinct select-top select-distinct-top
                     values where window with with-columns
                     with-data within-group]]))

(deftest select-top-tests
  (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)))))))