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
// Compile README.docify.md to README.md
compile_markdown!;
pub use *;
pub use ;
/// Driver-facing traits and helper types.
///
/// This module re-exports the low-level driver traits and capability markers used when
/// implementing a custom backend. Most application code will use the concrete drivers (like
/// [`Postgres`] or [`Sqlite`]) rather than these internals.
/// Type-safe SQL macro that builds and executes a query with compile-time checks.
///
/// Validates table/column names, binds arguments, and executes immediately, returns awaitable [anyhow](https://crates.io/crates/anyhow)::Result.
///
/// Notes:
/// - For INSERT/UPDATE/DELETE without `RETURNING`, the output is driver-specific (generally the
/// number of rows affected).
/// - Input syntax highlighting is applied in IDE's, but on documentation page it is not.
///
/// ## Syntax
/// ```rust,ignore
/// query!(<Driver> conn, SQL)
/// ```
///
/// - `<Driver>` is optional, if omitted the driver is inferred from `conn`.
/// - `conn` is generally a connection or transaction implementing [`EasyExecutor`], available for
/// mutable easy-sql connections/transactions and compatible sqlx executor types. The macro generates
/// a mutable borrow internally.
///
/// Example:
///
/// - SQL keywords are case-insensitive.
/// - `{value}` inserts an external Rust value as a bound argument.
/// - See below for more info about the accepted SQL.
///
/// ## Query forms
///
/// ### SELECT
/// `SELECT OutputType FROM TableType ...` returns `OutputType`, a single row implementing [`Output`].
/// The `Output` trait also covers `Vec<T>` and `Option<T>` for multiple or optional rows.
///
/// Use `Table.column` or `OutputType.column` for column references. With the
/// `use_output_columns` feature, bare column names are validated against the output type instead of the Table type.
///
/// Accepted Clauses: `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`, `LIMIT`, `DISTINCT`
///
/// ### INSERT
/// `INSERT INTO TableType VALUES {data}` inserts one value or a collection. `{data}` must implement [`Insert`].
///
/// Use `RETURNING OutputType` to return inserted data, OutputType needs to implement [`Output`].
///
///
/// ### UPDATE
/// `UPDATE TableType SET {update}` uses a struct implementing [Update], or
/// `SET field = value` for inline updates.
///
/// Use `RETURNING OutputType` to return rows, OutputType needs to implement [`Output`].
///
/// Accepted Clauses: `WHERE`, `RETURNING`
///
/// ### DELETE
/// `DELETE FROM TableType ...` removes rows.
///
/// Use `RETURNING OutputType` to return rows, OutputType needs to implement [`Output`]
///
/// Accepted Clauses: `WHERE`, `RETURNING`
///
/// ### EXISTS
/// `EXISTS TableType WHERE ...` returns `bool`.
///
/// Accepted Clauses: `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`, `LIMIT`
///
/// ### Table joins
/// Use [`table_join!`](crate::table_join) to define joins, then reference joined columns with
/// `JoinedTable.column`.
///
/// ### SQL functions
/// Built-in functions (like `COUNT`, `SUM`, `LOWER`) are available, and custom ones can be
/// registered with [`custom_sql_function!`](crate::custom_sql_function).
///
/// ### `IN {vec}` parameter binding
/// `IN {vec}` expands placeholders at runtime. The value must implement `IntoIterator` and
/// `len()` (e.g., `Vec<T>`, `&[T]`). Use `IN {&vec}` if you need to reuse the collection.
///
/// ## Generic connection
/// `*conn` syntax might be needed when using `&mut EasyExecutor<D>` as connection
pub use query;
/// Type-safe SQL macro that builds a lazy query and returns a stream on execution.
///
/// Like [`query!`], this macro validates table/column names and binds arguments at compile time,
/// but it does **not** execute immediately. Instead it returns a lazy query builder that can be
/// stored, moved, and executed later.
///
/// `?` (handling result) is required to build the lazy query.
///
/// ## Syntax
/// ```rust,ignore
/// query_lazy!(<Driver> SQL)
/// ```
///
/// - `<Driver>` is optional; if omitted the default driver is taken from the build script via
/// [`sql_build::build`](https://docs.rs/sql-build/latest/sql_build/fn.build.html).
/// If multiple (or zero) defaults are configured, you must specify the driver explicitly.
/// - Uses the same SQL syntax and helpers as [`query!`]
/// - There is **no connection parameter** in the macro call; pass it when fetching.
///
/// ### Return value
/// returns a `anyhow::Result<LazyQueryResult>` with the following method:
/// - `fetch(impl EasyExecutorInto)`
/// - with a generic `conn: &mut impl EasyExecutor`, use `fetch(&mut *conn)` when you need to
/// use `conn` again later in the same scope
/// - on the final use in that scope, `fetch(conn)` is valid and shorter
/// - otherwise pass a connection or transaction directly (e.g., `fetch(conn)` or `fetch(&mut transaction)`)
///
/// Both return `futures::Stream<Item = anyhow::Result<Output>>`. The stream borrows the
/// connection; drop or fully consume it before reusing the connection.
///
/// ### Output and query forms
/// - Output must be a **single-row type** implementing [`Output`]. To return multiple rows,
/// iterate/collect the stream yourself.
/// - Supported query forms: `SELECT`, `INSERT`, `UPDATE`, `DELETE`.
/// - `INSERT`/`UPDATE`/`DELETE` **must** include `RETURNING` (because results are streamed).
/// - `EXISTS` is **not** supported; use [`query!`] instead.
///
/// ## Examples
pub use query_lazy;
/// Defines a SQL table schema.
///
/// Implements [`Table`], [`DatabaseSetup`], [`Output`], [`Insert`], and [`Update`] for the struct,
/// for usage inside of `query!` macros. Table names default to the struct
/// name converted to `snake_case`.
///
/// ## Basic usage
///
/// ## Field attributes
/// - `#[sql(primary_key)]` marks a column as part of the primary key.
/// - `#[sql(auto_increment)]` enables auto-increment for the column (driver-dependent).
/// - `#[sql(unique)]` adds a `UNIQUE` constraint.
/// - `#[sql(default = expr)]` sets a column default (the expression is type-checked).
/// - `#[sql(bytes)]` stores the field as a binary blob using [`bincode`](https://crates.io/crates/bincode) + [`serde`](https://crates.io/crates/serde).
/// - `#[sql(foreign_key = TableStruct)]` creates a foreign key to another table.
/// - `#[sql(foreign_key = TableStruct, cascade)]` enables `ON DELETE/UPDATE CASCADE`.
///
/// `Option<T>` fields are treated as nullable; all other fields are `NOT NULL` by default.
///
/// ### Foreign keys
///
/// ### Composite primary keys
///
/// ## Table attributes
/// - `#[sql(table_name = "...")]` overrides the generated `snake_case` name.
/// - `#[sql(drivers = Driver1, Driver2)]` sets the supported drivers when no default driver is
/// configured in the build script via
/// [`sql_build::build`](https://docs.rs/sql-build/latest/sql_build/fn.build.html).
/// - `#[sql(no_version)]` disables migrations for this table (feature `migrations`).
/// - `#[sql(version = 1)]` enables migrations and sets the table version (feature `migrations`).
/// - `#[sql(unique_id = "...")]` is auto generated and used by the build script for migration tracking.
/// - `#[sql(version_test = 1)]` sets a temporary version for migration testing, requires `unique_id`.
///
/// ## Notes
/// - Some drivers require at least one primary key; if none is specified, compilation will fail.
/// - Auto-increment may be restricted when using composite primary keys, depending on the driver.
/// - `#[sql(bytes)]` requires the field type to implement [`serde::Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html)/[`Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html).
pub use Table;
/// Defines insertable data for a table.
///
/// Implements [`Insert`] for the `Struct` and `&Struct`, for use in [`query!`](crate::query) and [`query_lazy!`](crate::query_lazy).
/// Field names map to table columns, and you can provide a subset of columns as long as the
/// missing ones are declared as defaults.
///
/// ## Basic usage
///
/// ## Defaults for omitted columns
/// Use `#[sql(default = field1, field2)]` to declare table columns that are **not** present in the
/// insert struct (for example, auto-increment primary keys or columns with SQL defaults). All
/// omitted columns must be listed so the macro can validate the table schema at compile time.
///
/// ## Field attributes
/// - `#[sql(bytes)]` must match `#[sql(bytes)]` on table struct, stores the field as a binary blob using [`bincode`](https://crates.io/crates/bincode) + [`serde`](https://crates.io/crates/serde).
///
/// ## Notes
/// - `#[sql(table = TableStruct)]` is required and must point to a [`Table`] type.
/// - You can insert a single value, borrow or a collection (`&T`, `Vec<T>`, `&Vec<T>`, `&[T]`).
pub use Insert;
/// Defines a SQL output mapping.
///
/// Implements [`Output`] for the struct, enabling type-safe selection and decoding of rows in
/// [`query!`] and [`query_lazy!`]. Column names are validated at compile time against the table
/// or joined tables.
///
/// ## Basic usage
///
/// ## Custom select expressions
/// Use `#[sql(select = ...)]` to map a field to a SQL expression. The expression is emitted into
/// the `SELECT` list with an alias matching the field name.
///
/// ### Custom select arguments
/// Use `{arg0}`, `{arg1}`, ... inside `#[sql(select = ...)]` and pass arguments in the query as
/// `SELECT OutputType(arg0, arg1) ...` or `RETURNING OutputType(arg0, arg1)`.
///
/// ## Joined output fields
/// For [`table_join!`](crate::table_join) results, map fields to joined columns with `#[sql(field = Table.column)]` or `#[sql(select = ...)]`.
///
/// ## Field attributes
/// - `#[sql(select = ...)]` maps the field to a custom SQL expression.
/// - `#[sql(field = Table.column)]` maps the field to a joined table column.
/// - `#[sql(bytes)]` decodes the field from binary data (matches table field settings).
///
/// ## Table attributes
/// - `#[sql(table = TableStruct)]` is required and sets the base table for validation.
///
/// ## Notes
/// - Output structs represent a **single row**; wrap in `Vec<T>` or `Option<T>` for multiple or
/// optional rows.
/// - With `use_output_columns`, you can reference `OutputType.column` (or bare columns) in
/// `query!` expressions.
/// - Custom select arguments must be sequential (`arg0`, `arg1`, ...).
pub use Output;
/// Defines update data for a table.
///
/// Implements [`Update`] for the struct and `&Struct`, for use in [`query!`](crate::query) and
/// [`query_lazy!`](crate::query_lazy). Field names map to table columns, and only the fields you
/// define are updated. `Option<T>` values are bound as-is, so `None` sets the column to `NULL`.
///
/// ## Basic usage
///
/// ## Partial updates
/// Define a smaller update struct to update a subset of columns. Use `&data` if you need to reuse
/// the update payload for multiple queries.
///
/// ## Field attributes
/// - `#[sql(bytes)]` must match `#[sql(bytes)]` on the table struct, stores the field as a binary
/// blob using [`bincode`](https://crates.io/crates/bincode) + [`serde`](https://crates.io/crates/serde).
/// - `#[sql(maybe_update)]` / `#[sql(maybe)]` marks an `Option<T>` field as optional: `None` skips the update while
/// `Some(value)` updates the column. For nullable columns you can also use `Option<Option<T>>`
/// to allow `Some(None)` to set `NULL`.
///
/// ## Notes
/// - `#[sql(table = TableStruct)]` is required and must point to a [`Table`] type.
pub use Update;
/// Composes database structure from nested types.
///
/// Implements [`DatabaseSetup`] by calling `setup` on each field (in order), which makes it easy
/// to group tables or other setup structs into reusable schemas.
///
/// - Works with named **or tuple** structs.
/// - Use `#[sql(drivers = Driver1, Driver2)]` to select supported drivers when no defaults are
/// configured in the build script via
/// [`sql_build::build`](https://docs.rs/sql-build/latest/sql_build/fn.build.html).
/// - Errors include the field name and type to help trace failing setup calls.
///
/// ## Basic usage
///
/// ## Nested setup groups
///
/// ## Notes
/// - Every field must implement [`DatabaseSetup`] for the selected driver(s).
/// - Setup order follows field order;
pub use DatabaseSetup;
/// Defines a joined table type for use in [`query!`](crate::query) and [`query_lazy!`](crate::query_lazy).
///
/// `table_join!` creates a lightweight type that implements [`Table`] with a generated join clause.
/// Use it as the table name in queries and as the `#[sql(table = ...)]` target for [`Output`].
///
/// ## Syntax
/// ```rust,ignore
/// table_join!(<Driver1, Driver2> JoinedTableStructName | TableA INNER JOIN TableB ON TableA.id = TableB.a_id)
/// ```
///
/// - The driver list is optional; when omitted, default drivers from the build script via
/// [`sql_build::build`](https://docs.rs/sql-build/latest/sql_build/fn.build.html) are used.
/// - Supported join types: `INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, `CROSS JOIN`.
/// - `CROSS JOIN` omits the `ON` clause.
/// - Multiple joins can be chained after the main table.
///
/// ## Output mapping
/// - Use `#[sql(field = Table.column)]` or `#[sql(select = ...)]` in [`Output`] structs.
/// - `LEFT JOIN` makes the joined table optional; map its fields as `Option<T>`.
/// - `RIGHT JOIN` makes tables to the **left** optional; map their fields as `Option<T>`.
///
/// ## Examples
pub use table_join;
/// Define a custom SQL function for use in [`query!`](crate::query) and [`query_lazy!`](crate::query_lazy).
///
/// Registers a SQL function name and argument-count validation so the query macros can parse
/// calls like `MyFunc(column, "arg")` and enforce argument counts at compile time.
///
/// ## Syntax
/// ```rust,ignore
/// custom_sql_function!(FunctionName; "SQL_FUNCTION_NAME"; 0 | 1 | 2 | Any);
/// ```
///
/// - `FunctionName`: Rust identifier used to generate the macro name.
/// - `"SQL_FUNCTION_NAME"`: SQL function name emitted in generated SQL.
/// - `args`: Argument count specification:
/// - A number (e.g., `2`) for exact argument count
/// - Multiple numbers separated by `|` (e.g., `1 | 2`) for multiple allowed counts
/// - `Any` for any number of arguments
///
/// ## Examples
///
/// ## Notes
/// - Function names are case-insensitive in queries, but the emitted SQL name preserves casing.
/// - The macro only validates SQL syntax; the function must exist in your database.
/// - `Any` disables argument-count validation; otherwise invalid counts cause a compile-time error.
pub use custom_sql_function;