forked from seancorfield/honeysql
/
sql.cljc
1699 lines (1553 loc) · 67.8 KB
/
sql.cljc
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; copyright (c) 2020-2022 sean corfield, all rights reserved
(ns honey.sql
"Primary API for HoneySQL 2.x.
This includes the `format` function -- the primary entry point -- as well
as several public formatters that are intended to help users extend the
supported syntax.
In addition, functions to extend HoneySQL are also provided here:
* `clause-order` -- returns the current clause priority ordering;
intended as aid when registering new clauses.
* `format-dsl` -- intended to format SQL statements; returns a vector
containing a SQL string followed by parameter values.
* `format-entity` -- intended to format SQL entities; returns a string
representing the SQL entity.
* `format-expr` -- intended to format SQL expressions; returns a vector
containing a SQL string followed by parameter values.
* `format-expr-list` -- intended to format a list of SQL expressions;
returns a pair comprising: a sequence of SQL expressions (to be
join with a delimiter) and a sequence of parameter values.
* `register-clause!` -- register a new statement/clause formatter.
* `register-fn!` -- register a new function call (or special syntax)
formatter.
* `register-op!` -- register a new operator formatter.
* `set-dialect!` -- set the default dialect to be used for formatting,
and optionally set a global `:quoted` option.
* `sql-kw` -- turns a Clojure keyword (or symbol) into SQL code (makes
it uppercase and replaces - with space). "
(:refer-clojure :exclude [format])
(:require [clojure.string :as str]))
;; default formatting for known clauses
(declare format-dsl)
(declare format-expr)
(declare format-expr-list)
;; dynamic dialect handling for formatting
(declare clause-format)
(def ^:private default-clause-order
"The (default) order for known clauses. Can have items added and removed."
[;; DDL comes first (these don't really have a precedence):
:alter-table :add-column :drop-column :modify-column :rename-column
:add-index :drop-index :rename-table
:create-table :create-table-as :with-columns
:create-view :create-materialized-view :create-extension
:drop-table :drop-view :drop-materialized-view :drop-extension
:refresh-materialized-view
;; then SQL clauses in priority order:
:raw :nest :with :with-recursive :intersect :union :union-all :except :except-all
:table
:select :select-distinct :select-distinct-on :select-top :select-distinct-top
:into :bulk-collect-into
:insert-into :update :delete :delete-from :truncate
:columns :set :from :using
:join-by
:join :left-join :right-join :inner-join :outer-join :full-join
:cross-join
:where :group-by :having
:window :partition-by
:order-by :limit :offset :fetch :for :lock :values
:on-conflict :on-constraint :do-nothing :do-update-set :on-duplicate-key-update
:returning
:with-data])
(defn add-clause-before
"Low-level helper just to insert a new clause.
If the clause is already in the list, this moves it to the end."
[order clause before]
(let [clauses (set order)
order (if (contains? clauses clause)
(filterv #(not= % clause) order)
order)]
(if before
(do
(when-not (contains? clauses before)
(throw (ex-info (str "Unrecognized clause: " before)
{:known-clauses order})))
(reduce (fn [v k]
(if (= k before)
(conj v clause k)
(conj v k)))
[]
order))
(conj order clause))))
(defn strop
"Escape any embedded closing strop characters."
[s x e]
(str s (str/replace x (str e) (str e e)) e))
(def ^:private dialects
(atom
(reduce-kv (fn [m k v]
(assoc m k (assoc v :dialect k)))
{}
{:ansi {:quote #(strop \" % \")}
:sqlserver {:quote #(strop \[ % \])}
:mysql {:quote #(strop \` % \`)
:clause-order-fn #(add-clause-before % :set :where)}
:oracle {:quote #(strop \" % \") :as false}})))
; should become defonce
(def ^:private default-dialect (atom (:ansi @dialects)))
(def ^:private default-quoted (atom nil))
(def ^:private ^:dynamic *dialect* nil)
;; nil would be a better default but that makes testing individual
;; functions harder than necessary:
(def ^:private ^:dynamic *clause-order* default-clause-order)
(def ^:private ^:dynamic *quoted* nil)
(def ^:private ^:dynamic *quoted-snake* nil)
(def ^:private ^:dynamic *inline* nil)
(def ^:private ^:dynamic *params* nil)
(def ^:private ^:dynamic *values-default-columns* nil)
;; there is no way, currently, to enable suspicious characters
;; in entities; if someone complains about this check, an option
;; can be added to format to turn this on:
(def ^:private ^:dynamic *allow-suspicious-entities* false)
;; "linting" mode (:none, :basic, :strict):
(def ^:private ^:dynamic *checking* :none)
;; the current DSL hash map being formatted (for contains-clause?):
(def ^:private ^:dynamic *dsl* nil)
;; caching data to detect expressions that cannot be cached:
(def ^:private ^:dynamic *caching* nil)
;; clause helpers
(defn contains-clause?
"Returns true if the current DSL expression being formatted
contains the specified clause (as a keyword or symbol)."
[clause]
(or (contains? *dsl* clause)
(contains? *dsl*
(if (keyword? clause)
(symbol (name clause))
(keyword (name clause))))))
(defn- mysql?
"Helper to detect if MySQL is the current dialect."
[]
(= :mysql (:dialect *dialect*)))
(defn- sql-server?
"Helper to detect if SQL Server is the current dialect."
[]
(= :sqlserver (:dialect *dialect*)))
;; String.toUpperCase() or `str/upper-case` for that matter converts the
;; string to uppercase for the DEFAULT LOCALE. Normally this does what you'd
;; expect but things like `inner join` get converted to `İNNER JOİN` (dot over
;; the I) when user locale is Turkish. This predictably has bad consequences
;; for people who like their SQL queries to work. The fix here is to use
;; String.toUpperCase(Locale/US) instead which always converts things the
;; way we'd expect.
;;
;; Use this instead of `str/upper-case` as it will always use Locale/US.
#?(:clj
(defn upper-case
"Upper-case a string in Locale/US to avoid locale-specific capitalization."
[^String s]
(.. s toString (toUpperCase (java.util.Locale/US))))
;; TODO - not sure if there's a JavaScript equivalent here we should be using as well
:cljs
(defn upper-case
"In ClojureScript, just an alias for cljs.string/upper-case."
[s]
(str/upper-case s)))
(defn- dehyphen
"Replace _embedded_ hyphens with spaces.
Hyphens at the start or end of a string should not be touched."
[s]
(str/replace s #"(\w)-(?=\w)" "$1 "))
(defn- namespace-_
"Return the namespace portion of a symbol, with dashes converted."
[x]
(try
(some-> (namespace x) (str/replace "-" "_"))
(catch #?(:clj Throwable :cljs :default) t
(throw (ex-info (str "expected symbol, found: "
(type x))
{:symbol x
:failure (str t)})))))
(defn- name-_
"Return the name portion of a symbol, with dashes converted."
[x]
(try
(str/replace (name x) "-" "_")
(catch #?(:clj Throwable :cljs :default) t
(throw (ex-info (str "expected symbol, found: "
(type x))
{:symbol x
:failure (str t)})))))
(defn format-entity
"Given a simple SQL entity (a keyword or symbol -- or string),
return the equivalent SQL fragment (as a string -- no parameters).
Handles quoting, splitting at / or ., replacing - with _ etc."
[e & [{:keys [aliased drop-ns]}]]
(let [col-fn (if (or *quoted* (string? e))
(if *quoted-snake* name-_ name)
name-_)
quote-fn (if (or *quoted* (string? e)) (:quote *dialect*) identity)
parts (if-let [n (when-not (or drop-ns (string? e))
(namespace-_ e))]
[n (col-fn e)]
(if aliased
[(col-fn e)]
(str/split (col-fn e) #"\.")))
entity (str/join "." (map #(cond-> % (not= "*" %) (quote-fn)) parts))
suspicious #";"]
(when-not *allow-suspicious-entities*
(when (re-find suspicious entity)
(throw (ex-info (str "suspicious character found in entity: " entity)
{:disallowed suspicious}))))
entity))
(comment
(for [v [:foo-bar "foo-bar" ; symbol is the same as keyword
:f-o.b-r :f-o/b-r]
a [true false] d [true false] q [true false]]
(binding [*dialect* (:mysql @dialects) *quoted* q]
(if q
[v a d (format-entity v {:aliased a :drop-ns d})
(binding [*quoted-snake* true]
(format-entity v {:aliased a :drop-ns d}))]
[v a d (format-entity v {:aliased a :drop-ns d})])))
)
(defn sql-kw
"Given a keyword, return a SQL representation of it as a string.
A keyword whose name begins with a single quote is left exactly as-is
(with the `:` and `'` removed), otherwise a `:kebab-case` keyword
becomes a `KEBAB CASE` (uppercase) string with hyphens replaced
by spaces, e.g., `:insert-into` => `INSERT INTO`.
Any namespace qualifier is ignored.
Any ? is escaped to ??."
[k]
(let [n (str/replace (name k) "?" "??")]
(if (= \' (first n))
(format-entity (keyword (subs n 1 (count n))))
(-> n (dehyphen) (upper-case)))))
(defn- sym->kw
"Given a symbol, produce a keyword, retaining the namespace
qualifier, if any."
[s]
(if (symbol? s)
(if-let [n (namespace s)]
(keyword n (name s))
(keyword (name s)))
s))
(defn- sqlize-value [x]
(cond
(nil? x) "NULL"
(string? x) (str \' (str/replace x "'" "''") \')
(ident? x) (sql-kw x)
(vector? x) (str "[" (str/join ", " (map #'sqlize-value x)) "]")
;; issue 385: quoted UUIDs for PostgreSQL/ANSI
#?(:clj (instance? java.util.UUID x) :cljs false)
(str \' x \') ; UUID cannot contain quotes
:else (str x)))
(defn- param-value [k]
(if (contains? *params* k)
(get *params* k)
(throw (ex-info (str "missing parameter value for " k)
{:params (keys *params*)}))))
(defn- ->param [k]
(with-meta (constantly k)
{::wrapper
(fn [fk _] (param-value (fk)))}))
(defn- format-var [x & [opts]]
;; rather than name/namespace, we want to allow
;; for multiple / in the %fun.call case so that
;; qualified column names can be used:
(let [c (cond-> (str x) (keyword? x) (subs 1))]
(cond (= \% (first c))
(let [[f & args] (str/split (subs c 1) #"\.")
quoted-args (map #(format-entity (keyword %) opts) args)]
[(str (upper-case (str/replace f "-" "_"))
"(" (str/join ", " quoted-args) ")")])
(= \? (first c))
(let [k (keyword (subs c 1))]
(if *inline*
[(sqlize-value (param-value k))]
["?" (->param k)]))
:else
[(format-entity x opts)])))
(defn- format-entity-alias [x]
(cond (sequential? x)
(let [s (first x)
pair? (< 1 (count x))]
(when (map? s)
(throw (ex-info "selectable cannot be statement!"
{:selectable s})))
(let [[sql & params] (format-expr s)]
(into [(cond-> sql
pair?
(str (if (and (contains? *dialect* :as) (not (:as *dialect*))) " " " AS ")
(format-entity (second x) {:aliased true})))]
params)))
:else
[(format-entity x)]))
(comment
(format-expr :a)
(format-expr [:raw "My String"])
(format-entity-alias [[:raw "My String"]])
)
(declare format-selects-common)
(defn- format-selectable-dsl [x & [{:keys [as aliased] :as opts}]]
(cond (map? x)
(format-dsl x {:nested true})
(sequential? x)
(let [s (first x)
a (second x)
pair? (= 2 (count x))
big? (and (ident? s) (or (= "*" (name s)) (str/ends-with? (name s) ".*"))
(ident? a) (#{"except" "replace"} (name a)))
more? (and (< 2 (count x)) (not big?))
[sql & params] (if (map? s)
(format-dsl s {:nested true})
(format-expr s))
[sql' & params'] (when (or pair? big?)
(cond (sequential? a)
(let [[sqls params] (format-expr-list a {:aliased true})]
(into [(str/join " " sqls)] params))
big? ; BigQuery support #281
(reduce (fn [[sql & params] [k arg]]
(let [[sql' params']
(cond (and (ident? k) (= "except" (name k)) arg)
(let [[sqls params]
(format-expr-list arg {:aliased true})]
[(str (sql-kw k) " (" (str/join ", " sqls) ")")
params])
(and (ident? k) (= "replace" (name k)) arg)
(let [[sql & params] (format-selects-common nil true arg)]
[(str (sql-kw k) " (" sql ")")
params])
:else
(throw (ex-info "bigquery * only supports except and replace"
{:clause k :arg arg})))]
(-> [(cond->> sql' sql (str sql " "))]
(into params)
(into params'))))
[]
(partition-all 2 (rest x)))
:else
(format-selectable-dsl a {:aliased true})))]
(-> [(cond pair?
(str sql
(if as
(if (and (contains? *dialect* :as)
(not (:as *dialect*)))
" "
" AS ")
" ") sql')
big?
(str sql " " sql')
more?
(throw (ex-info "illegal syntax in select expression"
{:symbol s :alias a :unexpected (nnext x)}))
:else
sql)]
(into params)
(into params')))
(ident? x)
(if aliased
[(format-entity x opts)]
(format-var x opts))
(and aliased (string? x))
[(format-entity x opts)]
:else
(format-expr x)))
(defn- reduce-sql [xs]
(reduce (fn [[sql params] [sql' & params']]
[(conj sql sql') (if params' (into params params') params)])
[[] []]
xs))
;; primary clauses
(defn- format-on-set-op [k xs]
(let [[sqls params] (reduce-sql (map #(format-dsl %) xs))]
(into [(str/join (str " " (sql-kw k) " ") sqls)] params)))
(defn format-expr-list
"Given a sequence of expressions represented as data, return a pair
where the first element is a sequence of SQL fragments and the second
element is a sequence of parameters. The caller should join the SQL
fragments with whatever appropriate delimiter is needed and then
return a vector whose first element is the complete SQL string and
whose subsequent elements are the parameters:
(let [[sqls params] (format-expr-list data opts)]
(into [(str/join delim sqls)] params))
This is intended to be used when writing your own formatters to
extend the DSL supported by HoneySQL."
[exprs & [opts]]
(when-not (sequential? exprs)
(throw (ex-info (str "format-expr-list expects a sequence of expressions, found: "
(type exprs))
{:exprs exprs})))
(reduce-sql (map #(format-expr % opts) exprs)))
(comment
(format-expr-list :?tags)
)
(defn- format-columns [k xs]
(let [[sqls params] (format-expr-list xs {:drop-ns (= :columns k)})]
(into [(str "(" (str/join ", " sqls) ")")] params)))
(defn- format-selects-common [prefix as xs]
(if (sequential? xs)
(let [[sqls params] (reduce-sql (map #(format-selectable-dsl % {:as as}) xs))]
(when-not (= :none *checking*)
(when (empty? xs)
(throw (ex-info (str prefix " empty column list is illegal")
{:clause (into [prefix] xs)}))))
(into [(str (when prefix (str prefix " ")) (str/join ", " sqls))] params))
(let [[sql & params] (format-selectable-dsl xs {:as as})]
(into [(str (when prefix (str prefix " ")) sql)] params))))
(defn- format-selects [k xs]
(format-selects-common
(sql-kw k)
(#{:select :select-distinct :from :window :delete-from
'select 'select-distinct 'from 'window 'delete-from}
k)
xs))
(defn- format-selects-on [_ xs]
(let [[on & cols] xs
[sql & params]
(format-expr (into [:distinct-on] on))
[sql' & params']
(format-selects-common
(str (sql-kw :select) " " sql)
true
cols)]
(-> [sql'] (into params) (into params'))))
(defn- format-select-top [k xs]
(let [[top & cols] xs
[top & parts]
(if (sequential? top)
;; could be an expression or a number followed by :percent :with-ties
(let [top-q? #(and (ident? %)
(#{:percent :with-ties} (sym->kw %)))
r-top (reverse top)
top-quals (take-while top-q? r-top)
top-list (drop-while top-q? r-top)]
(if (seq top-quals)
(if (= 1 (count top-list))
(into (vec top-list) (reverse top-quals))
(throw (ex-info "unparseable TOP expression"
{:top top})))
[top]))
[top])
[sql & params]
(format-expr top)
[sql' & params']
(format-selects-common
(str (sql-kw k) "(" sql ")"
(when (seq parts) " ")
(str/join " " (map sql-kw parts)))
true
cols)]
(-> [sql'] (into params) (into params'))))
(defn- format-select-into [k xs]
(let [[v e] (if (sequential? xs) xs [xs])
[sql & params] (when e (format-expr e))]
(into [(str (sql-kw k) " " (format-entity v)
(when sql
(str " "
(sql-kw (if (= :into k) :in :limit))
" "
sql)))]
params)))
(defn- format-with-part [x]
(if (sequential? x)
(let [[sql & params] (format-dsl (second x))]
(into [(str (format-entity (first x)) " " sql)] params))
[(format-entity x)]))
(defn- format-with [k xs]
;; TODO: a sequence of pairs -- X AS expr -- where X is either [entity expr]
;; or just entity, as far as I can tell...
(let [[sqls params]
(reduce-sql (map (fn [[x expr]]
(let [[sql & params] (format-with-part x)
[sql' & params'] (format-dsl expr)]
;; according to docs, CTE should _always_ be wrapped:
(cond-> [(str sql " AS " (str "(" sql' ")"))]
params (into params)
params' (into params'))))
xs))]
(into [(str (sql-kw k) " " (str/join ", " sqls))] params)))
(defn- format-selector [k xs]
(format-selects k [xs]))
(defn- format-insert [k table]
(if (sequential? table)
(cond (map? (second table))
(let [[table statement] table
[table cols]
(if (and (sequential? table) (sequential? (second table)))
table
[table])
[sql & params] (format-dsl statement)
[t-sql & t-params] (format-entity-alias table)
[c-sqls c-params] (reduce-sql (map #'format-entity-alias cols))]
(-> [(str (sql-kw k) " " t-sql
" "
(when (seq cols)
(str "("
(str/join ", " c-sqls)
") "))
sql)]
(into t-params)
(into c-params)
(into params)))
(sequential? (second table))
(let [[table cols] table
[t-sql & t-params] (format-entity-alias table)
[c-sqls c-params] (reduce-sql (map #'format-entity-alias cols))]
(-> [(str (sql-kw k) " " t-sql
" ("
(str/join ", " c-sqls)
")")]
(into t-params)
(into c-params)))
:else
(let [[sql & params] (format-entity-alias table)]
(into [(str (sql-kw k) " " sql)] params)))
(let [[sql & params] (format-entity-alias table)]
(into [(str (sql-kw k) " " sql)] params))))
(comment
(format-insert :insert-into [[[:raw ":foo"]] {:select :bar}])
)
(defn- format-join [k clauses]
(let [[sqls params]
(reduce (fn [[sqls params] [j e]]
(let [[sql-j & params-j]
(format-selects-common
(sql-kw (if (= :join k) :inner-join k))
true
[j])
sqls (conj sqls sql-j)]
(if (and (sequential? e) (= :using (first e)))
(let [[u-sqls u-params]
(reduce-sql (map #'format-entity-alias (rest e)))]
[(conj sqls
"USING"
(str "("
(str/join ", " u-sqls)
")"))
(-> params (into params-j) (into u-params))])
(let [[sql & params'] (when e (format-expr e))]
[(cond-> sqls e (conj "ON" sql))
(-> params
(into params-j)
(into params'))]))))
[[] []]
(partition-all 2 clauses))]
(into [(str/join " " sqls)] params)))
(def ^:private join-by-aliases
"Map of shorthand to longhand join names."
{:join :inner-join
:left :left-join
:right :right-join
:inner :inner-join
:outer :outer-join
:full :full-join
:cross :cross-join})
(def ^:private valid-joins
(set (vals join-by-aliases)))
(defn- format-join-by
"Clauses should be a sequence of join types followed
by their table and condition, or a sequence of join
clauses, so that you can construct a series of joins
in a specific order."
[_ clauses]
(let [joins (if (every? map? clauses)
(into []
(comp (mapcat #(mapcat (juxt key val) %))
(map vector))
clauses)
(partition-by ident? clauses))]
(when-not (even? (count joins))
(throw (ex-info ":join-by expects a sequence of join clauses"
{:clauses clauses})))
(let [[sqls params]
(reduce (fn [[sqls params] [[j] [clauses]]]
(let [j' (sym->kw j)
j' (sym->kw (join-by-aliases j' j'))]
(when-not (valid-joins j')
(throw (ex-info (str ":join-by found an invalid join type "
j)
{})))
(let [[sql' & params'] (format-dsl {j' clauses})]
[(conj sqls sql') (into params params')])))
[[] []]
(partition 2 joins))]
(into [(str/join " " sqls)] params))))
(defn- format-on-expr [k e]
(if (or (not (sequential? e)) (seq e))
(let [[sql & params] (format-expr e)]
(into [(str (sql-kw k) " " sql)] params))
[]))
(defn- format-group-by [k xs]
(let [[sqls params] (format-expr-list xs)]
(into [(str (sql-kw k) " " (str/join ", " sqls))] params)))
(defn- format-order-by [k xs]
(let [dirs (map #(when (sequential? %) (second %)) xs)
[sqls params]
(format-expr-list (map #(if (sequential? %) (first %) %) xs))]
(into [(str (sql-kw k) " "
(str/join ", " (map (fn [sql dir]
(str sql " " (sql-kw (or dir :asc))))
sqls
dirs)))] params)))
(defn- format-lock-strength [k xs]
(let [[strength tables nowait] (if (sequential? xs) xs [xs])]
[(str (sql-kw k) " " (sql-kw strength)
(when tables
(str
(cond (and (ident? tables)
(#{:nowait :skip-locked :wait} (sym->kw tables)))
(str " " (sql-kw tables))
(sequential? tables)
(str " OF "
(str/join ", " (map #'format-entity tables)))
:else
(str " OF " (format-entity tables)))
(when nowait
(str " " (sql-kw nowait))))))]))
(defn- format-values [k xs]
(cond (sequential? (first xs))
;; [[1 2 3] [4 5 6]]
(let [n-1 (map count xs)
;; issue #291: ensure all value sequences are the same length
xs' (if (apply = n-1)
xs
(let [n-n (apply max n-1)]
(map (fn [x] (take n-n (concat x (repeat nil)))) xs)))
[sqls params]
(reduce (fn [[sql params] [sqls' params']]
[(conj sql (str "(" (str/join ", " sqls') ")"))
(into params params')])
[[] []]
(map #'format-expr-list xs'))]
(into [(str (sql-kw k) " " (str/join ", " sqls))] params))
(map? (first xs))
;; [{:a 1 :b 2 :c 3}]
(let [cols-1 (keys (first xs))
;; issue #291: check for all keys in all maps but still
;; use the keys from the first map if they match so that
;; users can rely on the key ordering if they want to,
;; e.g., see test that uses array-map for the first row
cols-n (into #{} (mapcat keys) xs)
cols (if (= (set cols-1) cols-n) cols-1 cols-n)
[sqls params]
(reduce (fn [[sql params] [sqls' params']]
[(conj sql (str "(" (str/join ", " sqls') ")"))
(if params' (into params params') params')])
[[] []]
(map (fn [m]
(format-expr-list
(map #(get m
%
;; issue #366: use NULL or DEFAULT
;; for missing column values:
(if (contains? *values-default-columns* %)
[:default]
nil))
cols)))
xs))]
(into [(str "("
(str/join ", "
(map #(format-entity % {:drop-ns true}) cols))
") "
(sql-kw k)
" "
(str/join ", " sqls))]
params))
:else
(throw (ex-info ":values expects sequences or maps"
{:first (first xs)}))))
(comment
(into #{} (mapcat keys) [{:a 1 :b 2} {:b 3 :c 4}])
,)
(defn- format-set-exprs [k xs]
(let [[sqls params]
(reduce-kv (fn [[sql params] v e]
(let [[sql' & params'] (format-expr e)]
[(conj sql (str (format-entity v {:drop-ns (not (mysql?))}) " = " sql'))
(if params' (into params params') params)]))
[[] []]
xs)]
(into [(str (sql-kw k) " " (str/join ", " sqls))] params)))
(defn- format-on-conflict [k x]
(if (sequential? x)
(let [entities (take-while ident? x)
n (count entities)
[clause & more] (drop n x)
_ (when (or (seq more)
(and clause (not (map? clause))))
(throw (ex-info "unsupported :on-conflict format"
{:clause x})))
[sql & params] (when clause
(format-dsl clause))]
(into [(str (sql-kw k)
(when (pos? n)
(str " ("
(str/join ", " (map #'format-entity entities))
")"))
(when sql
(str " " sql)))]
params))
(format-on-conflict k [x])))
(defn- format-do-update-set [k x]
(cond (map? x)
(if (or (contains? x :fields) (contains? x 'fields))
(let [sets (str/join ", "
(map (fn [e]
(let [e (format-entity e {:drop-ns true})]
(str e " = EXCLUDED." e)))
(or (:fields x)
('fields x))))
where (or (:where x) ('where x))
[sql & params] (when where (format-dsl {:where where}))]
(into [(str (sql-kw k) " " sets
(when sql (str " " sql)))] params))
(format-set-exprs k x))
(sequential? x)
(let [[cols clauses] (split-with (complement map?) x)]
(if (seq cols)
(recur k {:fields cols :where (:where (first clauses))})
(recur k (first clauses))))
:else
(let [e (format-entity x {:drop-ns true})]
[(str (sql-kw k) " " e " = EXCLUDED." e)])))
(defn- format-simple-clause [c context]
(binding [*inline* true]
(let [[sql & params] (format-dsl c)]
(when (seq params)
(throw (ex-info (str "parameters are not accepted in " context)
{:clause c :params params})))
sql)))
(defn- format-simple-expr [e context]
(binding [*inline* true]
(let [[sql & params] (format-expr e)]
(when (seq params)
(throw (ex-info (str "parameters are not accepted in " context)
{:expr e :params params})))
sql)))
(defn- format-alter-table [k x]
(if (sequential? x)
[(str (sql-kw k) " " (format-entity (first x))
(when-let [clauses (next x)]
(str " " (str/join ", " (map #(format-simple-clause % "column/index operations") clauses)))))]
[(str (sql-kw k) " " (format-entity x))]))
(defn- format-ddl-options
"Given a sequence of options for a DDL statement (the part that
comes between the entity name being created/dropped and the
remaining part of the statement), render clauses and sequences
of keywords and entity names. Returns a sequence of SQL strings."
[opts context]
(for [opt opts]
(cond (map? opt)
(format-simple-clause opt context)
(sequential? opt)
(str/join " "
(map (fn [e]
(if (ident? e)
(sql-kw e)
(format-simple-expr e context)))
opt))
:else
(sql-kw opt))))
(defn- destructure-create-item [table context]
(let [params
(if (sequential? table)
table
[table])
tab? #(or (ident? %) (string? %))
coll (take-while tab? params)
opts (drop-while tab? params)
ine (last coll)
[prequel table ine]
(if (= :if-not-exists (sym->kw ine))
[(butlast (butlast coll)) (last (butlast coll)) ine]
[(butlast coll) (last coll) nil])]
(into [(str/join " " (map sql-kw prequel))
(format-entity table)
(when ine (sql-kw ine))]
(format-ddl-options opts context))))
(defn- format-create [q k item as]
(let [[pre entity ine & more]
(destructure-create-item item (str (sql-kw q) " options"))]
[(str/join " " (remove nil?
(-> [(sql-kw q)
(when (and (= :create q) (seq pre)) pre)
(sql-kw k)
ine
(when (and (= :refresh q) (seq pre)) pre)
entity]
(into more)
(conj (when as (sql-kw as))))))]))
(defn- format-with-data [_ data]
(let [data (if (sequential? data) (first data) data)]
[(str/join " " (remove nil?
[(sql-kw :with)
(when-not data (sql-kw :no))
(sql-kw :data)]))]))
(defn- destructure-drop-items [tables context]
(let [params
(if (sequential? tables)
tables
[tables])
coll (take-while ident? params)
opts (drop-while ident? params)
[if-exists & tables]
(if (#{:if-exists 'if-exists} (first coll))
coll
(cons nil coll))]
(into [(when if-exists (sql-kw :if-exists))
(str/join ", " (map #'format-entity tables))]
(format-ddl-options opts context))))
(defn- format-drop-items
[k params]
(let [[if-exists tables & more] (destructure-drop-items params "DROP options")]
[(str/join " " (remove nil? (into [(sql-kw k) if-exists tables] more)))]))
(def ^:private ^:dynamic *formatted-column* (atom false))
(defn- format-single-column [xs]
(reset! *formatted-column* true)
(str/join " " (cons (format-simple-expr (first xs) "column operation")
(map #(binding [*formatted-column* (atom false)]
(cond-> (format-simple-expr % "column operation")
(not @*formatted-column*)
(upper-case)))
(rest xs)))))
(defn- format-table-columns [_ xs]
[(str "("
(str/join ", " (map #'format-single-column xs))
")")])
(defn- format-add-item [k spec]
(if (contains? #{:if-not-exists 'if-not-exists} (last spec))
[(str (sql-kw k) " " (sql-kw :if-not-exists) " " (format-single-column (butlast spec)))]
[(str (sql-kw k) " " (format-single-column spec))]))
(defn- format-rename-item [k [x y]]
[(str (sql-kw k) " " (format-entity x) " TO " (format-entity y))])
(defn- raw-render [s]
(if (sequential? s)
(let [[sqls params]
(reduce (fn [[sqls params] s]
(if (sequential? s)
(let [[sql & params'] (format-expr s)]
[(conj sqls sql)
(into params params')])
[(conj sqls s) params]))
[[] []]
s)]
(into [(str/join sqls)] params))
[s]))
(def ^:private base-clause-order
"The (base) order for known clauses. Can have items added and removed.
This is the 'pre-dialect' ordering."
(atom default-clause-order))
(def ^:private current-clause-order
"The (current) order for known clauses. Can have items added and removed.
This is the 'post-dialect` ordering when a new default dialect is set."
(atom default-clause-order))
(def ^:private clause-format
"The (default) behavior for each known clause. Can also have items added
and removed."
(atom {:alter-table #'format-alter-table
:add-column #'format-add-item
:drop-column #'format-drop-items
:modify-column #'format-add-item
:rename-column #'format-rename-item
;; so :add-index works with both [:index] and [:unique]
:add-index (fn [_ x] (format-on-expr :add x))
:drop-index #'format-selector
:rename-table (fn [_ x] (format-selector :rename-to x))
:create-table (fn [_ x] (format-create :create :table x nil))
:create-table-as (fn [_ x] (format-create :create :table x :as))
:create-extension (fn [_ x] (format-create :create :extension x nil))
:with-columns #'format-table-columns
:create-view (fn [_ x] (format-create :create :view x :as))
:create-materialized-view (fn [_ x] (format-create :create :materialized-view x :as))
:drop-table #'format-drop-items
:drop-extension #'format-drop-items
:drop-view #'format-drop-items
:drop-materialized-view #'format-drop-items
:refresh-materialized-view (fn [_ x] (format-create :refresh :materialized-view x nil))
:raw (fn [_ x] (raw-render x))
:nest (fn [_ x]
(let [[sql & params] (format-dsl x {:nested true})]
(into [sql] params)))
:with #'format-with
:with-recursive #'format-with
:intersect #'format-on-set-op
:union #'format-on-set-op
:union-all #'format-on-set-op
:except #'format-on-set-op
:except-all #'format-on-set-op
:table #'format-selector
:select #'format-selects
:select-distinct #'format-selects
:select-distinct-on #'format-selects-on
:select-top #'format-select-top
:select-distinct-top #'format-select-top
:into #'format-select-into
:bulk-collect-into #'format-select-into
:insert-into #'format-insert
:update #'format-selector
:delete #'format-selects
:delete-from #'format-selector
:truncate #'format-selector
:columns #'format-columns
:set #'format-set-exprs
:from #'format-selects
:using #'format-selects
:join-by #'format-join-by
:join #'format-join
:left-join #'format-join
:right-join #'format-join
:inner-join #'format-join
:outer-join #'format-join
:full-join #'format-join
:cross-join #'format-selects
:where #'format-on-expr
:group-by #'format-group-by