sql-macros-derive 0.5.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
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
//! Shared intermediate representation.
//!
//! Every `#[derive(Sql...)]` macro builds one `TableModel` from the
//! `syn::DeriveInput` and then only reads from it — none of the
//! `select.rs`/`update.rs`/etc. codegen modules touch `syn::Attribute` or
//! `darling` directly. This is the single place that turns "what the user
//! wrote in attributes" into "what SQL/Rust to generate", so the five
//! `generate_method`-style functions that used to duplicate this logic
//! (one per derive) now share one implementation.

use quote::ToTokens;

use crate::attrs::{FieldAttrs, MethodFilterSpec, MethodSpec, TableAttrs, UpsertSpec};
pub use crate::attrs::Operator;

/// One field of the annotated struct, after attribute parsing.
#[derive(Debug)]
pub struct Column {
    pub ident: syn::Ident,
    pub ty: syn::Type,
    /// The `SELECT`-list entry for this column: `email`, or
    /// `role AS "role!: Role"` when `as_type` is set.
    pub sql_select_expr: String,
    pub is_select_filter: bool,
    pub is_select_many_filter: bool,
    pub is_update_filter: bool,
    pub is_delete_filter: bool,
    pub is_upsert_target: bool,
    /// `#[table(insert_only)]` — excluded from every generated `UPDATE`'s
    /// `SET` clause (see `attrs::FieldAttrs::insert_only`), but otherwise a
    /// completely ordinary column (still in `INSERT`'s column list, still
    /// usable as `#[table(update)]`'s own WHERE key, etc.).
    pub is_insert_only: bool,
    /// Set when the field carries `#[table(as_type = "...")]` — a Postgres
    /// enum/domain column whose bind expression needs an explicit `as _` in
    /// generated `INSERT`/`UPDATE` calls (see [`bind_expr`]). `None` for a
    /// plain column, which binds as a bare `self.field` so `sqlx::query!`'s
    /// normal compile-time type check still applies to it.
    pub has_as_type: bool,
    /// `#[table(pg_type = "...")]` — see `attrs::FieldAttrs::pg_type`.
    /// `None` means "auto-detect from `ty`, or error if that fails" (see
    /// [`unnest_array_type`]).
    pub pg_type: Option<String>,
    /// `#[table(op = "...")]` or `op = ["...", ...]` — the comparison
    /// operator(s) this column uses in its own single-field methods
    /// (`select_by_<field>`, `select_many_by_<field>`, `delete_by_<field>`,
    /// `update_by_<field>`). Defaults to `[Eq]`. Each operator in the list
    /// generates its own method variant, one field at a time — every
    /// single-field-method derive loops `for op in column.ops`
    /// independently, the same shape for all four. Custom multi-field
    /// methods (`select = name(...)`) never read this; they're always a
    /// plain `=`, `AND`-joined (or, for a raw template, whatever the user
    /// wrote).
    pub ops: Vec<Operator>,
}

impl From<FieldAttrs> for Column {
    fn from(f: FieldAttrs) -> Self {
        let ident = f.ident.expect("named struct fields always have an ident");
        let sql_select_expr = match &f.as_type {
            Some(as_type) => format!("{ident} AS \"{as_type}\""),
            None => ident.to_string(),
        };
        let has_as_type = f.as_type.is_some();
        Column {
            ident,
            ty: f.ty,
            sql_select_expr,
            is_select_filter: f.select.is_present(),
            is_select_many_filter: f.select_many.is_present(),
            is_update_filter: f.update.is_present(),
            is_delete_filter: f.delete.is_present(),
            is_upsert_target: f.upsert.is_present(),
            is_insert_only: f.insert_only.is_present(),
            has_as_type,
            pg_type: f.pg_type,
            ops: f.op.map(|list| list.0).unwrap_or_else(|| vec![Operator::Eq]),
        }
    }
}

/// One concrete `(column, operator)` assignment for a single generated
/// method variant. A field with `op = ["gt", "lt"]` produces one
/// `FilterChoice` per operator, each its own method; a plain field or a
/// custom method's field list is just `Operator::Eq`.
#[derive(Debug, Clone, Copy)]
pub struct FilterChoice<'a> {
    pub column: &'a Column,
    pub op: Operator,
}

/// The word used in a generated method name for a non-`Eq` operator, e.g.
/// `select_by_age` + `_` + `op_word(Gt)` -> `select_by_age_gt`.
pub fn op_word(op: Operator) -> &'static str {
    match op {
        Operator::Eq => "eq",
        Operator::Gt => "gt",
        Operator::Lt => "lt",
        Operator::Gte => "gte",
        Operator::Lte => "lte",
        Operator::Like => "like",
        Operator::Ilike => "ilike",
        Operator::In => "in",
        Operator::NotIn => "not_in",
    }
}

/// One piece of a raw filter template after `$field` references have been
/// resolved against the struct's columns: either literal text (copied
/// through unchanged) or a reference to a column, whose bound-value
/// placeholder number is only decided at render time (see
/// [`render_custom_where`]), since it depends on the offset the caller needs
/// (e.g. `SqlUpdate` numbers its `WHERE` placeholders after its `SET` ones).
#[derive(Debug)]
pub enum RawSegment<'a> {
    Text(String),
    Field(&'a Column),
}

/// How a [`CustomMethod`]'s `WHERE` text should be built. Custom methods
/// never use a column's `#[table(op = ...)]` — they're always `=`, whether
/// listed as fields (`AND`-joined) or referenced by `$field` in a raw
/// template (just the bound-value placeholder); anything more specific has
/// to be written out by hand in a raw template's own SQL text.
#[derive(Debug)]
pub enum FilterTemplate<'a> {
    /// Plain field list — always `=`, `AND`-joined via [`sql_condition`].
    Fields,
    /// A raw `$field`-templated string the user wrote themselves. `$field`
    /// is only the bound-value placeholder; every character that isn't part
    /// of one passes through unchanged (so `OR`/`AND`/`NOT`/`>`/`LIKE`/
    /// parens/anything else — including the column name — is up to them).
    Raw(Vec<RawSegment<'a>>),
}

/// A named custom method (`select = get_active_user(is_active, is_removed)`
/// or `select = search_users("$email OR $phone")`) resolved against the
/// struct's actual fields, so codegen never has to re-check "does this
/// field exist" itself. `filters` lists the referenced columns in the order
/// their placeholders are numbered (first occurrence, for a raw template);
/// build the actual `WHERE` text with [`render_custom_where`], not
/// `sql_condition` directly, since only that knows how to handle `template`.
#[derive(Debug)]
pub struct CustomMethod<'a> {
    pub method_name: syn::Ident,
    pub filters: Vec<&'a Column>,
    pub template: FilterTemplate<'a>,
}

/// A named `ON CONFLICT` target, resolved against the struct's actual
/// fields — the columns that appear in this method's `ON CONFLICT (...)`
/// clause. Used both for a bare-`#[table(upsert)]` field's own
/// single-column method (see [`TableModel::upsert_targets`]) and for
/// a struct-level composite target (`#[table(upsert =
/// insert_or_update_member(org_id, user_id))]`, see
/// [`TableModel::custom_upsert_methods`]).
#[derive(Debug)]
pub struct CustomUpsert<'a> {
    pub method_name: syn::Ident,
    pub targets: Vec<&'a Column>,
}

#[derive(Debug)]
pub struct TableModel {
    pub struct_name: syn::Ident,
    pub table_name: String,
    pub columns: Vec<Column>,
    pub spec_columns: Option<String>,
    pub return_type: Option<syn::Type>,
    pub return_fields: Option<String>,

    custom_select: Vec<MethodSpec>,
    custom_select_many: Vec<MethodSpec>,
    custom_delete: Vec<MethodSpec>,
    custom_update: Vec<MethodSpec>,
    custom_upsert: Vec<UpsertSpec>,
}

impl TableModel {
    pub fn from_derive_input(input: &syn::DeriveInput) -> darling::Result<Self> {
        let attrs = <TableAttrs as darling::FromDeriveInput>::from_derive_input(input)?;

        let struct_name = attrs.ident;
        let table_name = attrs
            .name
            .map(|q| q.0)
            .unwrap_or_else(|| format!("{}s", to_snake_case(&struct_name.to_string())));

        let fields = attrs
            .data
            .take_struct()
            .expect("supports(struct_named) guarantees this is a named struct")
            .fields;

        if fields.is_empty() {
            return Err(
                darling::Error::custom("struct must have at least one field")
                    .with_span(&struct_name),
            );
        }

        let columns = fields.into_iter().map(Column::from).collect();

        Ok(TableModel {
            struct_name,
            table_name,
            columns,
            spec_columns: attrs.spec_columns.map(|q| q.0),
            return_type: attrs.return_type.map(|t| t.0),
            return_fields: attrs.return_fields.map(|q| q.0),
            custom_select: attrs.custom_select,
            custom_select_many: attrs.custom_select_many,
            custom_delete: attrs.custom_delete,
            custom_update: attrs.custom_update,
            custom_upsert: attrs.custom_upsert,
        })
    }

    /// The `SELECT`-list text: plain column names, or `col AS "col!:
    /// Type"` where `as_type` is set. Only valid in a `SELECT` list — an
    /// `INSERT INTO t (...)` column list can't have `AS` in it, so
    /// `SqlInsert`/`SqlInsertMany` use [`column_names`] instead.
    pub fn sql_columns(&self) -> String {
        self.columns
            .iter()
            .map(|c| c.sql_select_expr.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Plain, comma-joined column names — no `as_type` annotation. For an
    /// `INSERT INTO t (...)` column list, where `AS` isn't valid syntax.
    pub fn column_names(&self) -> String {
        self.columns
            .iter()
            .map(|c| c.ident.to_string())
            .collect::<Vec<_>>()
            .join(", ")
    }

    fn find_column(&self, name: &str, span: &syn::Ident) -> darling::Result<&Column> {
        self.columns.iter().find(|c| c.ident == name).ok_or_else(|| {
            darling::Error::custom(format!("`{name}` is not a field of `{}`", self.struct_name))
                .with_span(span)
        })
    }

    fn resolve(&self, spec: &MethodSpec) -> darling::Result<CustomMethod<'_>> {
        match &spec.filter {
            MethodFilterSpec::Fields(field_idents) => {
                let mut filters = Vec::with_capacity(field_idents.len());
                for field_ident in field_idents {
                    filters.push(self.find_column(&field_ident.to_string(), field_ident)?);
                }
                Ok(CustomMethod {
                    method_name: spec.method_name.clone(),
                    filters,
                    template: FilterTemplate::Fields,
                })
            }
            MethodFilterSpec::Raw(raw) => {
                let (filters, segments) = self.parse_raw_template(&spec.method_name, raw)?;
                Ok(CustomMethod {
                    method_name: spec.method_name.clone(),
                    filters,
                    template: FilterTemplate::Raw(segments),
                })
            }
        }
    }

    /// Splits a raw filter template into literal-text and `$field`
    /// segments, resolving each `$field` against the struct's columns.
    /// `$` is only treated as a field reference when followed by a letter
    /// or `_` (so a literal `$1`-style placeholder, if one ever ended up in
    /// the template by mistake, is left alone rather than misread as a
    /// field named `1`).
    fn parse_raw_template<'a>(
        &'a self,
        method_name: &syn::Ident,
        template: &str,
    ) -> darling::Result<(Vec<&'a Column>, Vec<RawSegment<'a>>)> {
        let chars: Vec<char> = template.chars().collect();
        let mut filters: Vec<&Column> = Vec::new();
        let mut segments: Vec<RawSegment<'a>> = Vec::new();
        let mut text = String::new();
        let mut i = 0;

        while i < chars.len() {
            let starts_field = chars[i] == '$'
                && chars.get(i + 1).is_some_and(|c| c.is_alphabetic() || *c == '_');
            if starts_field {
                let start = i + 1;
                let mut end = start;
                while chars.get(end).is_some_and(|c| c.is_alphanumeric() || *c == '_') {
                    end += 1;
                }
                let name: String = chars[start..end].iter().collect();
                let column = self.find_column(&name, method_name)?;

                if !text.is_empty() {
                    segments.push(RawSegment::Text(std::mem::take(&mut text)));
                }
                if !filters.iter().any(|c| c.ident == column.ident) {
                    filters.push(column);
                }
                segments.push(RawSegment::Field(column));
                i = end;
            } else {
                text.push(chars[i]);
                i += 1;
            }
        }
        if !text.is_empty() {
            segments.push(RawSegment::Text(text));
        }

        Ok((filters, segments))
    }

    fn resolve_all(&self, specs: &[MethodSpec]) -> darling::Result<Vec<CustomMethod<'_>>> {
        let mut errors = darling::Error::accumulator();
        let mut methods = Vec::with_capacity(specs.len());
        for spec in specs {
            if let Some(method) = errors.handle(self.resolve(spec)) {
                methods.push(method);
            }
        }
        errors.finish()?;
        Ok(methods)
    }

    pub fn custom_select_methods(&self) -> darling::Result<Vec<CustomMethod<'_>>> {
        self.resolve_all(&self.custom_select)
    }

    pub fn custom_select_many_methods(&self) -> darling::Result<Vec<CustomMethod<'_>>> {
        self.resolve_all(&self.custom_select_many)
    }

    pub fn custom_delete_methods(&self) -> darling::Result<Vec<CustomMethod<'_>>> {
        self.resolve_all(&self.custom_delete)
    }

    pub fn custom_update_methods(&self) -> darling::Result<Vec<CustomMethod<'_>>> {
        self.resolve_all(&self.custom_update)
    }

    /// The fields marked bare `#[table(upsert)]` — each becomes its own
    /// independent single-column `ON CONFLICT` target, same shape as
    /// `select_by_<field>`/`update_by_<field>`/`delete_by_<field>`: never
    /// silently combined with another marked field. `insert()`/
    /// `insert_many()` themselves are unaffected by this — they stay a
    /// plain `INSERT`, no `ON CONFLICT`, regardless of how many fields
    /// carry the bare flag. Each derive (`SqlInsert`/`SqlInsertMany`) names
    /// its own generated method from this (`upsert_by_<field>` /
    /// `upsert_many_by_<field>` — same `select_by_`/`select_many_by_`
    /// split), rather than sharing one name, so deriving both on the same
    /// struct doesn't collide. For a single `ON CONFLICT` target spanning
    /// more than one column, use a struct-level `#[table(upsert =
    /// method_name(field1, field2, ...))]` instead (see
    /// [`custom_upsert_methods`]).
    pub fn upsert_targets(&self) -> impl Iterator<Item = &Column> {
        self.columns.iter().filter(|c| c.is_upsert_target)
    }

    fn resolve_upsert(&self, spec: &UpsertSpec) -> darling::Result<CustomUpsert<'_>> {
        let mut targets = Vec::with_capacity(spec.fields.len());
        for field_ident in &spec.fields {
            targets.push(self.find_column(&field_ident.to_string(), field_ident)?);
        }
        Ok(CustomUpsert {
            method_name: spec.method_name.clone(),
            targets,
        })
    }

    /// The struct's named composite `ON CONFLICT` targets, from
    /// `#[table(upsert = method_name(field1, field2, ...))]`. Each
    /// generates its own additional method, alongside the default
    /// `insert()`/`insert_many()` and any [`upsert_targets`]. `method_name`
    /// here is exactly what the attribute says — `insert_many.rs` suffixes
    /// it with `_many` itself (same `insert`/`insert_many` split) before
    /// generating its own method, so deriving both `SqlInsert` and
    /// `SqlInsertMany` with one shared attribute doesn't produce two
    /// methods with the same name.
    pub fn custom_upsert_methods(&self) -> darling::Result<Vec<CustomUpsert<'_>>> {
        let mut errors = darling::Error::accumulator();
        let mut methods = Vec::with_capacity(self.custom_upsert.len());
        for spec in &self.custom_upsert {
            if let Some(method) = errors.handle(self.resolve_upsert(spec)) {
                methods.push(method);
            }
        }
        errors.finish()?;
        Ok(methods)
    }
}

/// `id: i32, is_removed: bool` — a comma-separated parameter list built
/// straight from `syn::Type`s (no string round-trip, so it can't silently
/// drop generic type arguments like the 0.1 parser did), for a resolved
/// [`FilterChoice`] list — a choice with `op` of `In`/`NotIn` takes
/// `&[FieldType]` instead of `FieldType`, since its filter compares against
/// a list (`field = ANY($n)` / `field != ALL($n)`).
pub fn params_tokens_for_choices(choices: &[FilterChoice]) -> proc_macro2::TokenStream {
    let parts = choices.iter().map(|choice| {
        let ident = &choice.column.ident;
        let ty = &choice.column.ty;
        if matches!(choice.op, Operator::In | Operator::NotIn) {
            quote::quote! { #ident: &[#ty] }
        } else {
            quote::quote! { #ident: #ty }
        }
    });
    quote::quote! { #(#parts),* }
}

/// Wraps a generated method's SQL in a fenced code block for its `#[doc =
/// ...]` attribute. Needed because `#[doc = "..."]` content is rendered as
/// Markdown — a bare `\n` there is a Markdown *soft* line break, which
/// most renderers (rustdoc included) collapse back into a single space,
/// so the query's own line breaks (one clause per line) would otherwise
/// disappear in hover tooltips/rustdoc output even though they show up
/// fine in a raw macro-expansion dump. A fenced block preserves them
/// exactly. Only for the `#[doc = ...]` text — the query passed to
/// `sqlx::query!`/`query_as!` itself must stay the plain, un-fenced
/// string.
pub fn sql_doc(query: &str) -> String {
    format!("```sql\n{query}\n```")
}

pub fn idents(columns: &[&Column]) -> Vec<syn::Ident> {
    columns.iter().map(|c| c.ident.clone()).collect()
}

pub fn idents_for_choices(choices: &[FilterChoice]) -> Vec<syn::Ident> {
    choices.iter().map(|c| c.column.ident.clone()).collect()
}

/// `self.field1, self.field2 as _` — the bind-argument list for
/// `sqlx::query!`/`query_as!` in generated `INSERT`/`UPDATE` methods. Only
/// columns with `#[table(as_type = "...")]` get the `as _` cast, since
/// that's the only case that actually needs it (a custom Postgres
/// enum/domain column, where `sqlx::query!` can't otherwise resolve the
/// bind type against the schema); adding it to every field unconditionally
/// would quietly disable the macro's normal compile-time type check for
/// plain columns too.
pub fn self_bind_tokens(columns: &[&Column]) -> proc_macro2::TokenStream {
    let parts = columns.iter().map(|c| {
        let ident = &c.ident;
        if c.has_as_type {
            quote::quote! { self.#ident as _ }
        } else {
            quote::quote! { self.#ident }
        }
    });
    quote::quote! { #(#parts),* }
}

/// `&self.field1, &self.field2 as _` — like [`self_bind_tokens`], but with
/// an explicit leading `&`. Needed for a *columns-already-built* field
/// (`SqlInsertManyColumns`/`SqlUpdateManyColumns`, where the field is
/// itself a `Vec<T>`): `sqlx::query!`'s own compile-time type-check
/// duplicates the bind expression once to compare it against the
/// expected param type, and a bare `self.field` only survives that
/// duplication as a reference if it already *was* one — a plain
/// `Vec<T>` field loses its only reference there and the check fails
/// expecting `&[T]`. A bound `String`/`i32`/etc. field doesn't need this
/// (the scalar case, [`self_bind_tokens`], already works without it),
/// only a `Vec<T>` one. The `as _` cast ([`array_bind_needs_as_cast`])
/// is for a second, unrelated reason — see [`unnest_bind_tokens`].
pub fn self_bind_ref_tokens(columns: &[&Column]) -> proc_macro2::TokenStream {
    let parts = columns.iter().map(|c| {
        let ident = &c.ident;
        if array_bind_needs_as_cast(c) {
            quote::quote! { &self.#ident as _ }
        } else {
            quote::quote! { &self.#ident }
        }
    });
    quote::quote! { #(#parts),* }
}

/// For a batch method (`SqlInsertMany`'s `insert_many`, `SqlUpdateMany`'s
/// `update_many_by_<field>`) built on `UNNEST($1, $2, ...)`: `sqlx::query!`/
/// `query_as!` need one Postgres *array* parameter per column, not one
/// scalar bind per row — so the row-wise `items: &[Self]` has to be
/// transposed into one owned, column-wise `Vec` per field first. This
/// generates that transpose, one `let <ident>: Vec<<ty>> = items.iter()...`
/// per column, to run right before the query — see [`unnest_bind_tokens`]
/// for the matching bind-argument list.
pub fn unnest_collect_tokens(columns: &[&Column]) -> proc_macro2::TokenStream {
    let parts = columns.iter().map(|c| {
        let ident = &c.ident;
        let ty = &c.ty;
        // `.clone()` unconditionally, even for a `Copy` field (e.g. `bool`,
        // `i32`) — the macro has no way to know a field's type is `Copy`,
        // so the alternative would be a dedicated code path per field just
        // to dodge `clippy::clone_on_copy`. `#[allow(...)]` is simpler and
        // the extra clone is one `memcpy` per row, not a real cost.
        quote::quote! {
            #[allow(clippy::clone_on_copy)]
            let #ident: Vec<#ty> = items.iter().map(|item| item.#ident.clone()).collect();
        }
    });
    quote::quote! { #(#parts)* }
}

/// `&field1, &field2 as _` — the bind-argument list for the `Vec`s
/// [`unnest_collect_tokens`] builds. The `as _` cast
/// ([`array_bind_needs_as_cast`]) is needed for an `as_type` column (same
/// reason as [`self_bind_tokens`]) *and* for an `Option<T>`-typed one —
/// unlike a plain scalar bind, an array parameter's Postgres type has no
/// per-element nullability, so `sqlx::query!`'s compile-time check always
/// expects the bare, non-`Option` slice type and rejects an
/// `Option`-wrapped bind without the cast (confirmed live: the actual
/// encoding — `NULL` elements in a Postgres array — works fine once past
/// that check).
pub fn unnest_bind_tokens(columns: &[&Column]) -> proc_macro2::TokenStream {
    let parts = columns.iter().map(|c| {
        let ident = &c.ident;
        if array_bind_needs_as_cast(c) {
            quote::quote! { &#ident as _ }
        } else {
            quote::quote! { &#ident }
        }
    });
    quote::quote! { #(#parts),* }
}

/// Common scalar Rust types this crate can map to a Postgres array-element
/// type name automatically, for [`unnest_array_type`]. Anything else
/// (custom enum/domain types, or any other type this doesn't recognize)
/// needs an explicit `#[table(pg_type = "...")]`.
fn builtin_pg_array_type(ty: &syn::Type) -> Option<&'static str> {
    let text = quote::quote!(#ty).to_string().replace(' ', "");
    match text.as_str() {
        "String" => Some("text"),
        "bool" => Some("bool"),
        "i16" => Some("int2"),
        "i32" => Some("int4"),
        "i64" => Some("int8"),
        "f32" => Some("float4"),
        "f64" => Some("float8"),
        "Uuid" | "uuid::Uuid" => Some("uuid"),
        // `jsonb`, not `json` — an arbitrary pick, confirmed live that it
        // doesn't actually matter which one: Postgres has an implicit
        // assignment cast each way, so this works into a `json` column
        // too, not just a `jsonb` one.
        "Value" | "serde_json::Value" => Some("jsonb"),
        // Timestamp without a time zone — either date/time crate's plain
        // (no-offset) type, confirmed live with each crate's own sqlx
        // feature enabled on its own (not both at once: enabling both
        // `chrono` and `time` together makes sqlx's compile-time check
        // ambiguous about which one a `TIMESTAMP` column means, which
        // isn't a real-world setup — a project picks one date/time
        // crate, not both).
        "NaiveDateTime" | "chrono::NaiveDateTime" => Some("timestamp"),
        "PrimitiveDateTime" | "time::PrimitiveDateTime" => Some("timestamp"),
        _ => None,
    }
}

/// If `ty` is written as `<wrapper><T>` (`wrapper` being e.g. `"Vec"` or
/// `"Option"`), returns `T` — otherwise `None`.
fn single_generic_arg<'a>(ty: &'a syn::Type, wrapper: &str) -> Option<&'a syn::Type> {
    // A macro-generated field type (e.g. a `define_soa!`-style macro that
    // transposes `$field_ty` into `Vec<$field_ty>`) can wrap the expanded
    // type in an invisible `Type::Group` for hygiene — `Vec<⟦Option<i32>⟧>`
    // rather than a bare `Vec<Option<i32>>`. Unwrap any such groups before
    // matching, or a doubly-wrapped `Vec<Option<T>>` fails to recurse past
    // the first level (`vec_inner_type` would hand back the still-grouped
    // `Option<i32>`, which this function's own `Type::Path` match would
    // then reject).
    let mut ty = ty;
    while let syn::Type::Group(group) = ty {
        ty = &group.elem;
    }
    let syn::Type::Path(type_path) = ty else { return None };
    let segment = type_path.path.segments.last()?;
    if segment.ident != wrapper {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return None;
    };
    args.args.iter().find_map(|arg| match arg {
        syn::GenericArgument::Type(t) => Some(t),
        _ => None,
    })
}

/// `Vec<T>` -> `T`. Lets [`unnest_array_type`] detect a
/// *columns-already-built* field's Postgres type
/// (`SqlInsertManyColumns`/`SqlUpdateManyColumns`, where a column is
/// itself a `Vec<String>`) the same way it detects a plain row-wise
/// field's (`SqlInsertMany`, where the column is just `String`), without
/// a separate detection function for each.
fn vec_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
    single_generic_arg(ty, "Vec")
}

/// `Option<T>` -> `T`. Lets [`unnest_array_type`] detect a nullable
/// column's Postgres type the same way as a non-nullable one — `NULL`
/// itself doesn't change which Postgres type an array holds, only
/// whether an element of it can be absent.
fn option_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
    single_generic_arg(ty, "Option")
}

/// Whether an *array* bind (`UNNEST`'s own parameters — see
/// [`unnest_bind_tokens`]/[`self_bind_ref_tokens`]) needs an explicit
/// `as _` for this column. `#[table(as_type = "...")]` is the existing
/// reason; `Option<T>`/`Vec<Option<T>>` is a second one, found live:
/// unlike a plain scalar bind (where `sqlx::query!`'s compile-time check
/// infers nullability from the real target column), an array parameter's
/// Postgres type (e.g. `text[]`) has no per-element nullability of its
/// own — nothing in the type says whether an element can be `NULL` — so
/// the compile-time check always expects the bare, non-`Option` slice
/// type for *any* array bind, and rejects an `Option<T>`-wrapped one
/// without `as _`, even though the actual encoding (`NULL` elements in a
/// Postgres array) works fine once past that check.
fn array_bind_needs_as_cast(column: &Column) -> bool {
    column.has_as_type
        || option_inner_type(&column.ty).is_some()
        || vec_inner_type(&column.ty).and_then(option_inner_type).is_some()
}

/// The Postgres array-element type name to cast this column's `UNNEST`
/// parameter to (`$N::<this>[]`) — explicit `#[table(pg_type = "...")]` if
/// set, else an automatic guess for a handful of common scalar types,
/// unwrapping `Option<T>` (nullable) and/or `Vec<T>` (a
/// columns-already-built field — nullable there is `Vec<Option<T>>`)
/// first if the bare type doesn't match, else a spanned error pointing
/// at adding `pg_type`. See `attrs::FieldAttrs::pg_type` for why this is
/// needed at all: Postgres can't infer an `UNNEST` parameter's element
/// type from its eventual target column the way it can for a plain
/// scalar bind — the `unnest()` overload has to be resolved first,
/// before that context exists.
pub fn unnest_array_type(column: &Column) -> darling::Result<String> {
    if let Some(pg_type) = &column.pg_type {
        return Ok(pg_type.clone());
    }
    let ty = &column.ty;
    let cast = builtin_pg_array_type(ty)
        .or_else(|| option_inner_type(ty).and_then(builtin_pg_array_type))
        .or_else(|| vec_inner_type(ty).and_then(builtin_pg_array_type))
        .or_else(|| {
            vec_inner_type(ty)
                .and_then(option_inner_type)
                .and_then(builtin_pg_array_type)
        });
    if let Some(cast) = cast {
        return Ok(cast.into());
    }
    Err(darling::Error::custom(format!(
        "don't know the Postgres type for `{}` — add `#[table(pg_type = \"...\")]` \
         (e.g. `pg_type = \"text\"`, or a custom enum/domain type's own name) so \
         `UNNEST($N::<pg_type>[])` knows what to cast to",
        column.ident
    ))
    .with_span(&column.ident))
}

/// `$1::text[],$2::role[]` — the `UNNEST(...)` placeholder list for a batch
/// method (`SqlInsertMany`'s `insert_many`, `SqlUpdateMany`'s
/// `update_many_by_<field>`), one cast array parameter per column (see
/// [`unnest_array_type`]).
pub fn unnest_placeholders(columns: &[&Column]) -> darling::Result<String> {
    let mut errors = darling::Error::accumulator();
    let mut placeholders = Vec::with_capacity(columns.len());
    for (i, column) in columns.iter().enumerate() {
        if let Some(pg_type) = errors.handle(unnest_array_type(column)) {
            placeholders.push(format!("${}::{}[]", i + 1, pg_type));
        }
    }
    errors.finish()?;
    Ok(placeholders.join(","))
}

/// `id=$1`, `age>$2`, `email LIKE $3`, `id = ANY($4)` — one column's full
/// comparison at a given placeholder number, for a specific operator.
/// Shared by [`sql_condition_for_choices`] (an `AND`-joined list of these)
/// and single-field method generation in `select.rs`/`select_many.rs`/
/// `delete.rs`/`update.rs`.
fn render_comparison(ident: &syn::Ident, op: Operator, placeholder: usize) -> String {
    match op {
        Operator::In => format!("{ident} = ANY(${placeholder})"),
        Operator::NotIn => format!("{ident} != ALL(${placeholder})"),
        Operator::Like => format!("{ident} LIKE ${placeholder}"),
        Operator::Ilike => format!("{ident} ILIKE ${placeholder}"),
        op => format!("{ident}{}${placeholder}", op.sql_symbol()),
    }
}

/// `id=$1 AND is_removed=$2`, always `=`, placeholders numbered starting at
/// `offset + 1`. Used for a plain field-list custom method — those never
/// read a column's `#[table(op = ...)]`.
pub fn sql_condition(columns: &[&Column], offset: usize) -> String {
    columns
        .iter()
        .enumerate()
        .map(|(i, c)| render_comparison(&c.ident, Operator::Eq, offset + i + 1))
        .collect::<Vec<_>>()
        .join(" AND ")
}

/// Like [`sql_condition`], but for a resolved [`FilterChoice`] list, so each
/// column's comparison can use a specific operator (one variant of its
/// `#[table(op = ...)]` list) instead of always `=`. Used for single-field
/// methods (`select_by_<field>`, ...) and `SqlUpdate`'s default `update()`.
pub fn sql_condition_for_choices(choices: &[FilterChoice], offset: usize) -> String {
    choices
        .iter()
        .enumerate()
        .map(|(i, c)| render_comparison(&c.column.ident, c.op, offset + i + 1))
        .collect::<Vec<_>>()
        .join(" AND ")
}

/// Renders a [`CustomMethod`]'s `WHERE` text at the given placeholder
/// `offset` — `sql_condition(&method.filters, offset)` for a plain field
/// list (always `=`), or the user's raw template for a raw one. In a raw
/// template, `$field` is *only* the bound-value placeholder — the column
/// name, operator, and everything else is whatever the user wrote — with
/// the placeholder numbered by first occurrence (`position` from
/// `method.filters`, so the same field referenced twice reuses one number).
pub fn render_custom_where(method: &CustomMethod, offset: usize) -> String {
    match &method.template {
        FilterTemplate::Fields => sql_condition(&method.filters, offset),
        FilterTemplate::Raw(segments) => {
            let mut out = String::new();
            for segment in segments {
                match segment {
                    RawSegment::Text(text) => out.push_str(text),
                    RawSegment::Field(column) => {
                        let position = method
                            .filters
                            .iter()
                            .position(|c| c.ident == column.ident)
                            .expect("every field in a raw template is collected into filters during parse_raw_template");
                        out.push('$');
                        out.push_str(&(offset + position + 1).to_string());
                    }
                }
            }
            out
        }
    }
}

/// `email=$1, is_active=$2` — comma-joined `SET`-clause assignments,
/// placeholders numbered starting at `offset + 1`. Distinct from
/// `sql_condition` (` AND `-joined, for `WHERE`) because joining a `SET`
/// list with `AND` produces a single boolean-valued assignment to the first
/// column instead of one assignment per column.
pub fn sql_set_clause(columns: &[&Column], offset: usize) -> String {
    columns
        .iter()
        .enumerate()
        .map(|(i, c)| format!("{}=${}", c.ident, offset + i + 1))
        .collect::<Vec<_>>()
        .join(", ")
}

/// `email=data.email, is_active=data.is_active` — comma-joined `SET`-clause
/// assignments against a named source (`SqlUpdateMany`'s `UNNEST(...) AS
/// data(...)`), instead of `sql_set_clause`'s numbered placeholders. Same
/// "comma, not `AND`" reasoning applies.
pub fn sql_set_clause_from(columns: &[&Column], source: &str) -> String {
    columns
        .iter()
        .map(|c| format!("{ident}={source}.{ident}", ident = c.ident))
        .collect::<Vec<_>>()
        .join(", ")
}

/// `ON CONFLICT (email) DO UPDATE SET is_active=EXCLUDED.is_active`, built
/// from the fields marked `#[table(upsert)]` (`targets`, the conflict
/// target) against every other non-`insert_only` column in `all` (the `DO
/// UPDATE SET` list) — same skip-hook exclusion `#[table(insert_only)]`
/// gets in every `SqlUpdate`/`SqlUpdateMany`/`SqlUpdateManyColumns`-
/// generated `SET` clause (see `attrs::FieldAttrs::insert_only`): the
/// column is just never mentioned in this query either, so a conflicting
/// row's insert-time value survives an upsert instead of being overwritten
/// by `EXCLUDED.<col>`. `None` if `targets` is empty (no upsert
/// requested). Falls back to `DO NOTHING` if every remaining column is
/// part of the conflict target or `insert_only`, since an empty `SET`
/// list is invalid SQL.
pub fn upsert_clause(all: &[&Column], targets: &[&Column]) -> Option<String> {
    if targets.is_empty() {
        return None;
    }

    let target_list = targets
        .iter()
        .map(|c| c.ident.to_string())
        .collect::<Vec<_>>()
        .join(", ");

    let set_columns: Vec<&&Column> = all
        .iter()
        .filter(|c| !targets.iter().any(|t| t.ident == c.ident) && !c.is_insert_only)
        .collect();

    if set_columns.is_empty() {
        return Some(format!("\nON CONFLICT ({target_list}) DO NOTHING"));
    }

    let set_clause = set_columns
        .iter()
        .map(|c| format!("{ident}=EXCLUDED.{ident}", ident = c.ident))
        .collect::<Vec<_>>()
        .join(", ");

    Some(format!("\nON CONFLICT ({target_list}) DO UPDATE SET {set_clause}"))
}

/// `OrganizationMember` -> `organization_member`. Splits before an uppercase
/// letter that follows a lowercase/digit, or that precedes a lowercase letter
/// after a run of uppercase letters (so `HTTPServer` -> `http_server`).
fn to_snake_case(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut result = String::with_capacity(s.len() + 4);
    for (i, &c) in chars.iter().enumerate() {
        if c.is_uppercase() {
            let prev = i.checked_sub(1).map(|j| chars[j]);
            let next = chars.get(i + 1);
            let boundary = match prev {
                Some(p) => {
                    p.is_lowercase()
                        || p.is_numeric()
                        || (p.is_uppercase() && next.is_some_and(|n| n.is_lowercase()))
                }
                None => false,
            };
            if boundary {
                result.push('_');
            }
            result.extend(c.to_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

/// Renders a `syn::Type` back to source text for embedding in generated
/// code via `syn::parse_str` at a call site that already has a
/// `proc_macro2::TokenStream` slot (kept only where callers need a
/// `&syn::Type`, e.g. `quote! { Result<#ty, ...> }` — most call sites can
/// just interpolate `#ty` directly with `quote!`).
#[allow(dead_code)]
pub fn type_to_string(ty: &syn::Type) -> String {
    ty.to_token_stream().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::quote;

    fn parse(tokens: proc_macro2::TokenStream) -> syn::DeriveInput {
        syn::parse2(tokens).expect("failed to parse test struct")
    }

    #[test]
    fn table_name_defaults_to_pluralized_lowercase_struct_name() {
        let input = parse(quote! {
            struct User { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(model.table_name, "users");
    }

    #[test]
    fn table_name_requires_quotes_now() {
        // Regression: 0.1 accepted a bare identifier (`name = users`); 0.2
        // requires a quoted string and explains why in the error.
        let input = parse(quote! {
            #[table(name = users)]
            struct User { id: i32 }
        });
        let err = TableModel::from_derive_input(&input).unwrap_err();
        assert!(err.to_string().contains("quoted string"));
    }

    #[test]
    fn table_name_splits_camel_case_struct_name_into_snake_case() {
        let input = parse(quote! {
            struct UserTodo { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(model.table_name, "user_todos");
    }

    #[test]
    fn table_name_can_be_overridden_with_quotes() {
        let input = parse(quote! {
            #[table(name = "app_users")]
            struct User { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(model.table_name, "app_users");
    }

    #[test]
    fn sql_columns_handles_as_type_annotation() {
        let input = parse(quote! {
            struct User {
                id: i32,
                #[table(as_type = "role!: Role")]
                role: Role,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(model.sql_columns(), "id, role AS \"role!: Role\"");
    }

    #[test]
    fn field_types_with_multiple_generic_args_are_preserved() {
        // Regression test for the 0.1 bug where a hand-rolled string
        // round-trip silently dropped field types with zero or multiple
        // generic arguments (e.g. HashMap<K, V>).
        let input = parse(quote! {
            struct Payload {
                #[table(select)]
                data: std::collections::HashMap<String, i32>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let ty = &model.columns[0].ty;
        assert_eq!(
            quote!(#ty).to_string(),
            quote!(std::collections::HashMap<String, i32>).to_string()
        );
    }

    #[test]
    fn custom_select_method_resolves_named_fields() {
        let input = parse(quote! {
            #[table(select = get_active_user(is_active, is_removed))]
            struct User {
                id: i32,
                is_active: bool,
                is_removed: bool,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_methods().unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].method_name.to_string(), "get_active_user");
        let names: Vec<String> = methods[0]
            .filters
            .iter()
            .map(|c| c.ident.to_string())
            .collect();
        assert_eq!(names, vec!["is_active", "is_removed"]);
    }

    #[test]
    fn custom_method_referencing_unknown_field_is_a_spanned_error() {
        let input = parse(quote! {
            #[table(select = get_by_x(nonexistent))]
            struct User { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let err = model.custom_select_methods().unwrap_err();
        assert!(err.to_string().contains("nonexistent"));
        assert!(err.to_string().contains("not a field"));
    }

    #[test]
    fn repeated_select_attributes_all_collected() {
        let input = parse(quote! {
            #[table(select = a(id))]
            #[table(select = b(id))]
            struct User { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_methods().unwrap();
        let names: Vec<String> = methods.iter().map(|m| m.method_name.to_string()).collect();
        assert_eq!(names, vec!["a", "b"]);
    }

    #[test]
    fn sql_condition_numbers_placeholders_from_offset() {
        let input = parse(quote! {
            struct User { id: i32, email: String }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let cols: Vec<&Column> = model.columns.iter().collect();
        assert_eq!(sql_condition(&cols, 2), "id=$3 AND email=$4");
    }

    #[test]
    fn custom_method_field_list_ignores_a_fields_own_op() {
        // A custom multi-field method is always `=`, even if the field
        // also carries `#[table(op = "gt")]` for its own single-field
        // methods.
        let input = parse(quote! {
            #[table(select = get_by_age(age))]
            struct User {
                #[table(select_many, op = "gt")]
                age: i32,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_methods().unwrap();
        assert_eq!(render_custom_where(&methods[0], 0), "age=$1");
    }

    #[test]
    fn op_defaults_to_a_single_eq() {
        let input = parse(quote! {
            struct User { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(model.columns[0].ops, vec![Operator::Eq]);
    }

    #[test]
    fn op_list_generates_one_choice_per_operator() {
        let input = parse(quote! {
            struct User {
                #[table(select_many, op = ["gt", "lt"])]
                age: i32,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let column = &model.columns[0];
        assert_eq!(column.ops, vec![Operator::Gt, Operator::Lt]);
        let choices: Vec<String> = column
            .ops
            .iter()
            .map(|&op| sql_condition_for_choices(&[FilterChoice { column, op }], 0))
            .collect();
        assert_eq!(choices, vec!["age>$1", "age<$1"]);
    }

    #[test]
    fn op_ilike_renders_as_case_insensitive_like() {
        let input = parse(quote! {
            struct User {
                #[table(select_many, op = "ilike")]
                email: String,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let column = &model.columns[0];
        let choice = FilterChoice { column, op: column.ops[0] };
        assert_eq!(sql_condition_for_choices(&[choice], 0), "email ILIKE $1");
    }

    #[test]
    fn op_in_widens_the_param_type_to_a_slice() {
        let input = parse(quote! {
            struct User {
                #[table(select_many, op = "in")]
                id: i32,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let column = &model.columns[0];
        let choice = FilterChoice { column, op: column.ops[0] };
        assert_eq!(sql_condition_for_choices(&[choice], 0), "id = ANY($1)");
        assert_eq!(
            params_tokens_for_choices(&[choice]).to_string(),
            quote!(id: &[i32]).to_string()
        );
    }

    #[test]
    fn op_not_in_widens_the_param_type_to_a_slice() {
        let input = parse(quote! {
            struct User {
                #[table(select_many, op = "not_in")]
                id: i32,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let column = &model.columns[0];
        let choice = FilterChoice { column, op: column.ops[0] };
        assert_eq!(sql_condition_for_choices(&[choice], 0), "id != ALL($1)");
        assert_eq!(
            params_tokens_for_choices(&[choice]).to_string(),
            quote!(id: &[i32]).to_string()
        );
    }

    #[test]
    fn unknown_op_is_a_spanned_error() {
        let input = parse(quote! {
            struct User {
                #[table(select_many, op = "nope")]
                age: i32,
            }
        });
        let err = TableModel::from_derive_input(&input).unwrap_err();
        assert!(err.to_string().contains("unknown operator"));
    }

    #[test]
    fn empty_op_list_is_a_spanned_error() {
        let input = parse(quote! {
            struct User {
                #[table(select_many, op = [])]
                age: i32,
            }
        });
        let err = TableModel::from_derive_input(&input).unwrap_err();
        assert!(err.to_string().contains("at least one operator"));
    }

    #[test]
    fn raw_filter_template_is_a_bare_placeholder_not_a_whole_comparison() {
        // `$field` is only the bound-value placeholder — the user writes
        // the column name and comparison themselves.
        let input = parse(quote! {
            #[table(select_many = search_users("email=$email OR (phone=$phone AND NOT is_removed=$is_removed)"))]
            struct User {
                id: i32,
                email: String,
                phone: String,
                is_removed: bool,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_many_methods().unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(
            render_custom_where(&methods[0], 0),
            "email=$1 OR (phone=$2 AND NOT is_removed=$3)"
        );
    }

    #[test]
    fn raw_filter_template_ignores_a_fields_own_op() {
        let input = parse(quote! {
            #[table(select_many = search_users("email=$email OR age>$age"))]
            struct User {
                id: i32,
                email: String,
                #[table(op = "gt")]
                age: i32,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_many_methods().unwrap();
        assert_eq!(render_custom_where(&methods[0], 0), "email=$1 OR age>$2");
    }

    #[test]
    fn raw_filter_template_collects_referenced_fields_in_first_occurrence_order() {
        let input = parse(quote! {
            #[table(select_many = search_users("$email OR $phone"))]
            struct User {
                id: i32,
                email: String,
                phone: String,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_many_methods().unwrap();
        let names: Vec<String> = methods[0]
            .filters
            .iter()
            .map(|c| c.ident.to_string())
            .collect();
        assert_eq!(names, vec!["email", "phone"]);
    }

    #[test]
    fn raw_filter_template_reuses_the_same_placeholder_for_a_repeated_field() {
        let input = parse(quote! {
            #[table(select_many = search_users("$age OR $age"))]
            struct User {
                id: i32,
                age: i32,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_many_methods().unwrap();
        // `$age` appears twice but must reuse one placeholder both times.
        assert_eq!(render_custom_where(&methods[0], 0), "$1 OR $1");
        let names: Vec<String> = methods[0]
            .filters
            .iter()
            .map(|c| c.ident.to_string())
            .collect();
        assert_eq!(names, vec!["age"]);
    }

    #[test]
    fn raw_filter_template_offset_shifts_every_placeholder() {
        // SqlUpdate numbers its WHERE placeholders after its SET columns —
        // render_custom_where needs to shift a raw template the same way
        // sql_condition already shifts a plain field list.
        let input = parse(quote! {
            #[table(select_many = search_users("$email OR $phone"))]
            struct User {
                id: i32,
                email: String,
                phone: String,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let methods = model.custom_select_many_methods().unwrap();
        assert_eq!(render_custom_where(&methods[0], 2), "$3 OR $4");
    }

    #[test]
    fn raw_filter_template_unknown_field_is_a_spanned_error() {
        let input = parse(quote! {
            #[table(select_many = search_users("$nonexistent"))]
            struct User { id: i32 }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let err = model.custom_select_many_methods().unwrap_err();
        assert!(err.to_string().contains("nonexistent"));
        assert!(err.to_string().contains("not a field"));
    }

    #[test]
    fn unnest_array_type_auto_detects_uuid_and_json() {
        let input = parse(quote! {
            struct Event {
                id: Uuid,
                fully_qualified: uuid::Uuid,
                payload: Value,
                fully_qualified_payload: serde_json::Value,
                batched: Vec<Uuid>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(unnest_array_type(&model.columns[0]).unwrap(), "uuid");
        assert_eq!(unnest_array_type(&model.columns[1]).unwrap(), "uuid");
        assert_eq!(unnest_array_type(&model.columns[2]).unwrap(), "jsonb");
        assert_eq!(unnest_array_type(&model.columns[3]).unwrap(), "jsonb");
        // `Vec<Uuid>` (a columns-already-built field) detects the same
        // way, via `vec_inner_type`.
        assert_eq!(unnest_array_type(&model.columns[4]).unwrap(), "uuid");
    }

    #[test]
    fn unnest_array_type_auto_detects_timestamp_from_either_date_time_crate() {
        let input = parse(quote! {
            struct Event {
                a: NaiveDateTime,
                b: chrono::NaiveDateTime,
                c: PrimitiveDateTime,
                d: time::PrimitiveDateTime,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        for column in &model.columns {
            assert_eq!(unnest_array_type(column).unwrap(), "timestamp");
        }
    }

    #[test]
    fn unnest_array_type_unwraps_option_and_option_in_vec() {
        let input = parse(quote! {
            struct Event {
                nullable_scalar: Option<String>,
                nullable_batch: Vec<Option<i32>>,
                plain_batch: Vec<f32>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(unnest_array_type(&model.columns[0]).unwrap(), "text");
        assert_eq!(unnest_array_type(&model.columns[1]).unwrap(), "int4");
        assert_eq!(unnest_array_type(&model.columns[2]).unwrap(), "float4");
    }

    #[test]
    fn unnest_array_type_sees_through_a_macro_hygiene_group_around_option() {
        // A `macro_rules!` that transposes `$field_ty` into `Vec<$field_ty>`
        // (e.g. a `define_soa!`-style batch-struct generator) wraps the
        // substituted fragment in an invisible `Type::Group` for hygiene —
        // `Vec<⟦Option<i32>⟧>`, not a plain `Vec<Option<i32>>`. Both type
        // detection and the `as _` bind-cast decision go through
        // `single_generic_arg`, so a real repro needs an actual
        // `Type::Group` (not just textual nesting) — build the field type's
        // tokens with an explicit `Delimiter::None` group, as the macro
        // expansion would.
        use proc_macro2::{Delimiter, Group, TokenTree};

        let grouped_option = TokenTree::Group(Group::new(Delimiter::None, quote!(Option<i32>)));
        let input = parse(quote! {
            struct Batch {
                nullable_batch: Vec<#grouped_option>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        assert_eq!(unnest_array_type(&model.columns[0]).unwrap(), "int4");
        assert!(array_bind_needs_as_cast(&model.columns[0]));
    }
}