2020-09-25 02:07:32 +00:00
# Honey SQL [](https://circleci.com/gh/seancorfield/honeysql/tree/v2)
2012-07-13 01:50:13 +00:00
2013-08-06 20:36:56 +00:00
SQL as Clojure data structures. Build queries programmatically -- even at runtime -- without having to bash strings together.
2012-12-03 17:38:48 +00:00
2015-02-24 06:00:47 +00:00
## Build
2020-09-25 02:07:32 +00:00
The latest stable version (1.0.444) on Clojars and on cljdoc:
2020-03-08 22:17:18 +00:00
2020-05-29 23:10:16 +00:00
[](https://clojars.org/honeysql) [](https://cljdoc.org/d/honeysql/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.
2020-03-08 22:17:18 +00:00
2020-09-25 02:07:32 +00:00
This is the README for the upcoming 2.x version of HoneySQL which 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 the 1.x version).
2017-07-19 05:11:49 +00:00
## Note on code samples
All sample code in this README is automatically run as a unit test using
2020-03-08 22:19:54 +00:00
[seancorfield/readme ](https://github.com/seancorfield/readme ).
2017-07-19 05:11:49 +00:00
Note that while some of these samples show pretty-printed SQL, this is just for
README readability; honeysql does not generate pretty-printed SQL.
2020-09-25 02:07:32 +00:00
2012-07-13 01:50:13 +00:00
## Usage
2017-07-19 05:11:49 +00:00
```clojure
2020-09-29 03:45:43 +00:00
(refer-clojure :exclude '[for group-by set update])
2020-09-25 02:07:32 +00:00
(require '[honey.sql :as sql]
2020-09-29 03:45:43 +00:00
;; caution: this overwrites for, group-by, set, and update
2020-09-25 02:07:32 +00:00
'[honey.sql.helpers :refer :all :as helpers])
2012-07-13 15:46:50 +00:00
```
Everything is built on top of maps representing SQL queries:
2012-07-13 13:57:47 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2012-07-13 13:57:47 +00:00
(def sqlmap {:select [:a :b :c]
2019-09-08 06:42:38 +00:00
:from [:foo]
:where [:= :f.a "baz"]})
2012-07-13 15:46:50 +00:00
```
2019-09-07 20:14:36 +00:00
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).
2020-02-07 21:49:32 +00:00
### `format`
2020-03-08 22:40:08 +00:00
`format` turns maps into `next.jdbc` -compatible (and `clojure.java.jdbc` -compatible), parameterized SQL:
2012-07-13 13:57:47 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2012-07-13 14:53:19 +00:00
(sql/format sqlmap)
2017-07-19 01:01:00 +00:00
=> ["SELECT a, b, c FROM foo WHERE f.a = ?" "baz"]
2012-07-13 15:46:50 +00:00
```
2012-07-13 13:57:47 +00:00
2020-09-25 03:49:22 +00:00
HoneySQL is a relatively "pure" library, it does not manage your sql 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 ):
```clj
(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.
2020-09-25 02:07:32 +00:00
_The handling of namespace-qualified keywords is under review in 2.x._
2020-05-07 15:28:44 +00:00
By default, namespace-qualified keywords are treated as simple keywords: their namespace portion is ignored. This was the behavior in HoneySQL prior to the 0.9.0 release and has been restored since the 0.9.7 release as this is considered the least surprising behavior.
2019-09-08 06:42:38 +00:00
As of version 0.9.7, `format` accepts `:allow-namespaced-names? true` to provide the somewhat unusual behavior of 0.9.0-0.9.6, namely that namespace-qualified keywords were passed through into the SQL "as-is", i.e., with the `/` in them (which generally required a quoting strategy as well).
As of version 0.9.8, `format` accepts `:namespace-as-table? true` to treat namespace-qualified keywords as if the `/` were `.` , allowing `:table/column` as an alternative to `:table.column` . 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"]})
2020-09-25 02:07:32 +00:00
(sql/format q-sqlmap)
2019-09-08 06:42:38 +00:00
=> ["SELECT foo.a, foo.b, foo.c FROM foo WHERE foo.a = ?" "baz"]
```
2020-02-07 21:49:32 +00:00
### Vanilla SQL clause helpers
2020-09-25 03:49:22 +00:00
_The code behind this section is a work-in-progress._
There are also functions for each clause type in the `honey.sql.helpers` namespace:
2012-07-13 13:57:47 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2012-07-13 15:46:50 +00:00
(-> (select :a :b :c)
(from :foo)
(where [:= :f.a "baz"]))
```
2020-09-25 03:49:22 +00:00
Order doesn't matter (for independent clauses):
2012-07-13 15:46:50 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2012-07-13 15:46:50 +00:00
(= (-> (select :*) (from :foo))
(-> (from :foo) (select :*)))
2012-07-13 14:53:19 +00:00
=> true
2012-07-13 15:46:50 +00:00
```
2012-07-13 14:53:19 +00:00
2020-09-25 03:49:22 +00:00
When using the vanilla helper functions, repeated clauses will be merged into existing clauses (where that makes sense):
2012-07-13 13:57:47 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2020-09-25 03:49:22 +00:00
(-> sqlmap (select :d))
=> '{:from [:foo], :where [:= :f.a "baz"], :select [:a :b :c :d]}
2012-07-13 15:46:50 +00:00
```
2020-09-25 03:49:22 +00:00
If you want to replace a clause, you can `dissoc` the existing clause first, since this is all data:
2012-07-13 15:46:50 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2012-08-24 22:20:58 +00:00
(-> sqlmap
2020-09-25 03:49:22 +00:00
(dissoc :select)
(select :*)
(where [:> :b 10])
2012-08-24 22:20:58 +00:00
sql/format)
2020-09-25 03:49:22 +00:00
=> ["SELECT * FROM foo WHERE (f.a = ?) AND (b > ?)" "baz" 10]
2012-07-13 15:46:50 +00:00
```
2012-07-13 13:57:47 +00:00
2020-02-07 18:31:57 +00:00
`where` will combine multiple clauses together using SQL's `AND` :
2015-03-25 00:31:07 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2015-03-25 00:31:07 +00:00
(-> (select :*)
(from :foo)
(where [:= :a 1] [:< :b 100 ] )
sql/format)
2020-09-25 03:49:22 +00:00
=> ["SELECT * FROM foo WHERE (a = ?) AND (b < ?)" 1 100]
2015-03-25 00:31:07 +00:00
```
2018-06-25 20:00:42 +00:00
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)
2020-09-25 03:49:22 +00:00
=> ["SELECT a, b AS bar, c, d AS x FROM foo quux WHERE (quux.a = ?) AND (bar < ?)" 1 100]
2018-06-25 20:00:42 +00:00
```
In particular, note that `(select [:a :b])` means `SELECT a AS b` rather than
`SELECT a, b` -- `select` is variadic and does not take a collection of column names.
2020-02-07 21:49:32 +00:00
### Inserts
2018-06-25 19:30:48 +00:00
Inserts are supported in two patterns.
2014-10-07 22:07:39 +00:00
In the first pattern, you must explicitly specify the columns to insert,
then provide a collection of rows, each a collection of column values:
2014-06-21 12:23:02 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2014-06-21 12:23:02 +00:00
(-> (insert-into :properties)
2014-06-21 14:14:46 +00:00
(columns :name :surname :age)
2014-06-21 12:23:02 +00:00
(values
2014-06-21 14:14:46 +00:00
[["Jon" "Smith" 34]
["Andrew" "Cooper" 12]
["Jane" "Daniels" 56]])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true}))
=> ["
INSERT INTO properties (name, surname, age)
VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
"
"Jon" "Smith" 34 "Andrew" "Cooper" 12 "Jane" "Daniels" 56]
2014-06-21 12:23:02 +00:00
```
2014-10-07 22:07:39 +00:00
Alternately, you can simply specify the values as maps; the first map defines the columns to insert,
and the remaining maps *must* have the same set of keys and values:
2017-07-19 05:11:49 +00:00
```clojure
2014-10-07 22:07:39 +00:00
(-> (insert-into :properties)
(values [{:name "John" :surname "Smith" :age 34}
{:name "Andrew" :surname "Cooper" :age 12}
2015-03-17 16:22:05 +00:00
{:name "Jane" :surname "Daniels" :age 56}])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true}))
=> ["
INSERT INTO properties (name, surname, age)
VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
"
"John" "Smith" 34
"Andrew" "Cooper" 12
"Jane" "Daniels" 56]
2014-10-07 22:07:39 +00:00
```
2020-02-07 21:49:32 +00:00
### Nested subqueries
2014-10-07 22:07:39 +00:00
The column values do not have to be literals, they can be nested queries:
2017-07-19 05:11:49 +00:00
```clojure
2014-10-07 22:07:39 +00:00
(let [user-id 12345
2014-10-22 17:01:46 +00:00
role-name "user"]
2014-10-07 22:07:39 +00:00
(-> (insert-into :user_profile_to_role)
(values [{:user_profile_id user-id
:role_id (-> (select :id)
(from :role)
2014-10-22 17:01:46 +00:00
(where [:= :name role-name]))}])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true})))
2014-10-22 17:01:46 +00:00
2020-09-26 06:58:51 +00:00
=> ["
INSERT INTO user_profile_to_role (user_profile_id, role_id)
VALUES (?, (SELECT id FROM role WHERE name = ?))
"
12345
"user"]
2014-10-07 22:07:39 +00:00
```
2020-02-07 21:49:32 +00:00
```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))"]
```
### Composite types
2019-09-07 22:56:06 +00:00
Composite types are supported:
```clojure
(-> (insert-into :comp_table)
(columns :name :comp_column)
(values
[["small" (composite 1 "inch")]
["large" (composite 10 "feet")]])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true}))
=> ["
INSERT INTO comp_table (name, comp_column)
VALUES (?, (?, ?)), (?, (?, ?))
"
"small" 1 "inch" "large" 10 "feet"]
2019-09-07 22:56:06 +00:00
```
2020-02-07 21:49:32 +00:00
### Updates
2020-09-29 02:24:17 +00:00
Updates are possible too:
2014-06-21 12:23:02 +00:00
2017-07-19 05:11:49 +00:00
```clojure
(-> (helpers/update :films)
2020-09-29 02:24:17 +00:00
(set {:kind "dramatic"
:watched [:+ :watched 1]})
2014-06-21 14:14:46 +00:00
(where [:= :kind "drama"])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true}))
=> ["
UPDATE films SET kind = ?, watched = (watched + ?)
WHERE kind = ?
"
"dramatic"
1
"drama"]
2014-06-21 12:23:02 +00:00
```
2019-09-07 21:55:06 +00:00
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
2020-09-25 03:49:22 +00:00
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.
2019-09-07 21:55:06 +00:00
2020-02-07 21:49:32 +00:00
### Deletes
2014-06-21 12:23:02 +00:00
Deletes look as you would expect:
2017-07-19 05:11:49 +00:00
```clojure
2014-06-21 14:14:46 +00:00
(-> (delete-from :films)
(where [:< > :kind "musical"])
2020-09-26 06:58:51 +00:00
(sql/format))
2014-06-21 12:23:02 +00:00
=> ["DELETE FROM films WHERE kind < > ?" "musical"]
```
2018-06-27 01:24:01 +00:00
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"])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true}))
=> ["
DELETE films, directors
FROM films
INNER JOIN directors ON films.director_id = directors.id
WHERE kind < > ?
"
"musical"]
2018-06-27 01:24:01 +00:00
```
2019-09-07 20:24:46 +00:00
If you want to delete everything from a table, you can use `truncate` :
```clojure
(-> (truncate :films)
2020-09-26 06:58:51 +00:00
(sql/format))
2019-09-07 20:24:46 +00:00
=> ["TRUNCATE films"]
```
2020-03-06 17:34:06 +00:00
### Set operations
2012-07-13 13:57:47 +00:00
2020-03-06 17:34:06 +00:00
Queries may be combined within a :union, :union-all, :intersect or :except keyword:
2015-08-25 15:25:05 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2015-08-25 15:25:05 +00:00
(sql/format {:union [(-> (select :*) (from :foo))
(-> (select :*) (from :bar))]})
2016-11-06 20:29:37 +00:00
=> ["SELECT * FROM foo UNION SELECT * FROM bar"]
2015-08-25 15:25:05 +00:00
```
2020-02-07 21:49:32 +00:00
### Functions
2013-08-06 18:05:17 +00:00
Keywords that begin with `%` are interpreted as SQL function calls:
2012-07-13 15:46:50 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2013-08-06 18:05:17 +00:00
(-> (select :%count.*) (from :foo) sql/format)
2014-07-25 05:52:08 +00:00
=> ["SELECT count(*) FROM foo"]
2020-03-03 07:20:08 +00:00
```
```clojure
2014-07-25 05:52:08 +00:00
(-> (select :%max.id) (from :foo) sql/format)
=> ["SELECT max(id) FROM foo"]
2013-08-06 18:05:17 +00:00
```
2020-02-07 21:49:32 +00:00
### Bindable parameters
2020-09-25 03:49:22 +00:00
_This is not currently supported._
2013-08-06 18:27:56 +00:00
Keywords that begin with `?` are interpreted as bindable parameters:
2017-07-19 05:11:49 +00:00
```clojure
2013-08-06 18:27:56 +00:00
(-> (select :id)
(from :foo)
(where [:= :a :?baz])
2013-08-06 19:08:09 +00:00
(sql/format :params {:baz "BAZ"}))
2013-08-06 18:27:56 +00:00
=> ["SELECT id FROM foo WHERE a = ?" "BAZ"]
```
2020-02-07 21:49:32 +00:00
### Miscellaneous
2020-09-25 03:49:22 +00:00
TODO: need to update this section to reflect how to select a function call, how
to identify inline parameter values, and how to add in raw SQL fragments!
2013-08-06 18:05:17 +00:00
2017-07-19 05:11:49 +00:00
```clojure
(def call-qualify-map
2020-09-25 03:49:22 +00:00
(-> (select [[:foo :bar]] [[:raw "@var := foo.bar"]])
2017-07-19 05:11:49 +00:00
(from :foo)
2020-09-29 02:24:17 +00:00
(where [:= :a [:param :baz]] [:= :b [:inline 42]])))
2020-03-03 07:20:08 +00:00
```
```clojure
2017-07-19 05:11:49 +00:00
call-qualify-map
2020-09-29 02:24:17 +00:00
=> '{:where [:and [:= :a [:param :baz]] [:= :b [:inline 42]]]
2017-07-19 05:11:49 +00:00
:from (:foo)
2020-09-25 03:49:22 +00:00
:select [[[:foo :bar]] [[:raw "@var := foo.bar"]]]}
2020-03-03 07:20:08 +00:00
```
```clojure
2020-09-29 02:24:17 +00:00
(sql/format call-qualify-map {:params {:baz "BAZ"}})
2020-09-25 03:49:22 +00:00
=> ["SELECT foo(bar), @var := foo.bar FROM foo WHERE (a = ?) AND (b = 42)" "BAZ"]
2012-07-13 13:57:47 +00:00
```
2012-07-13 01:50:13 +00:00
2020-02-07 21:49:32 +00:00
#### PostGIS
2019-10-19 19:12:23 +00:00
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)
2020-09-25 03:49:22 +00:00
(values [{:location [:ST_SetSRID
[:ST_MakePoint 0.291 32.621]
[:cast 4325 :integer]]}])
2020-09-26 06:58:51 +00:00
(sql/format {:pretty? true}))
=> ["
INSERT INTO sample (location)
VALUES (ST_SetSRID(ST_MakePoint(?, ?), CAST(? AS integer)))
"
0.291 32.621 4326]
2019-10-19 19:12:23 +00:00
```
2020-02-07 21:49:32 +00:00
#### Raw SQL fragments
2020-09-25 03:49:22 +00:00
_This functionality is under review._
2018-06-30 04:59:17 +00:00
Raw SQL fragments that are strings are treated exactly as-is when rendered into
the formatted SQL string (with no parsing or parameterization). Inline values
will not be lifted out as parameters, so they end up in the SQL string as-is.
Raw SQL can also be supplied as a vector of strings and values. Strings are
rendered as-is into the formatted SQL string. Non-strings are lifted as
2020-09-29 02:24:17 +00:00
parameters. If you need a string parameter lifted, you must use `:param`
2018-06-30 04:59:17 +00:00
or the `param` helper.
```clojure
(-> (select :*)
(from :foo)
2020-09-29 02:24:17 +00:00
(where [:< :expired_at [ :raw [ " now ( ) - ' " 5 " seconds ' " ] ] ] )
2018-06-30 04:59:17 +00:00
(sql/format {:foo 5}))
=> ["SELECT * FROM foo WHERE expired_at < now ( ) - ' ? seconds ' " 5 ]
```
```clojure
(-> (select :*)
(from :foo)
2020-09-29 02:24:17 +00:00
(where [:< :expired_at [ :raw [ " now ( ) - ' " [ :param :t ] " seconds ' " ] ] ] )
2018-06-30 04:59:17 +00:00
(sql/format {:t 5}))
=> ["SELECT * FROM foo WHERE expired_at < now ( ) - ' ? seconds ' " 5 ]
```
2018-06-25 19:30:48 +00:00
2020-02-07 21:49:32 +00:00
#### Identifiers
2020-09-25 03:49:22 +00:00
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` :
2013-08-06 19:08:09 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2013-08-06 19:08:09 +00:00
(-> (select :foo.a)
(from :foo)
(where [:= :foo.a "baz"])
2020-09-25 03:49:22 +00:00
(sql/format {:dialect :mysql}))
2013-08-06 19:08:09 +00:00
=> ["SELECT `foo` .`a` FROM `foo` WHERE `foo` .`a` = ?" "baz"]
```
2020-02-07 21:49:32 +00:00
#### Locking
2020-09-29 03:45:43 +00:00
The ANSI/PostgreSQL/SQLServer dialects support locking selects via a `FOR` clause as follows:
2020-09-25 03:49:22 +00:00
2020-09-29 03:45:43 +00:00
* `:for [<lock-strength> <table(s)> <nowait>]` where `<lock-strength>` is required and may be one of:
* `:update`
* `:no-key-update`
* `:share`
* `:key-share`
* Both `<table(s)>` and `<nowait>` 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)
* `<nowait>` must be `:nowait` if it is present.
If `<table(s)>` and `<nowait>` are both omitted, you may also omit the `[` ..`]` and just say `:for :update` etc.
2015-04-20 01:57:44 +00:00
2017-07-19 05:11:49 +00:00
```clojure
2015-04-20 01:57:44 +00:00
(-> (select :foo.a)
(from :foo)
2017-07-19 01:01:00 +00:00
(where [:= :foo.a "baz"])
2020-09-29 03:45:43 +00:00
(for :update)
(format))
=> ["SELECT foo.a FROM foo WHERE (foo.a = ?) FOR UPDATE" "baz"]
2015-04-20 01:57:44 +00:00
```
2020-09-29 03:45:43 +00:00
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"]
```
2015-04-20 01:57:44 +00:00
2015-10-16 19:22:04 +00:00
To be able to use dashes in quoted names, you can pass ```:allow-dashed-names true``` as an argument to the ```format``` function.
2017-07-19 05:11:49 +00:00
```clojure
(sql/format
2015-10-16 19:19:42 +00:00
{:select [:f.foo-id :f.foo-name]
:from [[:foo-bar :f]]
:where [:= :f.foo-id 12345]}
2020-09-29 03:45:43 +00:00
{:allow-dashed-names? true ; not implemented yet
:quoted true})
2017-07-19 05:11:49 +00:00
=> ["SELECT \"f\".\"foo-id\", \"f\".\"foo-name\" FROM \"foo-bar\" \"f\" WHERE \"f\".\"foo-id\" = ?" 12345]
2015-10-16 19:19:42 +00:00
```
2020-02-07 21:49:32 +00:00
### Big, complicated example
2012-08-25 03:06:24 +00:00
Here's a big, complicated query. Note that Honey SQL makes no attempt to verify that your queries make any sense. It merely renders surface syntax.
2012-07-13 15:46:50 +00:00
2017-07-19 05:11:49 +00:00
```clojure
(def big-complicated-map
(-> (select :f.* :b.baz :c.quux [:b.bla "bla-bla"]
2020-09-25 03:49:22 +00:00
[[:now]] [[:raw "@x := 10"]])
2020-09-29 03:45:43 +00:00
#_ (modifiers :distinct) ; this is not implemented yet
2017-07-19 05:11:49 +00:00
(from [:foo :f] [:baz :b])
(join :draq [:= :f.b :draq.x])
(left-join [:clod :c] [:= :f.a :c.d])
(right-join :bock [:= :bock.z :c.e])
(where [:or
2020-09-29 02:24:17 +00:00
[:and [:= :f.a "bort"] [:not= :b.baz [:param :param1]]]
2017-07-19 05:11:49 +00:00
[:< 1 2 3 ]
2020-09-29 02:24:17 +00:00
[:in :f.e [1 [:param :param2] 3]]
2017-07-19 05:11:49 +00:00
[:between :f.e 10 20]])
2020-09-29 03:45:43 +00:00
(group-by :f.a :c.e)
2017-07-19 05:11:49 +00:00
(having [:< 0 :f . e ] )
(order-by [:b.baz :desc] :c.quux [:f.a :nulls-first])
(limit 50)
(offset 10)))
2020-03-03 07:20:08 +00:00
```
```clojure
2017-07-19 05:11:49 +00:00
big-complicated-map
2012-10-19 16:41:26 +00:00
=> {:select [:f.* :b.baz :c.quux [:b.bla "bla-bla"]
2020-09-25 03:49:22 +00:00
[[:now]] [[:raw "@x := 10"]]]
2012-10-19 16:41:26 +00:00
:modifiers [:distinct]
:from [[:foo :f] [:baz :b]]
:join [:draq [:= :f.b :draq.x]]
:left-join [[:clod :c] [:= :f.a :c.d]]
:right-join [:bock [:= :bock.z :c.e]]
:where [:or
2020-09-29 02:24:17 +00:00
[:and [:= :f.a "bort"] [:not= :b.baz [:param :param1]]]
2012-10-19 16:41:26 +00:00
[:< 1 2 3 ]
2020-09-29 02:24:17 +00:00
[:in :f.e [1 [:param :param2] 3]]
2012-10-19 16:41:26 +00:00
[:between :f.e 10 20]]
2020-02-12 20:10:24 +00:00
:group-by [:f.a :c.e]
2012-10-19 16:41:26 +00:00
:having [:< 0 :f . e ]
2017-07-19 01:01:00 +00:00
:order-by [[:b.baz :desc] :c.quux [:f.a :nulls-first]]
2012-10-19 16:41:26 +00:00
:limit 50
:offset 10}
2020-03-03 07:20:08 +00:00
```
```clojure
2017-07-19 05:11:49 +00:00
(sql/format big-complicated-map {:param1 "gabba" :param2 2})
2020-09-26 06:58:51 +00:00
=> ["
SELECT DISTINCT f.*, b.baz, c.quux, b.bla AS bla_bla, now(), @x := 10
FROM foo f, baz b
INNER JOIN draq ON f.b = draq.x
LEFT JOIN clod 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, f.a NULLS FIRST
LIMIT ?
OFFSET ?
"
"bort" "gabba" 1 2 2 3 1 2 3 10 20 0 50 10]
2020-03-03 07:20:08 +00:00
```
```clojure
2012-07-13 17:13:37 +00:00
;; Printable and readable
2017-07-19 05:11:49 +00:00
(= big-complicated-map (read-string (pr-str big-complicated-map)))
2012-07-13 17:09:02 +00:00
=> true
2012-07-13 15:46:50 +00:00
```
2012-08-24 22:20:58 +00:00
## Extensibility
2020-09-25 03:49:22 +00:00
_This needs a rewrite!_
2012-08-24 22:20:58 +00:00
You can define your own function handlers for use in `where` :
2020-03-03 07:20:08 +00:00
```clojure
2012-08-24 22:31:49 +00:00
(defmethod fmt/fn-handler "betwixt" [_ field lower upper]
(str (fmt/to-sql field) " BETWIXT "
2012-08-24 22:20:58 +00:00
(fmt/to-sql lower) " AND " (fmt/to-sql upper)))
2012-08-24 22:31:49 +00:00
(-> (select :a) (where [:betwixt :a 1 10]) sql/format)
2017-07-19 01:01:00 +00:00
=> ["SELECT a WHERE a BETWIXT ? AND ?" 1 10]
2012-08-24 22:20:58 +00:00
```
You can also define your own clauses:
2017-07-19 05:11:49 +00:00
```clojure
2012-08-24 22:20:58 +00:00
;; Takes a MapEntry of the operator & clause data, plus the entire SQL map
(defmethod fmt/format-clause :foobar [[op v] sqlmap]
(str "FOOBAR " (fmt/to-sql v)))
2020-03-08 22:17:18 +00:00
```
```clojure
2012-08-24 22:20:58 +00:00
(sql/format {:select [:a :b] :foobar :baz})
=> ["SELECT a, b FOOBAR baz"]
2020-03-03 07:20:08 +00:00
```
```clojure
2012-08-24 22:20:58 +00:00
(require '[honeysql.helpers :refer [defhelper]])
2012-08-24 22:37:03 +00:00
;; Defines a helper function, and allows 'build' to recognize your clause
2012-08-24 22:20:58 +00:00
(defhelper foobar [m args]
(assoc m :foobar (first args)))
2020-03-08 22:17:18 +00:00
```
```clojure
2012-08-24 22:20:58 +00:00
(-> (select :a :b) (foobar :baz) sql/format)
=> ["SELECT a, b FOOBAR baz"]
```
2019-03-25 21:40:00 +00:00
When adding a new clause, you may also need to register it with a specific priority so that it formats correctly, for example:
```clojure
(fmt/register-clause! :foobar 110)
```
If you do implement a clause or function handler for an ANSI SQL, consider submitting a pull request so others can use it, too. For non-standard clauses and/or functions, look for a library that extends `honeysql` for that specific database or create one, if no such library exists.
2012-10-22 14:20:26 +00:00
2020-03-08 22:17:18 +00:00
## Why does my parameter get emitted as `()`?
2019-03-25 21:40:00 +00:00
2020-03-08 22:40:08 +00:00
If you want to use your own datatype as a parameter then the idiomatic approach of implementing
`next.jdbc` 's [`SettableParameter` ](https://cljdoc.org/d/seancorfield/next.jdbc/CURRENT/api/next.jdbc.prepare#SettableParameter )
or `clojure.java.jdbc` 's [`ISQLValue` ](https://clojure.github.io/java.jdbc/#clojure.java.jdbc/ISQLValue ) protocol isn't enough as `honeysql` won't correct pass through your datatype, rather it will interpret it incorrectly.
2017-08-26 18:39:04 +00:00
2020-05-29 19:25:49 +00:00
To teach `honeysql` how to handle your datatype you need to implement [`honeysql.format/ToSql` ](https://github.com/seancorfield/honeysql/blob/a9dffec632be62c961be7d9e695d0b2b85732c53/src/honeysql/format.cljc#L94 ). For example:
2017-08-26 18:39:04 +00:00
``` clojure
;; given:
(defrecord MyDateWrapper [...]
(to-sql-timestamp [this]...)
)
;; executing:
(hsql/format {:where [:> :some_column (MyDateWrapper. ...)]})
;; results in => "where :some_column > ()"
;; we can teach honeysql about it:
2018-12-30 23:38:17 +00:00
(extend-protocol honeysql.format/ToSql
2017-08-26 18:39:04 +00:00
MyDateWrapper
(to-sql [v] (to-sql (date/to-sql-timestamp v))))
2018-06-25 19:30:48 +00:00
2017-08-26 18:39:04 +00:00
;; allowing us to now:
(hsql/format {:where [:> :some_column (MyDateWrapper. ...)]})
;; which correctly results in => "where :some_column>?" and the parameter correctly set
```
2012-07-13 17:11:46 +00:00
## TODO
2020-02-07 21:49:32 +00:00
- [ ] Create table, etc.
2012-07-13 17:11:46 +00:00
2016-07-10 18:43:18 +00:00
## Extensions
* [For PostgreSQL-specific extensions falling outside of ANSI SQL ](https://github.com/nilenso/honeysql-postgres )
2012-07-13 01:50:13 +00:00
## License
2020-09-25 02:07:32 +00:00
Copyright (c) 2020 Sean Corfield. HoneySQL 1.x was copyright (c) 2012-2020 Justin Kramer and Sean Corfield.
2012-07-13 01:50:13 +00:00
Distributed under the Eclipse Public License, the same as Clojure.