Commits

Anonymous committed 7bf321e

add merge-key-with-clause function and unit tests

Comments (0)

Files changed (3)

src/main/clj/org/bituf/sqlrat/clause.clj

     (as-clause (into [qexpr] qparm))))
 
 
+(defn merge-key-with-clause
+  "Merge a clause-key with clause.
+   Example: (merge-key-with-clause :where (as-clause [\"id = ?\" 45]))
+            >> [\"WHERE id=?\" 45]
+   Example: (merge-key-with-clause :group-by (cscols [:qty :cost]))
+            >> [\"GROUP BY qty, cost\"]"
+  [^Keyword k ^Vector clause]
+  (assert (clause? clause))
+  (merge-clauses (str-clause-key k) clause))
+
+
 ;; short hand functions for merging clauses
 
 (defn prefix "Prefix to clause" [clause token] (merge-clauses token clause))

src/main/clj/org/bituf/sqlrat/clause/internal.clj

 (ns org.bituf.sqlrat.clause.internal)
 
-(defn bad-arg#
-  [reason & more]
-  (throw (IllegalArgumentException. (apply str reason more))))
 
-(defn str-col [k] (if (keyword? k) (name k) k))
+;; ======== Keyword to String conversion ========
+
+(defn str-col
+  "Convert keyword/anything to a string (colname)."
+  [k]
+  (if (keyword? k) (name k)
+    (str k)))
+
+(defn str-clause-key
+  "Convert a clause keyword to string.
+   :where becomes \" WHERE \"
+   :group-by becomes \" GROUP BY \"
+   and so on."
+  [^Keyword clause-key]
+  (assert (keyword? clause-key))
+  (.toUpperCase
+    (.replace
+      (str \  (name clause-key) \  )
+      \- \  )))
 
 
 ;; ======== Clause metadata ========

src/test/clj/org/bituf/sqlrat/test/clause.clj

       (is (= cc (merge-clauses c1 c2))))))
 
 
+(deftest test-merge-key-with-clause
+  (testing "Merge WHERE clause"
+    (let [c (=? :id 45)]
+      (is (= [" WHERE id=?" 45]
+            (merge-key-with-clause :where c)))))
+  (testing "Merge GROUP BY clause"
+    (let [c (cscols [:qty :cost])]
+      (is (= [" GROUP BY qty, cost"]
+            (merge-key-with-clause :group-by c))))))
+
+
 (deftest test-op2-with-value
   (let [k :id
         v 34
   (test-as-clause)
   (test-clause?-and-assert-clause)
   (test-merge-clauses)
+  (test-merge-key-with-clause)
   (test-op2-with-value)
   (test-op2-with-subquery)
   (test-multi-op)