sql-macros-derive 0.6.0

Auto generate sql queries for CRUD on sqlx
Documentation
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
//! Attribute parsing for `#[table(...)]`, built on `darling`.
//!
//! This replaces the old hand-rolled `TokenTree` walker. `darling` gives us:
//! - span-accurate `syn::Error`s instead of `panic!` (via `write_errors()`)
//! - automatic support for repeated `#[table(...)]` attributes on one item
//!   (`#[darling(multiple)]`), which is how one struct can define several
//!   `select = name(fields)` style custom methods
//! - a typed field list (`darling::ast::Data`) instead of re-walking
//!   `syn::Fields` by hand in every derive
//!
//! # Breaking change vs. 0.1
//! `#[table(name = users)]` (bare identifier) is no longer accepted; use
//! `#[table(name = "users")]`. Everything else (`return_type = User`,
//! `select = method(fields)`, `as_type = "..."`, `spec_columns = "..."`,
//! `return_fields = "..."`) is unchanged.

use darling::{Error, FromDeriveInput, FromField, FromMeta, ast, util};

/// The field-list side of a custom method spec — either a plain
/// comma-separated list (always `=`, `AND`-joined — `#[table(op = ...)]`
/// doesn't apply to custom methods, only to a field's own single-field
/// methods), or a raw filter template given as a single quoted string,
/// where `$field` is *only* the bound-value placeholder (numbered by first
/// occurrence) and everything else (the column name, `=`, `OR`, `AND`,
/// `NOT`, parens, ...) is the user's own SQL, passed through unchanged. See
/// [`MethodSpec`].
#[derive(Debug, Clone)]
pub enum MethodFilterSpec {
    Fields(Vec<syn::Ident>),
    Raw(String),
}

/// `method_name(field1, field2, ...)` or `method_name("$field OR ...")` —
/// the value side of `#[table(select = get_active_user(is_active,
/// is_removed))]` or `#[table(select = search_users("$email OR $phone"))]`.
///
/// The field-list form can't be a plain string because the field names need
/// to resolve to real struct fields later (and get real spans for error
/// messages), so it's parsed as a call-shaped expression; the raw-template
/// form is a single string-literal argument instead — the only way `AND`,
/// `OR`, `NOT`, etc. can appear at all, since those aren't valid Rust
/// expression tokens.
#[derive(Debug, Clone)]
pub struct MethodSpec {
    pub method_name: syn::Ident,
    pub filter: MethodFilterSpec,
}

impl FromMeta for MethodSpec {
    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        let syn::Expr::Call(call) = expr else {
            return Err(
                Error::custom("expected `method_name(field1, field2, ...)`").with_span(expr)
            );
        };

        let syn::Expr::Path(func_path) = call.func.as_ref() else {
            return Err(Error::custom("expected a method name here").with_span(&call.func));
        };
        let method_name = func_path
            .path
            .get_ident()
            .ok_or_else(|| {
                Error::custom("method name must be a plain identifier").with_span(func_path)
            })?
            .clone();

        // A single quoted-string argument is a raw filter template
        // (`name("$email OR $phone")`) rather than a field list.
        if let [syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(s),
            ..
        })] = call.args.iter().collect::<Vec<_>>().as_slice()
        {
            return Ok(MethodSpec {
                method_name,
                filter: MethodFilterSpec::Raw(s.value()),
            });
        }

        let fields = call
            .args
            .iter()
            .map(|arg| {
                let syn::Expr::Path(field_path) = arg else {
                    return Err(Error::custom("expected a field name").with_span(arg));
                };
                field_path.path.get_ident().cloned().ok_or_else(|| {
                    Error::custom("field name must be a plain identifier").with_span(field_path)
                })
            })
            .collect::<darling::Result<Vec<_>>>()?;

        if fields.is_empty() {
            return Err(
                Error::custom("expected at least one field name in parentheses").with_span(call),
            );
        }

        Ok(MethodSpec {
            method_name,
            filter: MethodFilterSpec::Fields(fields),
        })
    }
}

/// `method_name(field1, field2, ...)` — the value side of `#[table(upsert =
/// insert_or_update_member(org_id, user_id))]`. Always a plain field list
/// (no raw-template form, unlike [`MethodSpec`] — a conflict target is just
/// a list of column names, there's no comparison/condition to write), and
/// always at least two fields: a single field's conflict target is what the
/// bare `#[table(upsert)]` flag on that field is for; this attribute exists
/// specifically for a *composite* target spanning more than one field.
#[derive(Debug, Clone)]
pub struct UpsertSpec {
    pub method_name: syn::Ident,
    pub fields: Vec<syn::Ident>,
}

impl FromMeta for UpsertSpec {
    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        let syn::Expr::Call(call) = expr else {
            return Err(
                Error::custom("expected `method_name(field1, field2, ...)`").with_span(expr)
            );
        };

        let syn::Expr::Path(func_path) = call.func.as_ref() else {
            return Err(Error::custom("expected a method name here").with_span(&call.func));
        };
        let method_name = func_path
            .path
            .get_ident()
            .ok_or_else(|| {
                Error::custom("method name must be a plain identifier").with_span(func_path)
            })?
            .clone();

        let fields = call
            .args
            .iter()
            .map(|arg| {
                let syn::Expr::Path(field_path) = arg else {
                    return Err(Error::custom("expected a field name").with_span(arg));
                };
                field_path.path.get_ident().cloned().ok_or_else(|| {
                    Error::custom("field name must be a plain identifier").with_span(field_path)
                })
            })
            .collect::<darling::Result<Vec<_>>>()?;

        if fields.len() < 2 {
            return Err(Error::custom(
                "expected at least two field names — for a single field, use `#[table(upsert)]` on that field directly instead",
            )
            .with_span(call));
        }

        Ok(UpsertSpec {
            method_name,
            fields,
        })
    }
}

/// A string that must be given as a quoted literal (`name = "users"`), with a
/// friendly, span-accurate error if someone writes a bare identifier instead
/// (the most common mistake coming from the old 0.1 syntax).
#[derive(Debug, Clone)]
pub struct QuotedString(pub String);

impl FromMeta for QuotedString {
    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        match expr {
            syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(s),
                ..
            }) => Ok(QuotedString(s.value())),
            syn::Expr::Path(p) if p.path.get_ident().is_some() => Err(Error::custom(format!(
                "expected a quoted string; write `\"{}\"` instead of `{}`",
                p.path.get_ident().unwrap(),
                p.path.get_ident().unwrap()
            ))
            .with_span(expr)),
            _ => Err(Error::custom("expected a quoted string, e.g. `\"users\"`").with_span(expr)),
        }
    }
}

/// A type given unquoted, e.g. `return_type = User` or `return_type = crate::User`.
/// Parsed from the expression's tokens since attribute values are always
/// `syn::Expr`, never `syn::Type`, at the meta-parsing layer.
#[derive(Debug, Clone)]
pub struct TypeExpr(pub syn::Type);

impl FromMeta for TypeExpr {
    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        let tokens = quote::ToTokens::to_token_stream(expr);
        syn::parse2::<syn::Type>(tokens)
            .map(TypeExpr)
            .map_err(|e| Error::custom(format!("expected a type here: {e}")).with_span(expr))
    }
}

/// The comparison operator for a filter field (`select`, `select_many`,
/// `update`, or `delete`): `#[table(select_many, op = "gt")]`. Defaults to
/// `Eq` when `op` is absent, which is the only operator that existed before
/// this attribute — every existing `#[table(select)]`-style field keeps
/// generating an `=` comparison unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operator {
    Eq,
    Gt,
    Lt,
    Gte,
    Lte,
    Like,
    /// Postgres-specific case-insensitive `LIKE`.
    Ilike,
    /// `field = ANY($n)`; the generated method takes `&[FieldType]` instead
    /// of `FieldType` for this filter.
    In,
    /// `field != ALL($n)` — the negation of `In`; also takes `&[FieldType]`.
    NotIn,
}

impl Operator {
    pub fn sql_symbol(self) -> &'static str {
        match self {
            Operator::Eq => "=",
            Operator::Gt => ">",
            Operator::Lt => "<",
            Operator::Gte => ">=",
            Operator::Lte => "<=",
            Operator::Like => "LIKE",
            Operator::Ilike => "ILIKE",
            Operator::In => unreachable!("`In` is rendered as `= ANY($n)`, not `<ident> <symbol>`"),
            Operator::NotIn => {
                unreachable!("`NotIn` is rendered as `!= ALL($n)`, not `<ident> <symbol>`")
            }
        }
    }
}

impl FromMeta for Operator {
    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        let syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(s),
            ..
        }) = expr
        else {
            return Err(Error::custom("expected a quoted operator, e.g. `op = \"gt\"`")
                .with_span(expr));
        };
        match s.value().as_str() {
            "eq" => Ok(Operator::Eq),
            "gt" => Ok(Operator::Gt),
            "lt" => Ok(Operator::Lt),
            "gte" => Ok(Operator::Gte),
            "lte" => Ok(Operator::Lte),
            "like" => Ok(Operator::Like),
            "ilike" => Ok(Operator::Ilike),
            "in" => Ok(Operator::In),
            "not_in" => Ok(Operator::NotIn),
            other => Err(Error::custom(format!(
                "unknown operator `{other}`; expected one of: eq, gt, lt, gte, lte, like, ilike, in, not_in"
            ))
            .with_span(expr)),
        }
    }
}

/// `op = "gt"` (one operator) or `op = ["gt", "lt"]` (several) — each
/// operator in the list generates its own method variant for that field
/// (`select_by_age` for the implicit `eq`, `select_by_age_gt`,
/// `select_by_age_lt`, ...). Absent, this defaults to a single `Eq`, same
/// as before this attribute existed.
#[derive(Debug, Clone)]
pub struct OperatorList(pub Vec<Operator>);

impl FromMeta for OperatorList {
    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        match expr {
            syn::Expr::Array(array) => {
                let ops = array
                    .elems
                    .iter()
                    .map(Operator::from_expr)
                    .collect::<darling::Result<Vec<_>>>()?;
                if ops.is_empty() {
                    return Err(
                        Error::custom("expected at least one operator in the list")
                            .with_span(array),
                    );
                }
                Ok(OperatorList(ops))
            }
            other => Operator::from_expr(other).map(|op| OperatorList(vec![op])),
        }
    }
}

/// Field-level `#[table(...)]`.
///
/// A field can be a plain column, or opt in to being a filter for `select`,
/// `select_many`, `update`, or `delete` methods; a filter field can also
/// carry an `as_type` override for its `SELECT` column (used for Postgres
/// enums: `role AS "role!: Role"`).
#[derive(Debug, Clone, FromField)]
#[darling(attributes(table))]
pub struct FieldAttrs {
    pub ident: Option<syn::Ident>,
    pub ty: syn::Type,

    #[darling(default)]
    pub select: util::Flag,
    #[darling(default)]
    pub select_many: util::Flag,
    #[darling(default)]
    pub update: util::Flag,
    #[darling(default)]
    pub delete: util::Flag,
    /// Set once at creation, never again: a **skip hook**, not a database-
    /// level guard — this field is included in `SqlInsert`/`SqlInsertMany`/
    /// `SqlInsertManyColumns`'s column list as usual, but every `SET`
    /// clause this crate generates for it (`SqlUpdate`/`SqlUpdateMany`/
    /// `SqlUpdateManyColumns`'s `update_by_<field>` and struct-level
    /// `#[table(update = method_name(...))]` methods, *and* `SqlInsert`/
    /// `SqlInsertMany`/`SqlInsertManyColumns`'s own `ON CONFLICT ... DO
    /// UPDATE SET` upsert clause) simply never mentions the column at
    /// all — no `EXCLUDED.<col>`, no bind, nothing. The column isn't
    /// locked by a trigger or constraint; it's just absent from these
    /// particular generated queries, the same way a field without
    /// `#[table(select)]` is simply absent from `select_by_<field>`'s
    /// WHERE clause. Any other query you write by hand (raw SQL, a
    /// different ORM call, `psql`) can still change it — this only
    /// affects what this crate's own generated methods do. For
    /// `SqlUpdate`/`SqlUpdateMany`/`SqlUpdateManyColumns`, if every other
    /// field is also excluded (the key itself, or another `skip_update`
    /// field), the method has nothing left to `SET` and fails to
    /// compile. For the upsert clause, the equivalent all-excluded case
    /// instead falls back to `ON CONFLICT (...) DO NOTHING` — both
    /// because an empty `SET` is invalid SQL, but only the latter has a
    /// sensible non-empty fallback.
    #[darling(default)]
    pub skip_update: util::Flag,
    /// Generates its own `upsert_by_<field>` method on `SqlInsert`/
    /// `SqlInsertMany` — an `INSERT ... ON CONFLICT (this_field) DO UPDATE
    /// SET col = EXCLUDED.col, ...` for every other field — same shape as
    /// `select_by_<field>`/`update_by_<field>`/`delete_by_<field>`: each
    /// marked field is independent and gets its own method, never silently
    /// combined with another marked field. The plain `insert()`/
    /// `insert_many()` methods are unaffected either way (never `ON
    /// CONFLICT`). For one `ON CONFLICT` target spanning more than one
    /// column, use a struct-level `#[table(upsert = method_name(field1,
    /// field2, ...))]` instead, which generates an additional, separately
    /// named method.
    #[darling(default)]
    pub upsert: util::Flag,

    #[darling(default)]
    pub as_type: Option<String>,
    /// The Postgres type name for this column (e.g. `"text"`, `"int4"`,
    /// `"role"`) — needed only by `SqlInsertMany`/`SqlUpdateMany`'s
    /// `UNNEST`-based batch methods, to cast each array parameter
    /// (`$1::<pg_type>[]`). Postgres can't infer an `UNNEST` parameter's
    /// element type from context the way it infers a plain scalar bind's
    /// type from its target column — function-overload resolution for
    /// `unnest()` happens *before* that context is available, so an
    /// uncast `$1` is a hard "function unnest(unknown) is not unique"
    /// error, not just a missed optimization. Auto-detected for common
    /// scalar types (`String`, `bool`, `i16`/`i32`/`i64`, `f32`/`f64`) if
    /// omitted; required for anything else (a custom enum/domain type via
    /// `as_type`, or any other type the auto-detection doesn't recognize)
    /// — omitting it there is a compile error telling you to add it.
    #[darling(default)]
    pub pg_type: Option<String>,
    #[darling(default)]
    pub op: Option<OperatorList>,
}

/// Struct-level `#[table(...)]`.
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(table), supports(struct_named))]
pub struct TableAttrs {
    pub ident: syn::Ident,
    pub data: ast::Data<util::Ignored, FieldAttrs>,

    #[darling(default)]
    pub name: Option<QuotedString>,
    #[darling(default)]
    pub spec_columns: Option<QuotedString>,
    #[darling(default)]
    pub return_type: Option<TypeExpr>,
    #[darling(default)]
    pub return_fields: Option<QuotedString>,

    #[darling(default, multiple, rename = "select")]
    pub custom_select: Vec<MethodSpec>,
    #[darling(default, multiple, rename = "select_many")]
    pub custom_select_many: Vec<MethodSpec>,
    #[darling(default, multiple, rename = "delete")]
    pub custom_delete: Vec<MethodSpec>,
    #[darling(default, multiple, rename = "update")]
    pub custom_update: Vec<MethodSpec>,
    #[darling(default, multiple, rename = "upsert")]
    pub custom_upsert: Vec<UpsertSpec>,
}