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
//! The SQLite dialect for keelson.
//!
//! Four statement types, each shaped by the syntax diagrams at
//! <https://www.sqlite.org/lang.html>, plus the mods that fill them in and the
//! expression starters they are filled in with.
//!
//! ```
//! use keelson_sqlite as sqlite;
//! use keelson_sqlite::{Chain, Query, arg, quote, select};
//!
//! let q = sqlite::select((
//! select::columns((quote("id"), quote("name"))),
//! select::from(quote("users")),
//! select::where_(quote("age").gte(arg(21i32))),
//! ));
//!
//! let (sql, args) = q.build()?;
//! assert_eq!(sql, r#"SELECT "id", "name" FROM "users" WHERE ("age" >= ?1)"#);
//! assert_eq!(args, vec![keelson_core::Value::I32(21)]);
//! # Ok::<_, keelson_core::Error>(())
//! ```
//!
//! # Where this sits
//!
//! Layer 1 of keelson, for SQLite. It is a complete way to use keelson on its
//! own: it depends only on [keelson-core](https://docs.rs/keelson-core) and produces a SQL
//! string and an argument list, which you may run with any driver you like. To
//! run it through keelson, add Layer 2 ([keelson-exec](https://docs.rs/keelson-exec) plus a
//! backend such as [keelson-sqlx](https://docs.rs/keelson-sqlx)); to have typed models built
//! out of these mods, add Layers 3 and 4 ([keelson-models](https://docs.rs/keelson-models),
//! [keelson-gen](https://docs.rs/keelson-gen)). Because SQLite needs no server, it is also
//! the engine keelson's own always-on end-to-end tests run against. The whole
//! map is the [keelson](https://docs.rs/keelson) facade crate.
//!
//! # How it is put together
//!
//! The assembly rules are the ones `keelson_psql` documents, because they are
//! keelson's rather than any dialect's: **a starter is a function of one mod**, and a
//! tuple of mods is a mod; **a mod module shares its name with its starter**, so
//! `sqlite::select` is both a function and a module; **a mod is written once**,
//! generic over the `keelson_core::clause` `Has*` trait it needs; and **a raw
//! `&str` works wherever an expression does**, so `select::from("users")` writes
//! `FROM users` while `select::from(quote("users"))` writes `FROM "users"`.
//!
//! # Where SQLite is not PostgreSQL
//!
//! This crate is hand-written against SQLite's grammar rather than derived from the
//! PostgreSQL one, and the differences are load-bearing. The five worth knowing
//! before writing a query:
//!
//! 1. **A compound operand takes no parentheses.** SQLite's `compound-select-stmt`
//! is a run of bare `select-core`s, so `(SELECT 1) UNION (SELECT 2)` is a syntax
//! error. Pass a query or [`query`] to [`select::union`], never [`subquery`].
//! 2. **There is one `ORDER BY`/`LIMIT` per statement**, and in a compound it
//! belongs to the whole compound. PostgreSQL's `order_by_combined` family has
//! nothing to correspond to here.
//! 3. **`OFFSET` is part of the `LIMIT` production**, so an offset with no limit is
//! a build-time [`Error::Incomplete`].
//! 4. **`UNION ALL` is the only `ALL`.** `INTERSECT ALL` and `EXCEPT ALL` do not
//! exist, which is why [`CompoundOp`] folds `ALL` into the operator instead of
//! carrying it as a flag.
//! 5. **`VALUES (…), (…)` is a statement.** [`select::values`] and [`select::rows`]
//! fill the other alternative of `select-core`.
//!
//! Beyond those: `?1` and `:name` placeholders, `INDEXED BY`/`NOT INDEXED` on any
//! table reference, `INSERT OR REPLACE` and `UPDATE OR IGNORE`, several
//! `ON CONFLICT` clauses on one `INSERT`, `RETURNING` on all three mutations, a
//! `CROSS JOIN` that takes an `ON` — and no locking clause, no `FETCH`, no
//! `TABLESAMPLE`, no `LATERAL`, no `GROUPING SETS`, no `DISTINCT ON`, and no
//! `USING` on a `DELETE`.
//!
//! # Sub-queries
//!
//! The four query types implement [`IntoExpr`], so one goes straight into any
//! expression slot: `select::union(other)`, `select::with("c", other)`,
//! `insert::query(other)`. Those slots want the query **bare** — SQLite parenthesises
//! neither a `WITH` body's contents twice nor a compound operand at all. Where the
//! parentheses belong to the sub-query itself — a `FROM` item, a scalar
//! sub-expression, an `IN (…)` operand — use [`subquery`]. Placeholders re-index
//! across the nesting on their own, because the counter belongs to the writer.
pub use Sqlite;
pub use ;
pub use Function;
pub use SqliteOps;
pub use ;
// The core vocabulary a caller needs in order to use any of the above, re-exported
// so that a program building SQLite queries needs one dependency and one `use`.
pub use ;
pub use ;
use Cow;
use ToValue;
use expr;
// ---------------------------------------------------------------------------
// Statement starters
// ---------------------------------------------------------------------------
/// Build a `SELECT` from one mod — usually a tuple of them.
///
/// The returned query knows its own dialect, so
/// [`build()`](keelson_core::Query::build) takes no arguments.
/// Build an `INSERT` from one mod.
/// Build an `UPDATE` from one mod.
/// Build a `DELETE` from one mod.
// ---------------------------------------------------------------------------
// Expression starters
// ---------------------------------------------------------------------------
/// A whole statement, written by hand, as a runnable query.
///
/// [`raw`] is a *fragment* an expression accepts; this is a *statement* nothing
/// built. It is an ordinary [`Query`], so the execution layer's verbs work on
/// it — `fetch_all::<T>()` maps hand-written SQLite onto a struct exactly as
/// it maps a built one — and it nests as a sub-select in a built statement.
///
/// Placeholders are `?` and are rewritten to `?1` as it renders; `\?` is a
/// literal question mark. Values are bound with [`RawQuery::bind`] and never
/// reach the SQL text.
///
/// ```
/// use keelson_sqlite::{raw_query, Query as _};
///
/// let q = raw_query("SELECT id, name FROM users WHERE age >= ?").bind(21);
/// let (sql, args) = q.build()?;
/// assert_eq!(sql, "SELECT id, name FROM users WHERE age >= ?1");
/// assert_eq!(args, vec![keelson_sqlite::Value::I32(21)]);
/// # Ok::<_, keelson_sqlite::Error>(())
/// ```
/// [`raw_query`], with the values written where they bind (feature `macros`).
///
/// ```
/// # use keelson_sqlite::{sql, Query as _};
/// let min_age = 21;
/// let q = sql!("SELECT id, name FROM users WHERE age >= {min_age}");
/// let (text, args) = q.build()?;
/// assert_eq!(text, "SELECT id, name FROM users WHERE age >= ?1");
/// assert_eq!(args, vec![keelson_sqlite::Value::I32(21)]);
/// # Ok::<_, keelson_sqlite::Error>(())
/// ```
///
/// It expands to exactly that call — `raw_query("…").bind(min_age)` — so
/// nothing is hidden and the result composes like any other query. What it
/// buys is two mistakes that stop being expressible:
///
/// - **Binds cannot be transposed.** `raw_query(…).bind(a).bind(b)` with `a`
/// and `b` the wrong way round type-checks and runs; here the value is
/// written at the hole.
/// - **A question mark you typed stays a question mark.** The `?` rewriting
/// does not track quoting, so `WHERE note = 'what\?'` would otherwise hold a
/// hole, and a statement whose argument count happened to match would be
/// silently wrong. The macro escapes every `?` it did not generate.
///
/// The grammar is `format!`'s, and the analogy is exact except in one place
/// that matters: **`{x}` binds, it never interpolates.** No hole can put text
/// into the SQL. Where you do want to splice SQL — an `IN` list, a sub-query
/// — say so with `{x:sql}`, which takes an expression rather than a value:
///
/// ```
/// # use keelson_sqlite::{args, sql, Query as _};
/// let ids = args([1, 2, 3]);
/// let (text, _) = sql!("SELECT * FROM users WHERE id IN ({ids:sql})").build()?;
/// assert!(text.contains("IN ("));
/// # Ok::<_, keelson_sqlite::Error>(())
/// ```
///
/// `{{` and `}}` are literal braces. Values are still bound, not typed: for
/// SQL the schema checks, use a generated model or a `.sql` file.
pub use __sql_with;
/// Raw SQL, verbatim. `?` is left alone — see [`template`].
///
/// The progressive-enhancement entry point: a hand-written fragment goes anywhere a
/// structured expression does.
/// Raw SQL whose `?` are rewritten to `?1`, `?2`, … with `args` interleaved. Write
/// `\?` for a literal question mark.
/// A single-quoted string literal. `s("A")` renders `'A'`.
///
/// Nothing is escaped: this is for SQL the program itself wrote — a keyword, an enum
/// label, a collation name. Text from outside belongs in [`arg`], where it is bound.
/// A quoted identifier: `quote("age")` gives `"age"`, `quote(("users", "id"))` gives
/// `"users"."id"`.
/// One bound argument, rendered `?n`.
/// Several bound arguments, comma-separated and *not* parenthesised — for a slot
/// that brings its own, such as `VALUES (…)`.
/// Several bound arguments, parenthesised: `(?1, ?2, ?3)`.
/// A named parameter: `named("cutoff")` renders `:cutoff`.
///
/// SQLite is the one dialect keelson targets that has these, so this starter has no
/// counterpart in `keelson_psql`. A named parameter binds nothing and consumes no
/// positional slot — it exists so a statement can be prepared now and its values
/// supplied by whatever rebinds it.
/// `n` unbound `?n` placeholders, each binding `NULL`, so a statement can be
/// prepared now and its values supplied by whatever rebinds it.
/// A parenthesised, comma-separated list: `(a, b)`. One element gives plain
/// parentheses.
/// A function call: `f("count", "*")`, `f("row_number", ()).over(())`.
///
/// Returns keelson-sqlite's own [`Function`], which carries `DISTINCT`, the
/// aggregate `ORDER BY`, `FILTER` and `OVER` — everything SQLite hangs off a call and
/// core deliberately does not know about.
/// A `CASE` expression: `case_().when(cond, then).else_(other)`.
///
/// Named with a trailing underscore because `case` is not available as a plain
/// identifier; the SQL is unaffected.
/// `CAST(expr AS type_name)`.
///
/// SQLite has no `::` shorthand, so this is the only spelling. Not wrapped in
/// parentheses of its own: `CAST(…)` is already self-delimiting.
/// `NOT expr`. The operand is parenthesised if it needs it; the result is not,
/// because `NOT` binds looser than anything it can contain.
/// `(a AND b AND c)`.
/// `(a OR b OR c)`.