├── .cljstyle
├── .gitignore
├── HISTORY.md
├── LICENSE
├── README.md
├── doc
├── css
│ └── default.css
├── index.html
├── js
│ ├── jquery.min.js
│ └── page_effects.js
├── stch.sql.ddl.html
├── stch.sql.format.html
├── stch.sql.html
├── stch.sql.types.html
└── stch.sql.util.html
├── examples
└── sql.clj
├── project.clj
├── spec
└── stch
│ ├── sql
│ └── ddl_spec.clj
│ └── sql_spec.clj
└── src
└── stch
├── sql.clj
└── sql
├── ddl.clj
├── format.clj
├── types.clj
└── util.clj
/.cljstyle:
--------------------------------------------------------------------------------
1 | {:list-indent-size 1
2 | :indents {defrecord [[:inner 0] [:inner 1]]
3 | defrecord' [[:inner 0] [:inner 1]]
4 | deftype [[:inner 0] [:inner 1]]
5 | create [[:inner 0]]
6 | alt [[:inner 0]]
7 | #"(describe|context|it|around)" [[:inner 0]]}
8 | :line-break-functions? false
9 | :line-break-vars? false
10 | :max-consecutive-blank-lines 1
11 | :padding-lines 1
12 | :reformat-types? false}
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /lib
3 | /classes
4 | /checkouts
5 | pom.xml
6 | pom.xml.asc
7 | *.jar
8 | *.class
9 | .lein-deps-sum
10 | .lein-failures
11 | .lein-plugins
12 | .lein-repl-history
13 | .DS_Store
14 | .nrepl-port
15 |
--------------------------------------------------------------------------------
/HISTORY.md:
--------------------------------------------------------------------------------
1 | # History
2 |
3 | ## 0.1.1
4 |
5 | 1. Add PostgreSQL serial types.
6 |
7 | ## 0.1.0
8 |
9 | 1. Initial release.
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
4 |
5 | 1. DEFINITIONS
6 |
7 | "Contribution" means:
8 |
9 | a) in the case of the initial Contributor, the initial code and
10 | documentation distributed under this Agreement, and
11 |
12 | b) in the case of each subsequent Contributor:
13 |
14 | i) changes to the Program, and
15 |
16 | ii) additions to the Program;
17 |
18 | where such changes and/or additions to the Program originate from and are
19 | distributed by that particular Contributor. A Contribution 'originates' from
20 | a Contributor if it was added to the Program by such Contributor itself or
21 | anyone acting on such Contributor's behalf. Contributions do not include
22 | additions to the Program which: (i) are separate modules of software
23 | distributed in conjunction with the Program under their own license
24 | agreement, and (ii) are not derivative works of the Program.
25 |
26 | "Contributor" means any person or entity that distributes the Program.
27 |
28 | "Licensed Patents" mean patent claims licensable by a Contributor which are
29 | necessarily infringed by the use or sale of its Contribution alone or when
30 | combined with the Program.
31 |
32 | "Program" means the Contributions distributed in accordance with this
33 | Agreement.
34 |
35 | "Recipient" means anyone who receives the Program under this Agreement,
36 | including all Contributors.
37 |
38 | 2. GRANT OF RIGHTS
39 |
40 | a) Subject to the terms of this Agreement, each Contributor hereby grants
41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to
42 | reproduce, prepare derivative works of, publicly display, publicly perform,
43 | distribute and sublicense the Contribution of such Contributor, if any, and
44 | such derivative works, in source code and object code form.
45 |
46 | b) Subject to the terms of this Agreement, each Contributor hereby grants
47 | Recipient a non-exclusive, worldwide, royalty-free patent license under
48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise
49 | transfer the Contribution of such Contributor, if any, in source code and
50 | object code form. This patent license shall apply to the combination of the
51 | Contribution and the Program if, at the time the Contribution is added by the
52 | Contributor, such addition of the Contribution causes such combination to be
53 | covered by the Licensed Patents. The patent license shall not apply to any
54 | other combinations which include the Contribution. No hardware per se is
55 | licensed hereunder.
56 |
57 | c) Recipient understands that although each Contributor grants the licenses
58 | to its Contributions set forth herein, no assurances are provided by any
59 | Contributor that the Program does not infringe the patent or other
60 | intellectual property rights of any other entity. Each Contributor disclaims
61 | any liability to Recipient for claims brought by any other entity based on
62 | infringement of intellectual property rights or otherwise. As a condition to
63 | exercising the rights and licenses granted hereunder, each Recipient hereby
64 | assumes sole responsibility to secure any other intellectual property rights
65 | needed, if any. For example, if a third party patent license is required to
66 | allow Recipient to distribute the Program, it is Recipient's responsibility
67 | to acquire that license before distributing the Program.
68 |
69 | d) Each Contributor represents that to its knowledge it has sufficient
70 | copyright rights in its Contribution, if any, to grant the copyright license
71 | set forth in this Agreement.
72 |
73 | 3. REQUIREMENTS
74 |
75 | A Contributor may choose to distribute the Program in object code form under
76 | its own license agreement, provided that:
77 |
78 | a) it complies with the terms and conditions of this Agreement; and
79 |
80 | b) its license agreement:
81 |
82 | i) effectively disclaims on behalf of all Contributors all warranties and
83 | conditions, express and implied, including warranties or conditions of title
84 | and non-infringement, and implied warranties or conditions of merchantability
85 | and fitness for a particular purpose;
86 |
87 | ii) effectively excludes on behalf of all Contributors all liability for
88 | damages, including direct, indirect, special, incidental and consequential
89 | damages, such as lost profits;
90 |
91 | iii) states that any provisions which differ from this Agreement are offered
92 | by that Contributor alone and not by any other party; and
93 |
94 | iv) states that source code for the Program is available from such
95 | Contributor, and informs licensees how to obtain it in a reasonable manner on
96 | or through a medium customarily used for software exchange.
97 |
98 | When the Program is made available in source code form:
99 |
100 | a) it must be made available under this Agreement; and
101 |
102 | b) a copy of this Agreement must be included with each copy of the Program.
103 |
104 | Contributors may not remove or alter any copyright notices contained within
105 | the Program.
106 |
107 | Each Contributor must identify itself as the originator of its Contribution,
108 | if any, in a manner that reasonably allows subsequent Recipients to identify
109 | the originator of the Contribution.
110 |
111 | 4. COMMERCIAL DISTRIBUTION
112 |
113 | Commercial distributors of software may accept certain responsibilities with
114 | respect to end users, business partners and the like. While this license is
115 | intended to facilitate the commercial use of the Program, the Contributor who
116 | includes the Program in a commercial product offering should do so in a
117 | manner which does not create potential liability for other Contributors.
118 | Therefore, if a Contributor includes the Program in a commercial product
119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend
120 | and indemnify every other Contributor ("Indemnified Contributor") against any
121 | losses, damages and costs (collectively "Losses") arising from claims,
122 | lawsuits and other legal actions brought by a third party against the
123 | Indemnified Contributor to the extent caused by the acts or omissions of such
124 | Commercial Contributor in connection with its distribution of the Program in
125 | a commercial product offering. The obligations in this section do not apply
126 | to any claims or Losses relating to any actual or alleged intellectual
127 | property infringement. In order to qualify, an Indemnified Contributor must:
128 | a) promptly notify the Commercial Contributor in writing of such claim, and
129 | b) allow the Commercial Contributor tocontrol, and cooperate with the
130 | Commercial Contributor in, the defense and any related settlement
131 | negotiations. The Indemnified Contributor may participate in any such claim
132 | at its own expense.
133 |
134 | For example, a Contributor might include the Program in a commercial product
135 | offering, Product X. That Contributor is then a Commercial Contributor. If
136 | that Commercial Contributor then makes performance claims, or offers
137 | warranties related to Product X, those performance claims and warranties are
138 | such Commercial Contributor's responsibility alone. Under this section, the
139 | Commercial Contributor would have to defend claims against the other
140 | Contributors related to those performance claims and warranties, and if a
141 | court requires any other Contributor to pay any damages as a result, the
142 | Commercial Contributor must pay those damages.
143 |
144 | 5. NO WARRANTY
145 |
146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON
147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the
151 | appropriateness of using and distributing the Program and assumes all risks
152 | associated with its exercise of rights under this Agreement , including but
153 | not limited to the risks and costs of program errors, compliance with
154 | applicable laws, damage to or loss of data, programs or equipment, and
155 | unavailability or interruption of operations.
156 |
157 | 6. DISCLAIMER OF LIABILITY
158 |
159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY
166 | OF SUCH DAMAGES.
167 |
168 | 7. GENERAL
169 |
170 | If any provision of this Agreement is invalid or unenforceable under
171 | applicable law, it shall not affect the validity or enforceability of the
172 | remainder of the terms of this Agreement, and without further action by the
173 | parties hereto, such provision shall be reformed to the minimum extent
174 | necessary to make such provision valid and enforceable.
175 |
176 | If Recipient institutes patent litigation against any entity (including a
177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself
178 | (excluding combinations of the Program with other software or hardware)
179 | infringes such Recipient's patent(s), then such Recipient's rights granted
180 | under Section 2(b) shall terminate as of the date such litigation is filed.
181 |
182 | All Recipient's rights under this Agreement shall terminate if it fails to
183 | comply with any of the material terms or conditions of this Agreement and
184 | does not cure such failure in a reasonable period of time after becoming
185 | aware of such noncompliance. If all Recipient's rights under this Agreement
186 | terminate, Recipient agrees to cease use and distribution of the Program as
187 | soon as reasonably practicable. However, Recipient's obligations under this
188 | Agreement and any licenses granted by Recipient relating to the Program shall
189 | continue and survive.
190 |
191 | Everyone is permitted to copy and distribute copies of this Agreement, but in
192 | order to avoid inconsistency the Agreement is copyrighted and may only be
193 | modified in the following manner. The Agreement Steward reserves the right to
194 | publish new versions (including revisions) of this Agreement from time to
195 | time. No one other than the Agreement Steward has the right to modify this
196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The
197 | Eclipse Foundation may assign the responsibility to serve as the Agreement
198 | Steward to a suitable separate entity. Each new version of the Agreement will
199 | be given a distinguishing version number. The Program (including
200 | Contributions) may always be distributed subject to the version of the
201 | Agreement under which it was received. In addition, after a new version of
202 | the Agreement is published, Contributor may elect to distribute the Program
203 | (including its Contributions) under the new version. Except as expressly
204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or
205 | licenses to the intellectual property of any Contributor under this
206 | Agreement, whether expressly, by implication, estoppel or otherwise. All
207 | rights in the Program not expressly granted under this Agreement are
208 | reserved.
209 |
210 | This Agreement is governed by the laws of the State of Washington and the
211 | intellectual property laws of the United States of America. No party to this
212 | Agreement will bring a legal action under this Agreement more than one year
213 | after the cause of action arose. Each party waives its rights to a jury trial
214 | in any resulting litigation.
215 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # stch.sql
2 |
3 | [](https://clojars.org/stch-library/sql)
4 |
5 | A DSL in Clojure for SQL query, DML, and DDL. Supports a majority of MySQL's statements.
6 |
7 | Based on code from [Honey SQL](https://github.com/jkk/honeysql) and ideas from [Lobos](http://budu.github.io/lobos/) and [SQLingvo](https://github.com/r0man/sqlingvo). Many thanks to the authors of those libraries.
8 |
9 | ## Installation
10 |
11 | Add the following to your project dependencies:
12 |
13 | ```clojure
14 | [stch-library/sql "0.1.1"]
15 | ```
16 |
17 | ## API Documentation
18 |
19 | http://stch-library.github.io/sql
20 |
21 | Note: This library uses [stch.schema](https://github.com/stch-library/schema). Please refer to that project page for more information regarding type annotations and their meaning.
22 |
23 | ## How to use
24 |
25 | This library is split into two distinct offerings.
26 |
27 | 1. Query and DML
28 | 2. DDL
29 |
30 | Query and DML functions are in stch.sql, accompanied by stch.sql.format. DDL functions are in stch.sql.ddl.
31 |
32 | Below is a small sampling of what you can do with this library. Please see the unit-tests in the spec directory for a comprehensive look at what's possible.
33 |
34 | ### Query
35 |
36 | Queries are composed of threaded fn calls, producing a map, which when formatted will produce a JDBC compatible vector.
37 |
38 | ```clojure
39 | (require '[stch.sql.format :as sql]
40 | '[stch.sql :refer :all])
41 |
42 | (-> (select :*)
43 | (from :foo)
44 | (where '(= firstName "Billy"))
45 | sql/format)
46 | ; ["SELECT * FROM foo WHERE firstName = ?" "Billy"]
47 | ```
48 |
49 | If you are using [clojure.jdbc](https://github.com/niwibe/clojure.jdbc), you can extend the ISQLStatement protocol, so that you don't have to manually call sql/format.
50 |
51 | ```clojure
52 | (require '[jdbc.types :as types])
53 |
54 | (extend-protocol types/ISQLStatement
55 | clojure.lang.APersistentMap
56 | (normalize [this conn options]
57 | (types/normalize (sql/format this) conn options)))
58 |
59 | (let [id 1234
60 | sql (-> (select :*)
61 | (from :users)
62 | (where `(= userID ~id)))
63 | result (query conn sql {:identifiers identity})]
64 | (-> result first))
65 | ```
66 |
67 | SELECT
68 |
69 | ```clojure
70 | (-> (select :*)
71 | sql/format)
72 | ; ["SELECT *"]
73 |
74 | ; Dashes to underscores
75 | (-> (select :first-name)
76 | sql/format)
77 | ; ["SELECT first_name"]
78 |
79 | ; NULL
80 | (-> (select nil)
81 | sql/format)
82 | ; ["SELECT NULL"]
83 |
84 | ; Aliased table name
85 | (-> (select [:firstName :name])
86 | sql/format)
87 | ; ["SELECT firstName AS name"]
88 |
89 | ; Modifiers
90 | (-> (select :id)
91 | (modifiers :distinct)
92 | (from :users)
93 | sql/format)
94 | ; ["SELECT DISTINCT id FROM users"]
95 | ```
96 |
97 | Functions
98 |
99 | ```clojure
100 | ; Prefix
101 | (-> (select '(now))
102 | sql/format)
103 | ; ["SELECT now()"]
104 |
105 | ; Infix
106 | (-> (select '(<> 1 2)) sql/format)
107 | ; ["SELECT 1 <> 2"]
108 |
109 | ; Convenience shorthand
110 | (-> (select '(count-distinct id))
111 | sql/format)
112 | ; ["SELECT COUNT(DISTINCT id)"]
113 | ```
114 |
115 | WHERE clause
116 |
117 | ```clojure
118 | ; Implicit AND
119 | (-> (select :*)
120 | (from :users)
121 | (where '(= id 5)
122 | '(= status "active"))
123 | sql/format)
124 | ; ["SELECT * FROM users WHERE (id = 5 AND status = ?)" "active"]
125 |
126 | ; OR
127 | (-> (select :*)
128 | (from :users)
129 | (where '(or (= id 5)
130 | (= status "active")))
131 | sql/format)
132 | ; ["SELECT * FROM users WHERE (id = 5 OR status = ?)" "active"]
133 | ```
134 |
135 | Parameters
136 |
137 | ```clojure
138 | ; Named
139 | (-> (select :*)
140 | (from :users)
141 | (where '(= name ?name)
142 | '(= userID ?userID))
143 | (sql/format :params {:name "Billy"
144 | :userID 3}))
145 | ; ["SELECT * FROM users WHERE (name = ? AND userID = ?)" "Billy" 3]
146 |
147 | ; Sequential
148 | (-> (select :*)
149 | (from :users)
150 | (where '(= name ?name)
151 | '(= userID ?userID))
152 | (sql/format :params ["Billy" 3]))
153 | ; ["SELECT * FROM users WHERE (name = ? AND userID = ?)" "Billy" 3]
154 |
155 | ; Unnamed
156 | (-> (select :*)
157 | (from :users)
158 | (where '(= name ?)
159 | '(= userID ?))
160 | (sql/format :params ["Billy" 3]))
161 | ; ["SELECT * FROM users WHERE (name = ? AND userID = ?)" "Billy" 3]
162 |
163 | ; Spliced
164 | (def n "Billy")
165 |
166 | (-> (select :*)
167 | (from :foo)
168 | (where `(= name ~n))
169 | sql/format)
170 | ; ["SELECT * FROM foo WHERE name = ?" "Billy"]
171 | ```
172 |
173 | JOIN: join, left-join, right-join
174 |
175 | ```clojure
176 | (-> (select :*)
177 | (from :users)
178 | (join :contacts
179 | '(= users.id contacts.id))
180 | sql/format)
181 | ; ["SELECT * FROM users INNER JOIN contacts ON users.id = contacts.id"]
182 |
183 | ; Aliased table name
184 | (-> (select :*)
185 | (from :foo)
186 | (join :bar '(= foo.x bar.x)
187 | [:baz :b] '(= bar.x b.x))
188 | sql/format)
189 | ; ["SELECT * FROM foo INNER JOIN bar ON foo.x = bar.x INNER JOIN baz AS b ON bar.x = b.x"]
190 | ```
191 |
192 | ORDER BY
193 |
194 | ```clojure
195 | (-> (select :*)
196 | (from :users)
197 | (order-by :name :age)
198 | sql/format)
199 | ; ["SELECT * FROM users ORDER BY name, age"]
200 |
201 | ; DESC
202 | (-> (select :*)
203 | (from :users)
204 | (order-by (desc :name))
205 | sql/format)
206 | ; ["SELECT * FROM users ORDER BY name DESC"]
207 | ```
208 |
209 | GROUP BY
210 |
211 | ```clojure
212 | (-> (select :*)
213 | (from :users)
214 | (group :name :age)
215 | sql/format)
216 | ; ["SELECT * FROM users GROUP BY name, age"]
217 | ```
218 |
219 | HAVING
220 |
221 | ```clojure
222 | (-> (select :*)
223 | (from :users)
224 | (having '(> (count email) 2))
225 | sql/format)
226 | ; ["SELECT * FROM users HAVING count(email) > 2"]
227 | ```
228 |
229 | LIMIT
230 |
231 | ```clojure
232 | (-> (select :*)
233 | (from :users)
234 | (limit 50)
235 | sql/format)
236 | ; ["SELECT * FROM users LIMIT 50"]
237 |
238 | ; OFFSET
239 | (-> (select :*)
240 | (from :users)
241 | (limit 50)
242 | (offset 50)
243 | sql/format)
244 | ; ["SELECT * FROM users LIMIT 50 OFFSET 50"]
245 | ```
246 |
247 | Subqueries
248 |
249 | ```clojure
250 | (-> (select :*)
251 | (from :users)
252 | (where `(in id
253 | ~(-> (select :userid)
254 | (from :contacts))))
255 | sql/format)
256 | ; ["SELECT * FROM users WHERE (id IN (SELECT userid FROM contacts))"]
257 | ```
258 |
259 | UNION
260 |
261 | ```clojure
262 | (sql/format
263 | (union (-> (select :name :email)
264 | (from :users))
265 | (-> (select :name :email)
266 | (from :deleted-users))))
267 | ; ["(SELECT name, email FROM users) UNION (SELECT name, email FROM deleted_users)"]
268 | ```
269 |
270 | Order doesn't matter
271 |
272 | ```clojure
273 | (-> (where '(= userid 1234))
274 | (from :users)
275 | (order-by :first-name :last-name)
276 | (select :first-name :last-name)
277 | sql/format)
278 | ; ["SELECT first_name, last_name FROM users WHERE userid = 1234 ORDER BY first_name, last_name"]
279 | ```
280 |
281 | Composition
282 |
283 | select, from, join, left-join, right-join, where, having, group, and order-by are compositional by design. The way in which each composes should be fairly intuitive. Here are some examples.
284 |
285 | ```clojure
286 | (def query
287 | (-> (select :first-name)
288 | (from :users)
289 | (join :contacts '(= users.cid contacts.cid))
290 | (where '(= id 5))
291 | (group :first-name)
292 | (order-by :first-name)))
293 |
294 | (-> query
295 | (select :last-name)
296 | (join :perms '(= users.uid perms.uid))
297 | (where '(= status "active"))
298 | (group :last-name)
299 | (order-by :last-name)
300 | sql/format)
301 | ; ["SELECT first_name, last_name FROM users INNER JOIN contacts ON users.cid = contacts.cid INNER JOIN perms ON users.uid = perms.uid WHERE (id = 5 AND status = ?) GROUP BY first_name, last_name ORDER BY first_name, last_name" "active"]
302 | ```
303 |
304 | ### DML
305 |
306 | INSERT
307 |
308 | ```clojure
309 | ; Vector of maps
310 | (-> (insert-into :users)
311 | (values [{:name "Billy" :age 35}
312 | {:name "Joey" :age 37}])
313 | sql/format)
314 | ; ["INSERT INTO users (age, name) VALUES (35, ?), (37, ?)" "Billy" "Joey"]
315 |
316 | ; Vector of vectors
317 | (-> (insert-into :users)
318 | (values [["Billy" 35]["Joey" 37]])
319 | sql/format)
320 | ; ["INSERT INTO users VALUES (?, 35), (?, 37)" "Billy" "Joey"]
321 |
322 | ; ON DUPLICATE KEY
323 | (-> (insert-into :foo)
324 | (columns :a :b :c)
325 | (values [[1 2 3]])
326 | (on-dup-key {:c 9})
327 | sql/format)
328 | ; ["INSERT INTO foo (a, b, c) VALUES (1, 2, 3) ON DUPLICATE KEY UPDATE c = 9"]
329 | ```
330 |
331 | INSERT/SELECT
332 |
333 | ```clojure
334 | (-> (insert-into :foo)
335 | (columns :a :b :c)
336 | (select :x.a :y.b :z.c)
337 | (from :x)
338 | (join :y '(= x.id y.id)
339 | :z '(= y.id z.id))
340 | sql/format)
341 | ; ["INSERT INTO foo (a, b, c) SELECT x.a, y.b, z.c FROM x INNER JOIN y ON x.id = y.id INNER JOIN z ON y.id = z.id"]
342 | ```
343 |
344 | UPDATE
345 |
346 | ```clojure
347 | (-> (update :users)
348 | (setv {:name "Billy", :age 35})
349 | (where '(= id 234))
350 | sql/format)
351 | ; ["UPDATE users SET age = 35, name = ? WHERE id = 234" "Billy"]
352 | ```
353 |
354 | DELETE
355 |
356 | ```clojure
357 | (-> (delete-from :foo)
358 | (where '(= email "billy@bob.com"))
359 | sql/format)
360 | ; ["DELETE FROM foo WHERE email = ?" "billy@bob.com"]
361 |
362 | ; Multiple tables
363 | (-> (delete-from :t1)
364 | (using :t1 :t2)
365 | (where '(= t1.x t2.x)
366 | '(= t2.y 3))
367 | sql/format)
368 | ; ["DELETE FROM t1 USING t1, t2 WHERE (t1.x = t2.x AND t2.y = 3)"]
369 | ```
370 |
371 | REPLACE (same behavior as insert)
372 |
373 | ```clojure
374 | (-> (replace-into :users)
375 | (values [{:name "Billy" :age 35}
376 | {:name "Joey" :age 37}])
377 | sql/format)
378 | ; ["REPLACE INTO users (age, name) VALUES (35, ?), (37, ?)" "Billy" "Joey"]
379 | ```
380 |
381 | ### Quoting
382 |
383 | Quote style to use for identifiers. Options include:
384 |
385 | 1. :ansi (PostgreSQL)
386 | 2. :mysql
387 | 3. :sqlserver
388 | 4. :oracle
389 |
390 | Defaults to no quoting.
391 |
392 | ```clojure
393 | (-> (select :users.name
394 | :contacts.*
395 | '(date_format dob "%m/%d/%Y"))
396 | (from :users)
397 | (join :contacts
398 | '(= users.id contacts.userid))
399 | (where '(in users.status ["active"
400 | "pending"]))
401 | (group :users.status)
402 | (order-by (asc :contacts.last-name))
403 | (limit 25)
404 | (sql/format :quoting :mysql))
405 | ; ["SELECT `users`.`name`, `contacts`.*, date_format(`dob`, ?) FROM `users` INNER JOIN `contacts` ON `users`.`id` = `contacts`.`userid` WHERE (`users`.`status` IN (?, ?)) GROUP BY `users`.`status` ORDER BY `contacts`.`last_name` ASC LIMIT 25" "%m/%d/%Y" "active" "pending"]
406 | ```
407 |
408 | ### DDL
409 |
410 | The two primary functions are create and alt, which take a table record and produce a SQL string.
411 |
412 | #### CREATE
413 |
414 | ```clojure
415 | (use 'stch.sql.ddl)
416 |
417 | (create
418 | (-> (table :users)
419 | (integer :userID :unsigned :not-null)
420 | (integer :orgID)
421 | (set' :groups ["user" "admin"] (default "user"))
422 | (enum :status ["active" "inactive"])
423 | (decimal :ranking '(3 1) (default 0))
424 | (varchar :username [50])
425 | (chr :countryCode [2] (default "US"))
426 | (primary-key :userID)
427 | (index [:userID :orgID])
428 | (unique :username)
429 | (foreign-key :orgID '(orgs orgID) :on-delete-cascade))
430 | (engine :InnoDB)
431 | (collate :utf8-general-ci))
432 | ; "CREATE TABLE users (userID INT UNSIGNED NOT NULL, orgID INT, groups SET('user', 'admin') DEFAULT 'user', status ENUM('active', 'inactive'), ranking DECIMAL(3, 1) DEFAULT 0, username VARCHAR(50), countryCode CHAR(2) DEFAULT 'US', PRIMARY KEY(userID), INDEX(userID, orgID), UNIQUE(username), FOREIGN KEY(orgID) REFERENCES orgs(orgID) ON DELETE CASCADE) ENGINE=InnoDB, COLLATE=utf8_general_ci"
433 | ```
434 |
435 | All column types have a corresponding function. See API for details.
436 |
437 | ```clojure
438 | (create
439 | (-> (table :users)
440 | (chr :countryCode [2])))
441 | ; "CREATE TABLE users (countryCode CHAR(2))"
442 | ```
443 |
444 | INDEX
445 |
446 | ```clojure
447 | (create
448 | (-> (table :users)
449 | (integer :user_id)
450 | (index :user_id)))
451 | ; "CREATE TABLE users (user_id INT, INDEX(user_id))"
452 |
453 | ; Multiple columns
454 | (create
455 | (-> (table :users)
456 | (varchar :first_name [100])
457 | (varchar :last_name [100])
458 | (index [:first_name :last_name])))
459 | ; "CREATE TABLE users (first_name VARCHAR(100), last_name VARCHAR(100), INDEX(first_name, last_name))"
460 |
461 | ; FOREIGN KEY
462 | (create
463 | (-> (table :contacts)
464 | (integer :user_id)
465 | (foreign-key :user_id '(users user_id) :on-delete-cascade)))
466 | ; "CREATE TABLE contacts (user_id INT, FOREIGN KEY(user_id) REFERENCES users(user_id) ON DELETE CASCADE)"
467 |
468 | ; Named key
469 | (create
470 | (-> (table :users)
471 | (varchar :username [50])
472 | (constraint :uname (unique :username))))
473 | ; "CREATE TABLE users (username VARCHAR(50), CONSTRAINT uname UNIQUE(username))"
474 | ```
475 |
476 | Table Options
477 |
478 | ```clojure
479 | (create
480 | (-> (table :users)
481 | (varchar :username [50]))
482 | (engine :InnoDB)
483 | (character-set :utf8))
484 | ; "CREATE TABLE users (username VARCHAR(50)) ENGINE=InnoDB, CHARACTER SET=utf8"
485 | ```
486 |
487 | Appending
488 |
489 | ```clojure
490 | (defcolumns cols
491 | (-> (integer :user-id :unsigned :not-null)
492 | (index :user-id)))
493 |
494 | (create
495 | (-> (table :users)
496 | (append cols)
497 | (varchar :username [50])))
498 | ; "CREATE TABLE users (user_id INT UNSIGNED NOT NULL, INDEX(user_id), username VARCHAR(50))"
499 | ```
500 |
501 | TEMPORARY TABLE
502 |
503 | ```clojure
504 | (create
505 | (-> (temp-table :users)
506 | (integer :userID)))
507 | ; "CREATE TEMPORARY TABLE users (userID INT)"
508 | ```
509 |
510 | #### ALTER
511 |
512 | ```clojure
513 | (alt
514 | (-> (table :users)
515 | (add (varchar :email [50]) (after :userID))
516 | (add (varchar :firstName [25]) :first)
517 | (add (index [:firstName :lastName]))
518 | (add (index '(username ranking)))
519 | (add (foreign-key :orgID '(orgs orgID) :on-delete-cascade))
520 | (change :username (varchar :username [100]))
521 | (drop-default :ranking)
522 | (set-default :ranking 1)
523 | (drop-column :countryCode)
524 | (drop-index :uname)
525 | (drop-primary-key)
526 | (drop-foreign-key :fk1)))
527 | ; "ALTER TABLE users ADD COLUMN email VARCHAR(50) AFTER userID, ADD COLUMN firstName VARCHAR(25) FIRST, ADD INDEX(firstName, lastName), ADD INDEX(username, ranking), ADD FOREIGN KEY(orgID) REFERENCES orgs(orgID) ON DELETE CASCADE, CHANGE username username VARCHAR(100), ALTER COLUMN ranking DROP DEFAULT, ALTER COLUMN ranking SET DEFAULT 1, DROP COLUMN countryCode, DROP INDEX uname, DROP PRIMARY KEY, DROP FOREIGN KEY fk1"
528 | ```
529 |
530 | ADD
531 |
532 | ```clojure
533 | ; AFTER
534 | (alt
535 | (-> (table :users)
536 | (add (varchar :email [50]) (after :userID))))
537 | ; "ALTER TABLE users ADD COLUMN email VARCHAR(50) AFTER userID"
538 |
539 | ; FIRST
540 | (alt
541 | (-> (table :users)
542 | (add (varchar :email [50]) :first)))
543 | ; "ALTER TABLE users ADD COLUMN email VARCHAR(50) FIRST"
544 |
545 | ; INDEX
546 | (alt
547 | (-> (table :users)
548 | (add (index :firstName))))
549 | ; "ALTER TABLE users ADD INDEX(firstName)"
550 | ```
551 |
552 | CHANGE
553 |
554 | ```clojure
555 | (alt
556 | (-> (table :users)
557 | (change :username (varchar :username [100]))))
558 | ; "ALTER TABLE users CHANGE username username VARCHAR(100)"
559 | ```
560 |
561 | SET DEFAULT
562 |
563 | ```clojure
564 | (alt
565 | (-> (table :users)
566 | (set-default :ranking 1)))
567 | ; "ALTER TABLE users ALTER COLUMN ranking SET DEFAULT 1"
568 | ```
569 |
570 | DROP COLUMN
571 |
572 | ```clojure
573 | (alt
574 | (-> (table :users)
575 | (drop-column :username)))
576 | ; "ALTER TABLE users DROP COLUMN username"
577 | ```
578 |
579 | ## Unit-tests
580 |
581 | Run "lein spec"
582 |
--------------------------------------------------------------------------------
/doc/css/default.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: sans-serif;
3 | font-size: 11pt;
4 | }
5 |
6 | pre, code {
7 | font-family: Monaco, DejaVu Sans Mono, Consolas, monospace;
8 | font-size: 9pt;
9 | }
10 |
11 | h2 {
12 | font-weight: normal;
13 | font-size: 18pt;
14 | margin: 10px 0 0.4em 0;
15 | }
16 |
17 | #header, #content, .sidebar {
18 | position: fixed;
19 | }
20 |
21 | #header {
22 | top: 0;
23 | left: 0;
24 | right: 0;
25 | height: 20px;
26 | background: #444;
27 | color: #fff;
28 | padding: 5px;
29 | }
30 |
31 | #content {
32 | top: 30px;
33 | right: 0;
34 | bottom: 0;
35 | overflow: auto;
36 | background: #fff;
37 | color: #333;
38 | padding: 0 1em;
39 | }
40 |
41 | .sidebar {
42 | position: fixed;
43 | top: 30px;
44 | bottom: 0;
45 | overflow: auto;
46 | }
47 |
48 | #namespaces {
49 | background: #e6e6e6;
50 | border-right: solid 1px #bbb;
51 | left: 0;
52 | width: 250px;
53 | }
54 |
55 | #vars {
56 | background: #eeeeee;
57 | border-right: solid 1px #ccc;
58 | left: 251px;
59 | width: 200px;
60 | }
61 |
62 | .namespace-index {
63 | left: 251px;
64 | }
65 |
66 | .namespace-docs {
67 | left: 452px;
68 | }
69 |
70 | #header {
71 | background: -moz-linear-gradient(top, #555 0%, #222 100%);
72 | background: -webkit-linear-gradient(top, #555 0%, #333 100%);
73 | background: -o-linear-gradient(top, #555 0%, #222 100%);
74 | background: -ms-linear-gradient(top, #555 0%, #222 100%);
75 | background: linear-gradient(top, #555 0%, #222 100%);
76 | box-shadow: 0 0 10px #555;
77 | z-index: 100;
78 | }
79 |
80 | #header h1 {
81 | margin: 0;
82 | padding: 0;
83 | font-size: 12pt;
84 | font-weight: normal;
85 | text-shadow: -1px -1px 0px #333;
86 | }
87 |
88 | #header a, .sidebar a {
89 | display: block;
90 | text-decoration: none;
91 | }
92 |
93 | #header a {
94 | color: #fff;
95 | }
96 |
97 | .sidebar a {
98 | color: #333;
99 | }
100 |
101 | #header h2 {
102 | float: right;
103 | font-size: 9pt;
104 | font-weight: normal;
105 | margin: 3px 3px;
106 | color: #bbb;
107 | }
108 |
109 | #header h2 a {
110 | display: inline;
111 | }
112 |
113 | .sidebar h3 {
114 | margin: 0;
115 | padding: 10px 0.5em 0 0.5em;
116 | font-size: 14pt;
117 | font-weight: normal
118 | }
119 |
120 | .sidebar ul {
121 | padding: 0.5em 0em;
122 | margin: 0;
123 | }
124 |
125 | .sidebar li {
126 | display: block;
127 | }
128 |
129 | .sidebar li a {
130 | padding: 7px 10px;
131 | }
132 |
133 | #namespaces li.current a {
134 | border-left: 3px solid #a33;
135 | padding-left: 7px;
136 | color: #a33;
137 | }
138 |
139 | #vars li.current a {
140 | border-left: 3px solid #33a;
141 | padding-left: 7px;
142 | color: #33a;
143 | }
144 |
145 | #content h3 {
146 | margin-bottom: 0.5em;
147 | font-size: 13pt;
148 | font-weight: bold;
149 | }
150 |
151 | .public h3, h4.macro {
152 | margin: 0;
153 | float: left;
154 | }
155 |
156 | .usage {
157 | clear: both;
158 | }
159 |
160 | h4.macro {
161 | font-variant: small-caps;
162 | font-size: 13px;
163 | font-weight: bold;
164 | color: #717171;
165 | margin-top: 3px;
166 | margin-left: 10px;
167 | }
168 |
169 | .public {
170 | margin-top: 1.5em;
171 | margin-bottom: 2.0em;
172 | }
173 |
174 | .public:last-child {
175 | margin-bottom: 20%;
176 | }
177 |
178 | .namespace:last-child {
179 | margin-bottom: 10%;
180 | }
181 |
182 | .index {
183 | padding: 0;
184 | }
185 |
186 | .index * {
187 | display: inline;
188 | }
189 |
190 | .index li {
191 | padding: 0 .5em;
192 | }
193 |
194 | .index ul {
195 | padding-left: 0;
196 | }
197 |
198 | .usage code {
199 | display: block;
200 | color: #008;
201 | }
202 |
203 | .doc {
204 | margin-bottom: .5em;
205 | }
206 |
207 | .src-link a {
208 | font-size: 9pt;
209 | }
210 |
--------------------------------------------------------------------------------
/doc/index.html:
--------------------------------------------------------------------------------
1 |
2 |
Takes a SQL map and optional input parameters and returns a vector
7 | of a SQL string and parameters, as expected by clojure.java.jdbc.
8 |
9 | Input parameters will be filled into designated spots according to
10 | name (if a map is provided) or by position (if a sequence is provided).
11 |
12 | Instead of passing parameters, you can use keyword arguments:
13 | :params - input parameters
14 | :quoting - quote style to use for identifiers; one of :ansi (PostgreSQL),
15 | :mysql, :sqlserver, or :oracle. Defaults to no quoting.
16 | :return-param-names - when true, returns a vector of
17 | [sql-str param-values param-names]