-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_query_builder.clj
More file actions
91 lines (80 loc) · 2.43 KB
/
sql_query_builder.clj
File metadata and controls
91 lines (80 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
(defn busca_tabela [table]
(fn
([] (str "SELECT * FROM " table))
([filters] (str "SELECT * FROM " table " WHERE " filters))
([fields filters] (str "SELECT " fields " FROM " table " WHERE " filters))
)
)
(defn aux_juntar_campos [acc field]
(if (empty? acc)
(str field)
(str acc ", " field)
)
)
(defn campos [fields]
(reduce aux_juntar_campos fields)
)
(defn formatar_valor [v]
(cond
(string? v) (str "\"" v "\"")
(true? v) "true"
(false? v) "false"
:else (str v)
)
)
(defn aux_operador_sql [fv] ;; fv -> field_value
(cond
(:igual_a fv) (str " = " (formatar_valor (:igual_a fv)) )
(:diferente_de fv) (str " <> " (formatar_valor (:diferente_de fv)) )
(:maior_que fv) (str " > " (formatar_valor (:maior_que fv)) )
(:menor_que fv) (str " < " (formatar_valor (:menor_que fv)) )
(:em fv) (str " IN (" (reduce aux_juntar_campos "" (map formatar_valor (:em fv)))")")
:else (str " = " (formatar_valor (:valor fv)))
)
)
(defn aux_juntar_campo_valor [fv] ;; fv -> field_value
(str (:campo fv) (aux_operador_sql fv))
)
(defn filtros [filters]
(if (string? filters) filters (aux_juntar_campo_valor filters))
)
(defn aux_adiciona_and [acc fv] ;; fv -> field_value
(if (empty? acc)
(aux_juntar_campo_valor fv)
(if (string? fv)
(str acc " AND " fv) ;; recebeu uma string com ORs
(str acc " AND " (aux_juntar_campo_valor fv))
)
)
)
(def e_s (partial reduce aux_adiciona_and ""))
(defn aux_adiciona_or [acc fv] ;; fv -> field_value
(if (empty? acc)
(aux_juntar_campo_valor fv)
(if (string? fv)
(str acc ") OR (" fv) ;; recebeu uma string com ANDs
(str acc " OR " (aux_juntar_campo_valor fv))
)
)
)
(defn ou_s [filters]
(str "(" (reduce aux_adiciona_or "" filters) ")")
)
(println
(
(busca_tabela "usuario")
(campos ["abc", "xyz"])
(filtros
(e_s [
{:campo "nome", :igual_a "José"},
{:campo "idade", :maior_que 20},
{:campo "id", :em [10, 20, 30]},
{:campo "status", :igual_a true},
(ou_s [
{:campo "camiseta", :valor "verde"},
{:campo "camiseta", :valor "azul"},
])
])
)
)
)