From 68c206aab2ddac42bef6de97fd065f75edcb1a98 Mon Sep 17 00:00:00 2001
From: Carlo Zancanaro <carlo@clearboxsystems.com.au>
Date: Sun, 23 Jun 2013 02:57:21 +1000
Subject: Make sort and group create subqueries to be correct

---
 src/clojure_sql/dsl.clj | 26 ++++++++++++++++++++------
 1 file changed, 20 insertions(+), 6 deletions(-)

diff --git a/src/clojure_sql/dsl.clj b/src/clojure_sql/dsl.clj
index 0053cbb..6d9b413 100644
--- a/src/clojure_sql/dsl.clj
+++ b/src/clojure_sql/dsl.clj
@@ -273,7 +273,7 @@
   Example:
     (select query `(= :id 10)) - filter for an id of 10
     (select query {:id 10}) - equivalent to the above
-    (select query `(in :id '(1 2 3)) - filter for an id of 1, 2 or 3 "
+    (select query `(in :id '(1 2 3)) - filter for an id of 1, 2 or 3"
   [query expression]
   (let [table-name (if (= (count (:tables query)) 1)
                      (-> query :tables first key))
@@ -288,13 +288,21 @@
     (assoc query :where new-where)))
 
 (defn sort
-  "Apply a sort to a query.
+  "Apply a sort to a query. Replaces any existing sort on the
+  query (ie. is not stable) .
 
   `fields` is a sequential collection of fields to sort by. Each
   element of fields can be either a field name, :field, or a vector of
-  field and direction, [:field :desc]."
+  field and direction, [:field :desc].
+
+  If a `take` or `drop` has already been applied to this query then
+  the sort will be applied *after* the `take`/`drop` (which results in
+  a subquery being created)."
   [query fields]
-  (let [table-name (if (= (count (:tables query)) 1)
+  (let [query (if (or (:take query) (:drop query))
+                (convert-to-subquery query)
+                query)
+        table-name (if (= (count (:tables query)) 1)
                      (-> query :tables first key))
         fields-seq (if (sequential? fields)
                      fields
@@ -309,9 +317,15 @@
 (defn group
   "Apply a grouping to a query.
 
-  `fields` is a sequential collection of fields to group by."
+  `fields` is a sequential collection of fields to group by.
+
+  If the query has already been grouped then this will create a
+  subquery."
   [query fields]
-  (let [table-name (if (= (count (:tables query)) 1)
+  (let [query (if (:group query)
+                (convert-to-subquery query)
+                query)
+        table-name (if (= (count (:tables query)) 1)
                      (-> query :tables first key))
         fields-seq (if (sequential? fields)
                      fields
-- 
cgit v1.2.3