Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose a Clojure Query with embedded double quotes

I want to compose a Clojure query, so that the lnam and fnam parameters in the where clause are double-quoted. I need them double-quoted, because embedded names contain single quote characters, like "O'BRIEN".

I have been looking at examples for both Clojure queries and embedding double quotes in strings, but am not finding examples of what I want.

This works fine in lein repl

gic-cmp.core=> (def lnam "O'BRIEN")
#'gic-cmp.core/lnam
gic-cmp.core=> (str """"lnam"""")
"O'BRIEN"

But this won't produce a quoted string in the query below.

(defn match-this-rec-with-last
    ""
    [gic-id lnam fnam search-date]
    (let [query (str (str "select g.* from gic_employees g where g.processed_date = '" search-date "' ")
                          (str "and g.gic_id = '" gic-id "' and g.last_name = ")
                          """"lnam""""
                          (str " and g.first_name = ")
                          (str """"fnam"""")
                          (str " order by g.processed_date desc "))]
      (println query)
      (j/query db
            [query])))
like image 850
octopusgrabbus Avatar asked Aug 19 '14 12:08

octopusgrabbus


2 Answers

The REPL displays the return value of the str function with quotes around it.

(str """"lnam"""")

this returns 2 empty strings, lnam, and 2 more empty strings all with quotes around it.

The underlying string is a java.lang.String and the standard java way to include double quotes within a string is to escape it with a backslash.

user=> (str "test with \"quoted\" value")
"test with \"quoted\" value"
user=> (println (str "test with \"quoted\" value"))
test with "quoted" value
like image 144
GregA100k Avatar answered Sep 22 '22 19:09

GregA100k


Use ? for query params, jdbc will escape them properly:

(defn match-this-rec-with-last
  ""
  [gic-id lnam fnam search-date]
  (let [query [(clojure.string/join " " ["select g.* from gic_employees g where g.processed_date = ?"
                                          "AND g.gic_id = ? and g.last_name = ?"
                                          "AND g.first_name = ?"
                                          "ORDER BY g.processed_date desc"])
               ;; values
               search-date gic-id lnam fnam]]
    (println query)
    (j/query db
             query)))
like image 39
edbond Avatar answered Sep 23 '22 19:09

edbond