From 9cf71871f3768bfd7f7b9912cc13a3e5c275a626 Mon Sep 17 00:00:00 2001 From: Niels van Klaveren Date: Tue, 19 Aug 2014 11:11:09 +0200 Subject: [PATCH] Added OVER (PARTITION BY) clause Supports windowed aggregate functions as fields {:aggregate :%fn.field :over {:partition-by [:field]}} --- src/honeysql/format.clj | 15 ++++++++++++++- src/honeysql/helpers.clj | 25 ++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/honeysql/format.clj b/src/honeysql/format.clj index b42b020..db587a3 100644 --- a/src/honeysql/format.clj +++ b/src/honeysql/format.clj @@ -183,6 +183,9 @@ :right-join 140 :full-join 150 :where 160 + :aggregate 162 + :over 165 + :partition 167 :group-by 170 :having 180 :order-by 190 @@ -455,7 +458,17 @@ (defmethod format-clause :delete-from [[_ table] _] (str "DELETE FROM " (to-sql table))) - + +(defmethod format-clause :over [[_ part-clause] _] + (str "OVER " (to-sql part-clause))) + +(defmethod format-clause :aggregate [[_ aggregate-fn] _] + (str (to-sql aggregate-fn))) + +(defmethod format-clause :partition-by [[_ fields] _] + (str "PARTITION BY " + (comma-join (map to-sql fields)))) + (defn cte->sql [[cte-name query]] (str (to-sql cte-name) " AS " (to-sql query))) diff --git a/src/honeysql/helpers.clj b/src/honeysql/helpers.clj index e94eae6..8c12d7a 100644 --- a/src/honeysql/helpers.clj +++ b/src/honeysql/helpers.clj @@ -219,7 +219,30 @@ (defn delete-from ([table] (delete-from nil table)) ([m table] (build-clause :delete-from m table))) - + +(defmethod build-clause :over [_ m table] + (assoc m :over table)) + +(defn over + ([part-clause] (over nil part-clause)) + ([m part-clause] (build-clause :over m part-clause))) + +(defhelper merge-over [m fields] + (update-in m [:over] (partial apply merge) (collify fields))) + +(defhelper aggregate [m aggregate-fn] + (assoc m :aggregate aggregate-fn)) + +(defn aggregate + ([table] (aggregate nil table)) + ([m table] (build-clause :aggregate m table))) + +(defhelper spartition-by [m fields] + (assoc m :partition-by (collify fields))) + +(defhelper merge-partition-by [m fields] + (update-in m [:partition-by] concat (collify fields))) + (defmethod build-clause :with [_ m ctes] (assoc m :with ctes))