honeysql/README.md

400 lines
11 KiB
Markdown
Raw Normal View History

# Honey SQL
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
[![Build Status](https://travis-ci.org/jkk/honeysql.svg?branch=master)](https://travis-ci.org/jkk/honeysql)
[![Dependencies Status](http://jarkeeper.com/jkk/honeysql/status.svg)](http://jarkeeper.com/jkk/honeysql)
## Leiningen Coordinates
2012-08-24 22:49:52 +00:00
[![Clojars Project](http://clojars.org/honeysql/latest-version.svg)](http://clojars.org/honeysql)
2012-08-24 22:49:52 +00:00
## Note on code samples
All sample code in this README is automatically run as a unit test using
[midje-readme](https://github.com/boxed/midje-readme).
Note that while some of these samples show pretty-printed SQL, this is just for
README readability; honeysql does not generate pretty-printed SQL.
The #sql/regularize directive tells the test-runner to ignore the extraneous
whitespace.
## Usage
```clojure
2012-08-24 22:20:58 +00:00
(require '[honeysql.core :as sql]
'[honeysql.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
```clojure
2012-07-13 13:57:47 +00:00
(def sqlmap {:select [:a :b :c]
:from [:foo]
:where [:= :f.a "baz"]})
2012-07-13 15:46:50 +00:00
```
2012-07-13 17:13:37 +00:00
`format` turns maps into `clojure.java.jdbc`-compatible, parameterized SQL:
2012-07-13 13:57:47 +00:00
```clojure
2012-07-13 14:53:19 +00:00
(sql/format sqlmap)
=> ["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
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 jdbc:
```clj
2017-08-21 05:44:06 +00:00
(jdbc/query conn (sql/format sqlmap))
```
2012-08-24 22:31:49 +00:00
You can build up SQL maps yourself or use helper functions. `build` is the Swiss Army Knife helper. It lets you leave out brackets here and there:
2012-08-24 22:20:58 +00:00
```clojure
2012-08-24 22:20:58 +00:00
(sql/build :select :*
:from :foo
:where [:= :f.a "baz"])
=> {:where [:= :f.a "baz"], :from [:foo], :select [:*]}
```
You can provide a "base" map as the first argument to build:
```clojure
2012-08-24 22:20:58 +00:00
(sql/build sqlmap :offset 10 :limit 10)
=> {:limit 10
:offset 10
:select [:a :b :c]
:where [:= :f.a "baz"]
:from [:foo]}
2012-08-24 22:20:58 +00:00
```
There are also functions for each clause type in the `honeysql.helpers` namespace:
2012-07-13 13:57:47 +00:00
```clojure
2012-07-13 15:46:50 +00:00
(-> (select :a :b :c)
(from :foo)
(where [:= :f.a "baz"]))
```
2012-07-13 17:13:37 +00:00
Order doesn't matter:
2012-07-13 15:46:50 +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
2012-07-13 17:13:37 +00:00
When using the vanilla helper functions, new clauses will replace old clauses:
2012-07-13 13:57:47 +00:00
```clojure
2012-07-13 15:46:50 +00:00
(-> sqlmap (select :*))
=> '{:from [:foo], :where [:= :f.a "baz"], :select (:*)}
2012-07-13 15:46:50 +00:00
```
2012-07-13 17:13:37 +00:00
To add to clauses instead of replacing them, use `merge-select`, `merge-where`, etc.:
2012-07-13 15:46:50 +00:00
```clojure
2012-08-24 22:20:58 +00:00
(-> sqlmap
(merge-select :d :e)
(merge-where [:> :b 10])
sql/format)
=> ["SELECT a, b, c, d, e 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
`where` will combine multiple clauses together using and:
```clojure
(-> (select :*)
(from :foo)
(where [:= :a 1] [:< :b 100])
sql/format)
=> ["SELECT * FROM foo WHERE (a = ? AND b < ?)" 1 100]
```
2014-10-07 22:07:39 +00:00
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)
2014-06-21 14:14:46 +00:00
(columns :name :surname :age)
(values
2014-06-21 14:14:46 +00:00
[["Jon" "Smith" 34]
["Andrew" "Cooper" 12]
["Jane" "Daniels" 56]])
sql/format)
=> [#sql/regularize
"INSERT INTO properties (name, surname, age)
VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)"
"Jon" "Smith" 34 "Andrew" "Cooper" 12 "Jane" "Daniels" 56]
```
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:
```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}
{:name "Jane" :surname "Daniels" :age 56}])
2014-10-07 22:07:39 +00:00
sql/format)
=> [#sql/regularize
"INSERT INTO properties (name, surname, age)
VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)"
"John" "Smith" 34
"Andrew" "Cooper" 12
"Jane" "Daniels" 56]
2014-10-07 22:07:39 +00:00
```
The column values do not have to be literals, they can be nested queries:
```clojure
2014-10-07 22:07:39 +00:00
(let [user-id 12345
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)
(where [:= :name role-name]))}])
2014-10-07 22:08:57 +00:00
sql/format))
=> [#sql/regularize
"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
```
Updates are possible too (note the double S in `sset` to avoid clashing
with `clojure.core/set`):
```clojure
(-> (helpers/update :films)
2014-06-21 14:14:46 +00:00
(sset {:kind "dramatic"
:watched true})
(where [:= :kind "drama"])
sql/format)
=> ["UPDATE films SET kind = ?, watched = TRUE WHERE kind = ?" "dramatic" "drama"]
```
Deletes look as you would expect:
```clojure
2014-06-21 14:14:46 +00:00
(-> (delete-from :films)
(where [:<> :kind "musical"])
sql/format)
=> ["DELETE FROM films WHERE kind <> ?" "musical"]
```
2012-07-13 15:46:50 +00:00
Queries can be nested:
```clojure
2012-08-24 22:20:58 +00:00
(-> (select :*)
(from :foo)
(where [:in :foo.a (-> (select :a) (from :bar))])
sql/format)
=> ["SELECT * FROM foo WHERE (foo.a in (SELECT a FROM bar))"]
2012-07-13 15:46:50 +00:00
```
2012-07-13 13:57:47 +00:00
Queries may be united within a :union or :union-all keyword:
```clojure
(sql/format {:union [(-> (select :*) (from :foo))
(-> (select :*) (from :bar))]})
2016-11-06 20:29:37 +00:00
=> ["SELECT * FROM foo UNION SELECT * FROM bar"]
```
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
```clojure
2013-08-06 18:05:17 +00:00
(-> (select :%count.*) (from :foo) sql/format)
=> ["SELECT count(*) FROM foo"]
(-> (select :%max.id) (from :foo) sql/format)
=> ["SELECT max(id) FROM foo"]
2013-08-06 18:05:17 +00:00
```
2013-08-06 18:27:56 +00:00
Keywords that begin with `?` are interpreted as bindable parameters:
```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"]
```
2013-08-06 18:05:17 +00:00
There are helper functions and data literals for SQL function calls, field qualifiers, raw SQL fragments, and named input parameters:
```clojure
(def call-qualify-map
(-> (select (sql/call :foo :bar) (sql/qualify :foo :a) (sql/raw "@var := foo.bar"))
(from :foo)
(where [:= :a (sql/param :baz)])))
2012-07-13 13:57:47 +00:00
call-qualify-map
=> '{:where [:= :a #sql/param :baz]
:from (:foo)
:select (#sql/call [:foo :bar] :foo.a #sql/raw "@var := foo.bar")}
(sql/format call-qualify-map :params {:baz "BAZ"})
=> ["SELECT foo(bar), foo.a, @var := foo.bar FROM foo WHERE a = ?" "BAZ"]
2012-07-13 13:57:47 +00:00
```
To quote identifiers, pass the `:quoting` keyword option to `format`. Valid options are `:ansi` (PostgreSQL), `:mysql`, or `:sqlserver`:
2013-08-06 19:08:09 +00:00
```clojure
2013-08-06 19:08:09 +00:00
(-> (select :foo.a)
(from :foo)
(where [:= :foo.a "baz"])
(sql/format :quoting :mysql))
=> ["SELECT `foo`.`a` FROM `foo` WHERE `foo`.`a` = ?" "baz"]
```
2015-04-20 01:57:44 +00:00
To issue a locking select, add a :lock to the query or use the lock helper. The lock value must be a map with a :mode value. The built-in
modes are the standard :update (FOR UPDATE) or the vendor-specific :mysql-share (LOCK IN SHARE MODE) or :postresql-share (FOR SHARE). The
lock map may also provide a :wait value, which if false will append the NOWAIT parameter, supported by PostgreSQL.
```clojure
2015-04-20 01:57:44 +00:00
(-> (select :foo.a)
(from :foo)
(where [:= :foo.a "baz"])
2016-05-07 18:09:09 +00:00
(lock :mode :update)
2015-04-20 01:57:44 +00:00
(sql/format))
=> ["SELECT foo.a FROM foo WHERE foo.a = ? FOR UPDATE" "baz"]
```
To support novel lock modes, implement the `format-lock-clause` multimethod.
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.
```clojure
(sql/format
{:select [:f.foo-id :f.foo-name]
:from [[:foo-bar :f]]
:where [:= :f.foo-id 12345]}
:allow-dashed-names? true
:quoting :ansi)
=> ["SELECT \"f\".\"foo-id\", \"f\".\"foo-name\" FROM \"foo-bar\" \"f\" WHERE \"f\".\"foo-id\" = ?" 12345]
```
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
```clojure
(def big-complicated-map
(-> (select :f.* :b.baz :c.quux [:b.bla "bla-bla"]
(sql/call :now) (sql/raw "@x := 10"))
(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
[:and [:= :f.a "bort"] [:not= :b.baz (sql/param :param1)]]
[:< 1 2 3]
[:in :f.e [1 (sql/param :param2) 3]]
[:between :f.e 10 20]])
(group :f.a)
(having [:< 0 :f.e])
(order-by [:b.baz :desc] :c.quux [:f.a :nulls-first])
(limit 50)
(offset 10)))
big-complicated-map
=> {:select [:f.* :b.baz :c.quux [:b.bla "bla-bla"]
(sql/call :now) (sql/raw "@x := 10")]
: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
[:and [:= :f.a "bort"] [:not= :b.baz (sql/param :param1)]]
[:< 1 2 3]
[:in :f.e [1 (sql/param :param2) 3]]
[:between :f.e 10 20]]
:group-by [:f.a]
:having [:< 0 :f.e]
:order-by [[:b.baz :desc] :c.quux [:f.a :nulls-first]]
:limit 50
:offset 10}
(sql/format big-complicated-map {:param1 "gabba" :param2 2})
=> [#sql/regularize
"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
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]
2012-07-13 17:13:37 +00:00
;; Printable and readable
(= big-complicated-map (read-string (pr-str big-complicated-map)))
=> true
2012-07-13 15:46:50 +00:00
```
2012-08-24 22:20:58 +00:00
## Extensibility
You can define your own function handlers for use in `where`:
```clojure
2012-08-24 22:20:58 +00:00
(require '[honeysql.format :as fmt])
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)
=> ["SELECT a WHERE a BETWIXT ? AND ?" 1 10]
2012-08-24 22:31:49 +00:00
2012-08-24 22:20:58 +00:00
```
You can also define your own clauses:
```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)))
(sql/format {:select [:a :b] :foobar :baz})
=> ["SELECT a, b FOOBAR baz"]
(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)))
(-> (select :a :b) (foobar :baz) sql/format)
=> ["SELECT a, b FOOBAR baz"]
```
2012-10-22 14:20:26 +00:00
If you do implement a clause or function handler, consider submitting a pull request so others can use it, too.
2012-07-13 17:11:46 +00:00
## TODO
* Create table, etc.
## Extensions
* [For PostgreSQL-specific extensions falling outside of ANSI SQL](https://github.com/nilenso/honeysql-postgres)
## License
Copyright © 2012-2016 Justin Kramer
Distributed under the Eclipse Public License, the same as Clojure.