Codebase list honeysql-clojure / HEAD
HEAD

Tree @HEAD (Download .tar.gz)

  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
# Honey SQL [![Clojure CI](https://github.com/seancorfield/honeysql/actions/workflows/test.yml/badge.svg)](https://github.com/seancorfield/honeysql/actions/workflows/test.yml) [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/seancorfield/honeysql)

SQL as Clojure data structures. Build queries programmatically -- even at runtime -- without having to bash strings together.

## Build

[![Clojars Project](https://clojars.org/com.github.seancorfield/honeysql/latest-version.svg)](https://clojars.org/com.github.seancorfield/honeysql) [![cljdoc badge](https://cljdoc.org/badge/com.github.seancorfield/honeysql?2.3.911)](https://cljdoc.org/d/com.github.seancorfield/honeysql/CURRENT)

This project follows the version scheme MAJOR.MINOR.COMMITS where MAJOR and MINOR provide some relative indication of the size of the change, but do not follow semantic versioning. In general, all changes endeavor to be non-breaking (by moving to new names rather than by breaking existing names). COMMITS is an ever-increasing counter of commits since the beginning of this repository.

> Note: every commit to the **develop** branch runs CI (GitHub Actions) and successful runs push a MAJOR.MINOR.999-SNAPSHOT build to Clojars so the very latest version of HoneySQL is always available either via that [snapshot on Clojars](https://clojars.org/com.github.seancorfield/honeysql) or via a git dependency on the latest SHA.

HoneySQL 2.x requires Clojure 1.9 or later.

Compared to 1.x, HoneySQL 2.x provides a streamlined codebase and a simpler method for extending the DSL. It also supports SQL dialects out-of-the-box and will be extended to support vendor-specific language features over time (unlike 1.x).

> Note: you can use 1.x and 2.x side-by-side as they use different group IDs and different namespaces. This allows for a piecemeal migration. See this [summary of differences between 1.x and 2.x](doc/differences-from-1-x.md) if you are migrating from 1.x!

## Try HoneySQL Online!

[John Shaffer](https://github.com/john-shaffer) has created this awesome
[HoneySQL web app](https://john.shaffe.rs/honeysql/), written in ClojureScript,
so you can experiment with HoneySQL in a browser, including setting different
options so you can generate pretty SQL with inline values (via `:inline true`)
for copying and pasting directly into your SQL tool of choice!

## Note on code samples

Sample code in this documentation is verified via
[lread/test-doc-blocks](https://github.com/lread/test-doc-blocks).

Some of these samples show pretty-printed SQL: HoneySQL 2.x supports `:pretty true` which inserts newlines between clauses in the generated SQL strings.

### HoneySQL 1.x

[![Clojars Project](https://clojars.org/honeysql/honeysql/latest-version.svg)](https://clojars.org/honeysql/honeysql) [![cljdoc badge](https://cljdoc.org/badge/honeysql/honeysql?1.0.461)](https://cljdoc.org/d/honeysql/honeysql/CURRENT)

HoneySQL 1.x will continue to get critical security fixes but otherwise should be considered "legacy" at this point.

## Usage

This section includes a number of usage examples but does not dive deep into the
way the data structure acts as a DSL that can specify SQL statements (as hash maps)
and SQL expressions and function calls (as vectors). It is recommended that you read the
[**Getting Started**](https://cljdoc.org/d/com.github.seancorfield/honeysql/CURRENT/doc/getting-started)
section of the documentation before trying to use HoneySQL to build your own queries!

From Clojure:
<!-- {:test-doc-blocks/reader-cond :clj} -->
```clojure
(refer-clojure :exclude '[filter for group-by into partition-by set update])
(require '[honey.sql :as sql]
         ;; CAUTION: this overwrites several clojure.core fns:
         ;;
         ;; filter, for, group-by, into, partition-by, set, and update
         ;;
         ;; you should generally only refer in the specific
         ;; helpers that you want to use!
         '[honey.sql.helpers :refer :all :as h]
         ;; so we can still get at clojure.core functions:
         '[clojure.core :as c])
```

From ClojureScript, we don't have `:refer :all`. If we want to use `:refer`, we have no choice but to be specific:
<!-- {:test-doc-blocks/reader-cond :cljs} -->
```Clojure
(refer-clojure :exclude '[filter for group-by into partition-by set update])
(require '[honey.sql :as sql]
         '[honey.sql.helpers :refer [select select-distinct from
                                     join left-join right-join
                                     where for group-by having union
                                     order-by limit offset values columns
                                     update insert-into set composite
                                     delete delete-from truncate] :as h]
         '[clojure.core :as c])
```

Everything is built on top of maps representing SQL queries:

```clojure
(def sqlmap {:select [:a :b :c]
             :from   [:foo]
             :where  [:= :foo.a "baz"]})
```

Column names can be provided as keywords or symbols (but not strings -- HoneySQL treats strings as values that should be lifted out of the SQL as parameters).

### `format`

`format` turns maps into `next.jdbc`-compatible (and `clojure.java.jdbc`-compatible), parameterized SQL:

```clojure
(sql/format sqlmap)
=> ["SELECT a, b, c FROM foo WHERE foo.a = ?" "baz"]
;; sqlmap as symbols instead of keywords:
(-> '{select (a, b, c) from (foo) where (= foo.a "baz")}
    (sql/format))
=> ["SELECT a, b, c FROM foo WHERE foo.a = ?" "baz"]
```

HoneySQL is a relatively "pure" library, it does not manage your JDBC connection
or run queries for you, it simply generates SQL strings. You can then pass them
to a JDBC library, such as [`next.jdbc`](https://github.com/seancorfield/next-jdbc):

<!-- :test-doc-blocks/skip -->
```clojure
(jdbc/execute! conn (sql/format sqlmap))
```

> Note: you'll need to add your preferred JDBC library as a dependency in your project -- HoneySQL deliberately does not make that choice for you.

If you want to format the query as a string with no parameters (e.g. to use the SQL statement in a SQL console), pass `:inline true` as an option to `sql/format`:

```clojure
(sql/format sqlmap {:inline true})
=> ["SELECT a, b, c FROM foo WHERE foo.a = 'baz'"]
```

Namespace-qualified keywords (and symbols) are generally treated as table-qualified columns: `:foo/bar` becomes `foo.bar`, except in contexts where that would be illegal (such as the list of columns in an `INSERT` statement). This approach is likely to be more compatible with code that uses libraries like [`next.jdbc`](https://github.com/seancorfield/next-jdbc) and [`seql`](https://github.com/exoscale/seql), as well as being more convenient in a world of namespace-qualified keywords, following the example of `clojure.spec` etc.

```clojure
(def q-sqlmap {:select [:foo/a :foo/b :foo/c]
               :from   [:foo]
               :where  [:= :foo/a "baz"]})
(sql/format q-sqlmap)
=> ["SELECT foo.a, foo.b, foo.c FROM foo WHERE foo.a = ?" "baz"]
;; this also works with symbols instead of keywords:
(-> '{select (foo/a, foo/b, foo/c)
      from   (foo)
      where  (= foo/a "baz")}
    (sql/format))
=> ["SELECT foo.a, foo.b, foo.c FROM foo WHERE foo.a = ?" "baz"]
```

Documentation for the entire data DSL can be found in the
[Clause Reference](doc/clause-reference.md), the
[Operator Reference](doc/operator-reference.md), and the
[Special Syntax reference](doc/special-syntax.md).

### Vanilla SQL clause helpers

For every single SQL clause supported by HoneySQL (as keywords or symbols
in the data structure that is the DSL), there is also a corresponding
function in the `honey.sql.helpers` namespace:

```clojure
(-> (select :a :b :c)
    (from :foo)
    (where [:= :foo.a "baz"]))
=> {:select [:a :b :c] :from [:foo] :where [:= :foo.a "baz"]}
```

Order doesn't matter (for independent clauses):

```clojure
(= (-> (select :*) (from :foo))
   (-> (from :foo) (select :*)))
=> true
```

When using the vanilla helper functions, repeated clauses will be merged into existing clauses, in the natural evaluation order (where that makes sense):

```clojure
(-> sqlmap (select :d))
=> {:from [:foo], :where [:= :foo.a "baz"], :select [:a :b :c :d]}
```

If you want to replace a clause, you can `dissoc` the existing clause first, since this is all data:

```clojure
(-> sqlmap
    (dissoc :select)
    (select :*)
    (where [:> :b 10])
    sql/format)
=> ["SELECT * FROM foo WHERE (foo.a = ?) AND (b > ?)" "baz" 10]
```

> Note: the helpers always produce keywords so you can rely on `dissoc` with the desired keyword to remove. If you are building the data DSL "manually" and using symbols instead of keywords, you'll need to `dissoc` the symbol form instead.

`where` will combine multiple clauses together using SQL's `AND`:

```clojure
(-> (select :*)
    (from :foo)
    (where [:= :a 1] [:< :b 100])
    sql/format)
=> ["SELECT * FROM foo WHERE (a = ?) AND (b < ?)" 1 100]
```

Column and table names may be aliased by using a vector pair of the original
name and the desired alias:

```clojure
(-> (select :a [:b :bar] :c [:d :x])
    (from [:foo :quux])
    (where [:= :quux.a 1] [:< :bar 100])
    sql/format)
=> ["SELECT a, b AS bar, c, d AS x FROM foo AS quux WHERE (quux.a = ?) AND (bar < ?)" 1 100]
```

In particular, note that `(select [:a :b])` means `SELECT a AS b` rather than
`SELECT a, b` -- helpers like `select` are generally variadic and do not take
a collection of column names.

The examples in this README use a mixture of data structures and the helper
functions interchangably. For any example using the helpers, you could evaluate
it (without the call to `sql/format`) to see what the equivalent data structure
would be.

Documentation for all the helpers can be found in the
[`honey.sql.helpers` API reference](https://cljdoc.org/d/com.github.seancorfield/honeysql/CURRENT/api/honey.sql.helpers).

### Inserts

Inserts are supported in two patterns.
In the first pattern, you must explicitly specify the columns to insert,
then provide a collection of rows, each a collection of column values:

```clojure
(-> (insert-into :properties)
    (columns :name :surname :age)
    (values
     [["Jon" "Smith" 34]
      ["Andrew" "Cooper" 12]
      ["Jane" "Daniels" 56]])
    (sql/format {:pretty true}))
=> ["
INSERT INTO properties
(name, surname, age)
VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
"
"Jon" "Smith" 34 "Andrew" "Cooper" 12 "Jane" "Daniels" 56]
;; or as pure data DSL:
(-> {:insert-into [:properties]
     :columns [:name :surname :age]
     :values [["Jon" "Smith" 34]
              ["Andrew" "Cooper" 12]
              ["Jane" "Daniels" 56]]}
    (sql/format {:pretty true}))
=> ["
INSERT INTO properties
(name, surname, age)
VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
"
"Jon" "Smith" 34 "Andrew" "Cooper" 12 "Jane" "Daniels" 56]
```

If the rows are of unequal lengths, they will be padded with `NULL` values to make them consistent.

Alternately, you can simply specify the values as maps:

```clojure
(-> (insert-into :properties)
    (values [{:name "John" :surname "Smith" :age 34}
             {:name "Andrew" :surname "Cooper" :age 12}
             {:name "Jane" :surname "Daniels" :age 56}])
    (sql/format {:pretty true}))
=> ["
INSERT INTO properties
(name, surname, age) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
"
"John" "Smith" 34
"Andrew" "Cooper"  12
"Jane" "Daniels" 56]
;; or as pure data DSL:
(-> {:insert-into [:properties]
     :values [{:name "John", :surname "Smith", :age 34}
              {:name "Andrew", :surname "Cooper", :age 12}
              {:name "Jane", :surname "Daniels", :age 56}]}
    (sql/format {:pretty true}))
=> ["
INSERT INTO properties
(name, surname, age) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
"
"John" "Smith" 34
"Andrew" "Cooper"  12
"Jane" "Daniels" 56]
```

The set of columns used in the insert will be the union of all column names from all
the hash maps: columns that are missing from any rows will have `NULL` as their value
unless you specify those columns in the `:values-default-columns` option, which takes
a set of column names that should get the value `DEFAULT` instead of `NULL`:


```clojure
(-> (insert-into :properties)
    (values [{:name "John" :surname "Smith" :age 34}
             {:name "Andrew" :age 12}
             {:name "Jane" :surname "Daniels"}])
    (sql/format {:pretty true}))
=> ["
INSERT INTO properties
(name, surname, age) VALUES (?, ?, ?), (?, NULL, ?), (?, ?, NULL)
"
"John" "Smith" 34
"Andrew" 12
"Jane" "Daniels"]
(-> (insert-into :properties)
    (values [{:name "John" :surname "Smith" :age 34}
             {:name "Andrew" :age 12}
             {:name "Jane" :surname "Daniels"}])
    (sql/format {:pretty true :values-default-columns #{:age}}))
=> ["
INSERT INTO properties
(name, surname, age) VALUES (?, ?, ?), (?, NULL, ?), (?, ?, DEFAULT)
"
"John" "Smith" 34
"Andrew" 12
"Jane" "Daniels"]
```

### Nested subqueries

The column values do not have to be literals, they can be nested queries:

```clojure
(let [user-id 12345
      role-name "user"]
  (-> (insert-into :user_profile_to_role)
      (values [{:user_profile_id user-id
                :role_id         (-> (select :id)
                                     (from :role)
                                     (where [:= :name role-name]))}])
      (sql/format {:pretty true})))

=> ["
INSERT INTO user_profile_to_role
(user_profile_id, role_id) VALUES (?, (SELECT id FROM role WHERE name = ?))
"
12345
"user"]
;; or as pure data DSL:
(let [user-id 12345
      role-name "user"]
  (-> {:insert-into [:user_profile_to_role]
       :values [{:user_profile_id 12345,
                 :role_id {:select [:id],
                           :from [:role],
                           :where [:= :name "user"]}}]}
      (sql/format {:pretty true})))
=> ["
INSERT INTO user_profile_to_role
(user_profile_id, role_id) VALUES (?, (SELECT id FROM role WHERE name = ?))
"
12345
"user"]
```

```clojure
(-> (select :*)
    (from :foo)
    (where [:in :foo.a (-> (select :a) (from :bar))])
    (sql/format))
=> ["SELECT * FROM foo WHERE foo.a IN (SELECT a FROM bar)"]
;; or as pure data DSL:
(-> {:select [:*],
     :from [:foo],
     :where [:in :foo.a {:select [:a], :from [:bar]}]}
    (sql/format))
=> ["SELECT * FROM foo WHERE foo.a IN (SELECT a FROM bar)"]
```

Because values can be nested queries -- and also because values can be function calls --
whenever you are working with values that are, themselves, structured data, you will
need to tell HoneySQL not to interpret that structured data as part of the DSL. This
especially affects using JSON values with HoneySQL (e.g., targeting PostgreSQL). There
are two possible approaches:

1. Use named parameters instead of having the values directly in the DSL structure (see `:param` under **Miscellaneous** below), or
2. Use `[:lift ..]` wrapped around any structured values which tells HoneySQL not to interpret the vector or hash map value as a DSL.

### Composite types

Composite types are supported:

```clojure
(-> (insert-into :comp_table)
    (columns :name :comp_column)
    (values
     [["small" (composite 1 "inch")]
      ["large" (composite 10 "feet")]])
    (sql/format {:pretty true}))
=> ["
INSERT INTO comp_table
(name, comp_column)
VALUES (?, (?, ?)), (?, (?, ?))
"
"small" 1 "inch" "large" 10 "feet"]
;; or as pure data DSL:
(-> {:insert-into [:comp_table],
     :columns [:name :comp_column],
     :values [["small" [:composite 1 "inch"]]
              ["large" [:composite 10 "feet"]]]}
    (sql/format {:pretty true}))
=> ["
INSERT INTO comp_table
(name, comp_column)
VALUES (?, (?, ?)), (?, (?, ?))
"
"small" 1 "inch" "large" 10 "feet"]
```

### Updates

Updates are possible too:

```clojure
(-> (update :films)
    (set {:kind "dramatic"
           :watched [:+ :watched 1]})
    (where [:= :kind "drama"])
    (sql/format {:pretty true}))
=> ["
UPDATE films
SET kind = ?, watched = watched + ?
WHERE kind = ?
"
"dramatic"
1
"drama"]
;; or as pure data DSL:
(-> {:update :films,
     :set {:kind "dramatic", :watched [:+ :watched 1]},
     :where [:= :kind "drama"]}
    (sql/format {:pretty true}))
=> ["
UPDATE films
SET kind = ?, watched = watched + ?
WHERE kind = ?
"
"dramatic"
1
"drama"]
```

If you are trying to build a compound update statement (with `from` or `join`),
be aware that different databases have slightly different syntax in terms of
where `SET` should appear. The default above is to put `SET` before `FROM` which
is how PostgreSQL (and other ANSI-SQL dialects work). If you are using MySQL,
you will need to select the `:mysql` dialect in order to put the `SET` after
any `JOIN` clause.

### Deletes

Deletes look as you would expect:

```clojure
(-> (delete-from :films)
    (where [:<> :kind "musical"])
    (sql/format))
=> ["DELETE FROM films WHERE kind <> ?" "musical"]
;; or as pure data DSL:
(-> {:delete-from [:films],
     :where [:<> :kind "musical"]}
    (sql/format))
=> ["DELETE FROM films WHERE kind <> ?" "musical"]
```

If your database supports it, you can also delete from multiple tables:

```clojure
(-> (delete [:films :directors])
    (from :films)
    (join :directors [:= :films.director_id :directors.id])
    (where [:<> :kind "musical"])
    (sql/format {:pretty true}))
=> ["
DELETE films, directors
FROM films
INNER JOIN directors ON films.director_id = directors.id
WHERE kind <> ?
"
"musical"]
;; or pure data DSL:
(-> {:delete [:films :directors],
     :from [:films],
     :join [:directors [:= :films.director_id :directors.id]],
     :where [:<> :kind "musical"]}
    (sql/format {:pretty true}))
=> ["
DELETE films, directors
FROM films
INNER JOIN directors ON films.director_id = directors.id
WHERE kind <> ?
"
"musical"]
```

If you want to delete everything from a table, you can use `truncate`:

```clojure
(-> (truncate :films)
    (sql/format))
=> ["TRUNCATE films"]
;; or as pure data DSL:
(-> {:truncate :films}
    (sql/format))
=> ["TRUNCATE films"]
```

### Set operations

Queries may be combined with a `:union`, `:union-all`, `:intersect` or `:except` keyword:

```clojure
(sql/format {:union [(-> (select :*) (from :foo))
                     (-> (select :*) (from :bar))]})
=> ["SELECT * FROM foo UNION SELECT * FROM bar"]
```

There are also helpers for each of those:

```clojure
(sql/format (union (-> (select :*) (from :foo))
                   (-> (select :*) (from :bar))))
=> ["SELECT * FROM foo UNION SELECT * FROM bar"]
```

### Functions

Function calls (and expressions with operators) can be specified as
vectors where the first element is either a keyword or a symbol:

```clojure
(-> (select :*) (from :foo)
    (where [:> :date_created [:date_add [:now] [:interval 24 :hours]]])
    (sql/format))
=> ["SELECT * FROM foo WHERE date_created > DATE_ADD(NOW(), INTERVAL ? HOURS)" 24]
```

A shorthand syntax also exists for simple function calls:
keywords that begin with `%` are interpreted as SQL function calls:

```clojure
(-> (select :%count.*) (from :foo) sql/format)
=> ["SELECT COUNT(*) FROM foo"]
```
```clojure
(-> (select :%max.id) (from :foo) sql/format)
=> ["SELECT MAX(id) FROM foo"]
```

Since regular function calls are indicated with vectors and so are aliased pairs,
this shorthand can be more convenient due to the extra wrapping needed for the
regular function calls in a select:

```clojure
(-> (select [[:count :*]]) (from :foo) sql/format)
=> ["SELECT COUNT(*) FROM foo"]
```
```clojure
(-> (select [:%count.*]) (from :foo) sql/format)
=> ["SELECT COUNT(*) FROM foo"]
;; or even:
(-> (select :%count.*) (from :foo) sql/format)
=> ["SELECT COUNT(*) FROM foo"]
```
```clojure
(-> (select [[:max :id]]) (from :foo) sql/format)
=> ["SELECT MAX(id) FROM foo"]
;; the pure data DSL requires an extra level of brackets:
(-> {:select [[[:max :id]]], :from [:foo]} sql/format)
=> ["SELECT MAX(id) FROM foo"]
;; the shorthand makes this simpler:
(-> {:select [[:%max.id]], :from [:foo]} sql/format)
=> ["SELECT MAX(id) FROM foo"]
;; or even:
(-> {:select [:%max.id], :from [:foo]} sql/format)
=> ["SELECT MAX(id) FROM foo"]
;; or even:
(-> {:select :%max.id, :from :foo} sql/format)
=> ["SELECT MAX(id) FROM foo"]
```

If a keyword begins with `'`, the function name is formatted as a SQL
entity rather than being converted to uppercase and having hyphens `-`
converted to spaces). That means that hyphens `-` will become underscores `_`
unless you have quoting enabled:

```clojure
(-> (select :*) (from :foo)
    (where [:'my-schema.SomeFunction :bar 0])
    (sql/format))
=> ["SELECT * FROM foo WHERE my_schema.SomeFunction(bar, ?)" 0]
(-> (select :*) (from :foo)
    (where [:'my-schema.SomeFunction :bar 0])
    (sql/format :quoted true))
=> ["SELECT * FROM \"foo\" WHERE \"my-schema\".\"SomeFunction\"(\"bar\", ?)" 0]
(-> (select :*) (from :foo)
    (where [:'my-schema.SomeFunction :bar 0])
    (sql/format :dialect :mysql))
=> ["SELECT * FROM `foo` WHERE `my-schema`.`SomeFunction`(`bar`, ?)" 0]
```

### Bindable parameters

Keywords that begin with `?` are interpreted as bindable parameters:

```clojure
(-> (select :id)
    (from :foo)
    (where [:= :a :?baz])
    (sql/format {:params {:baz "BAZ"}}))
=> ["SELECT id FROM foo WHERE a = ?" "BAZ"]
;; or as pure data DSL:
(-> {:select [:id], :from [:foo], :where [:= :a :?baz]}
    (sql/format {:params {:baz "BAZ"}}))
=> ["SELECT id FROM foo WHERE a = ?" "BAZ"]
```

### Miscellaneous

Sometimes you want to provide SQL fragments directly or have certain values
placed into the SQL string rather than turned into a parameter.

The `:raw` syntax lets you embed SQL fragments directly into a HoneySQL expression.
It accepts either a single string to embed or a vector of expressions that will be
converted to strings and embedded as a single string.

The `:inline` syntax attempts to turn a Clojure value into a SQL value and then
embeds that string, e.g., `[:inline "foo"]` produces `'foo'` (a SQL string).

The `:param` syntax identifies a named parameter whose value will be supplied
via the `:params` argument to `format`.

The `:lift` syntax will prevent interpretation of Clojure data structures as
part of the DSL and instead turn such values into parameters (useful when you
want to pass a vector or a hash map directly as a positional parameter value,
for example when you have extended `next.jdbc`'s `SettableParameter` protocol
to a data structure -- as is common when working with PostgreSQL's JSON/JSONB types).

Finally, the `:nest` syntax will cause an extra set of parentheses to be
wrapped around its argument, after formatting that argument as a SQL expression.

These can be combined to allow more fine-grained control over SQL generation:

```clojure
(def call-qualify-map
  (-> (select [[:foo :bar]] [[:raw "@var := foo.bar"]])
      (from :foo)
      (where [:= :a [:param :baz]] [:= :b [:inline 42]])))
```
```clojure
call-qualify-map
=> {:where [:and [:= :a [:param :baz]] [:= :b [:inline 42]]]
    :from (:foo)
    :select [[[:foo :bar]] [[:raw "@var := foo.bar"]]]}
```
```clojure
(sql/format call-qualify-map {:params {:baz "BAZ"}})
=> ["SELECT FOO(bar), @var := foo.bar FROM foo WHERE (a = ?) AND (b = 42)" "BAZ"]
```

```clojure
(-> (select :*)
    (from :foo)
    (where [:< :expired_at [:raw ["now() - '" 5 " seconds'"]]])
    (sql/format))
=> ["SELECT * FROM foo WHERE expired_at < now() - '5 seconds'"]
```

```clojure
(-> (select :*)
    (from :foo)
    (where [:< :expired_at [:raw ["now() - '" [:lift 5] " seconds'"]]])
    (sql/format))
=> ["SELECT * FROM foo WHERE expired_at < now() - '? seconds'" 5]
```

```clojure
(-> (select :*)
    (from :foo)
    (where [:< :expired_at [:raw ["now() - '" [:param :t] " seconds'"]]])
    (sql/format {:params {:t 5}}))
=> ["SELECT * FROM foo WHERE expired_at < now() - '? seconds'" 5]
```

```clojure
(-> (select :*)
    (from :foo)
    (where [:< :expired_at [:raw ["now() - " [:inline (str 5 " seconds")]]]])
    (sql/format))
=> ["SELECT * FROM foo WHERE expired_at < now() - '5 seconds'"]
```

#### PostGIS

A common example in the wild is the PostGIS extension to PostgreSQL where you
have a lot of function calls needed in code:

```clojure
(-> (insert-into :sample)
    (values [{:location [:ST_SetSRID
                         [:ST_MakePoint 0.291 32.621]
                         [:cast 4325 :integer]]}])
    (sql/format {:pretty true}))
=> ["
INSERT INTO sample
(location) VALUES (ST_SETSRID(ST_MAKEPOINT(?, ?), CAST(? AS integer)))
"
0.291 32.621 4325]
```

#### Identifiers

To quote identifiers, pass the `:quoted true` option to `format` and they will
be quoted according to the selected dialect. If you override the dialect in a
`format` call, by passing the `:dialect` option, identifiers will be automatically
quoted. You can override the dialect and turn off quoting by passing `:quoted false`.
Valid `:dialect` options are `:ansi` (the default, use this for PostgreSQL),
`:mysql`, `:oracle`, or `:sqlserver`:

```clojure
(-> (select :foo.a)
    (from :foo)
    (where [:= :foo.a "baz"])
    (sql/format {:dialect :mysql}))
=> ["SELECT `foo`.`a` FROM `foo` WHERE `foo`.`a` = ?" "baz"]
```

#### Locking

The ANSI/PostgreSQL/SQLServer dialects support locking selects via a `FOR` clause as follows:

* `:for [<lock-strength> <table(s)> <qualifier>]` where `<lock-strength>` is required and may be one of:
  * `:update`
  * `:no-key-update`
  * `:share`
  * `:key-share`
* Both `<table(s)>` and `<qualifier>` are optional but if present, `<table(s)>` must either be:
  * a single table name (as a keyword) or
  * a sequence of table names (as keywords)
* `<qualifier>` can be `:nowait`, `:wait`, `:skip-locked` etc.

If `<table(s)>` and `<qualifier>` are both omitted, you may also omit the `[`..`]` and just say `:for :update` etc.

```clojure
(-> (select :foo.a)
    (from :foo)
    (where [:= :foo.a "baz"])
    (for :update)
    (sql/format))
=> ["SELECT foo.a FROM foo WHERE foo.a = ? FOR UPDATE" "baz"]
```

If the `:mysql` dialect is selected, an additional locking clause is available:
`:lock :in-share-mode`.
```clojure
(sql/format {:select [:*] :from :foo
             :where [:= :name [:inline "Jones"]]
             :lock [:in-share-mode]}
            {:dialect :mysql :quoted false})
=> ["SELECT * FROM foo WHERE name = 'Jones' LOCK IN SHARE MODE"]
```

Dashes are allowed in quoted names:

```clojure
(sql/format
  {:select [:f.foo-id :f.foo-name]
   :from [[:foo-bar :f]]
   :where [:= :f.foo-id 12345]}
  {:quoted true})
=> ["SELECT \"f\".\"foo-id\", \"f\".\"foo-name\" FROM \"foo-bar\" AS \"f\" WHERE \"f\".\"foo-id\" = ?" 12345]
```

### Big, complicated example

Here's a big, complicated query. Note that HoneySQL makes no attempt to verify that your queries make any sense. It merely renders surface syntax.

```clojure
(def big-complicated-map
  (-> (select-distinct :f.* :b.baz :c.quux [:b.bla "bla-bla"]
                       [[:now]] [[:raw "@x := 10"]])
      (from [:foo :f] [:baz :b])
      (join :draq [:= :f.b :draq.x]
            :eldr [:= :f.e :eldr.t])
      (left-join [:clod :c] [:= :f.a :c.d])
      (right-join :bock [:= :bock.z :c.e])
      (where [:or
               [:and [:= :f.a "bort"] [:not= :b.baz [:param :param1]]]
               [:and [:< 1 2] [:< 2 3]]
               [:in :f.e [1 [:param :param2] 3]]
               [:between :f.e 10 20]])
      (group-by :f.a :c.e)
      (having [:< 0 :f.e])
      (order-by [:b.baz :desc] :c.quux [:f.a :nulls-first])
      (limit 50)
      (offset 10)))
```
```clojure
big-complicated-map
=> {:select-distinct [:f.* :b.baz :c.quux [:b.bla "bla-bla"]
                     [[:now]] [[:raw "@x := 10"]]]
    :from [[:foo :f] [:baz :b]]
    :join [:draq [:= :f.b :draq.x]
           :eldr [:= :f.e :eldr.t]]
    :left-join [[:clod :c] [:= :f.a :c.d]]
    :right-join [:bock [:= :bock.z :c.e]]
    :where [:or
             [:and [:= :f.a "bort"] [:not= :b.baz [:param :param1]]]
             [:and [:< 1 2] [:< 2 3]]
             [:in :f.e [1 [:param :param2] 3]]
             [:between :f.e 10 20]]
    :group-by [:f.a :c.e]
    :having [:< 0 :f.e]
    :order-by [[:b.baz :desc] :c.quux [:f.a :nulls-first]]
    :limit 50
    :offset 10}
```
```clojure
(sql/format big-complicated-map
            {:params {:param1 "gabba" :param2 2}
             :pretty true})
=> ["
SELECT DISTINCT f.*, b.baz, c.quux, b.bla AS \"bla-bla\", NOW(), @x := 10
FROM foo AS f, baz AS b
INNER JOIN draq ON f.b = draq.x INNER JOIN eldr ON f.e = eldr.t
LEFT JOIN clod AS c ON f.a = c.d
RIGHT JOIN bock ON bock.z = c.e
WHERE ((f.a = ?) AND (b.baz <> ?)) OR ((? < ?) AND (? < ?)) OR (f.e IN (?, ?, ?)) OR f.e BETWEEN ? AND ?
GROUP BY f.a, c.e
HAVING ? < f.e
ORDER BY b.baz DESC, c.quux ASC, f.a NULLS FIRST
LIMIT ?
OFFSET ?
"
"bort" "gabba" 1 2 2 3 1 2 3 10 20 0 50 10]
```
```clojure
;; Printable and readable
(require '[clojure.edn :as edn])

(= big-complicated-map (edn/read-string (pr-str big-complicated-map)))
=> true
```

## Extensibility

Any keyword (or symbol) that appears as the first element of a vector will be treated as a generic function unless it is declared to be an operator or "special syntax". Any keyword (or symbol) that appears as a key in a hash map will be treated as a SQL clause -- and must either be built-in or must be registered as a new clause.

If your database supports `<=>` as an operator, you can tell HoneySQL about it using the `register-op!` function (which should be called before the first call to `honey.sql/format`):

```clojure
(sql/register-op! :<=>)
;; default is a binary operator:
(-> (select :a) (where [:<=> :a "foo"]) sql/format)
=> ["SELECT a WHERE a <=> ?" "foo"]
;; you can declare that an operator is variadic:
(sql/register-op! :<=> :variadic true)
(-> (select :a) (where [:<=> "food" :a "fool"]) sql/format)
=> ["SELECT a WHERE ? <=> a <=> ?" "food" "fool"]
```

Sometimes you want an operator to ignore `nil` clauses (`:and` and `:or` are declared that way):

```clojure
(sql/register-op! :<=> :ignore-nil true)
```

Or perhaps your database supports syntax like `a BETWIXT b AND c`, in which case you can use `register-fn!` to tell HoneySQL about it (again, called before the first call to `honey.sql/format`):

```clojure
;; the formatter will be passed your new operator (function) and a
;; sequence of the arguments provided to it (so you can write any arity ops):
(sql/register-fn! :betwixt
                  (fn [op [a b c]]
                    (let [[sql-a & params-a] (sql/format-expr a)
                          [sql-b & params-b] (sql/format-expr b)
                          [sql-c & params-c] (sql/format-expr c)]
                      (-> [(str sql-a " " (sql/sql-kw op) " "
                                sql-b " AND " sql-c)]
                          (c/into params-a)
                          (c/into params-b)
                          (c/into params-c)))))
;; example usage:
(-> (select :a) (where [:betwixt :a 1 10]) sql/format)
=> ["SELECT a WHERE a BETWIXT ? AND ?" 1 10]
```

You can also register SQL clauses, specifying the keyword, the formatting function, and an existing clause that this new clause should be processed before:

```clojure
;; the formatter will be passed your new clause and the value associated
;; with that clause in the DSL (which is often a sequence but does not
;; need to be -- it can be whatever syntax you desire in the DSL):
(sql/register-clause! :foobar
                      (fn [clause x]
                        (let [[sql & params]
                              (if (ident? x)
                                (sql/format-expr x)
                                (sql/format-dsl x))]
                          (c/into [(str (sql/sql-kw clause) " " sql)] params)))
                      :from) ; SELECT ... FOOBAR ... FROM ...
;; example usage:
(sql/format {:select [:a :b] :foobar :baz})
=> ["SELECT a, b FOOBAR baz"]
(sql/format {:select [:a :b] :foobar {:where [:= :id 1]}})
=> ["SELECT a, b FOOBAR WHERE id = ?" 1]
```

If you find yourself registering an operator, a function (syntax), or a new clause, consider submitting a [pull request to HoneySQL](https://github.com/seancorfield/honeysql/pulls) so others can use it, too. If it is dialect-specific, let me know in the pull request.

## License

Copyright (c) 2020-2021 Sean Corfield. HoneySQL 1.x was copyright (c) 2012-2020 Justin Kramer and Sean Corfield.

Distributed under the Eclipse Public License, the same as Clojure.