drizzle-core 0.4.0

A type-safe SQL query builder for Rust
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
mod chunk;
mod comment;
mod cte;
mod owned;
mod tokens;

use crate::prelude::*;
use crate::{
    param::{Param, ParamBind},
    placeholder::Placeholder,
    traits::{SQLParam, ToSQL},
};
pub use chunk::*;
pub use comment::{comment, comment_tags};
use core::fmt::{Display, Write};
pub use owned::*;
use smallvec::SmallVec;
pub use tokens::*;

#[cfg(feature = "profiling")]
use crate::profile_sql;

/// A SQL fragment: tokens, identifiers, raw text, and bound parameters.
///
/// Every query builder and expression renders to a `SQL`. `V` is the
/// driver's value type (`SQLiteValue`, `PostgresValue`, ...), which also
/// fixes the dialect used to render placeholders: `?` for SQLite and MySQL,
/// `$1, $2, ...` for PostgreSQL.
///
/// Chunks are stored inline for short fragments (up to 8) without a heap
/// allocation.
///
/// # Examples
///
/// ```
/// use drizzle_core::{SQL, Token};
/// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
/// # use std::borrow::Cow;
/// # #[derive(Debug, Clone, PartialEq)]
/// # struct Value(i64);
/// # impl SQLParam for Value {
/// #     const DIALECT: Dialect = Dialect::SQLite;
/// #     type DialectMarker = SQLiteDialect;
/// # }
/// # impl From<Value> for Cow<'_, Value> {
/// #     fn from(value: Value) -> Self { Cow::Owned(value) }
/// # }
///
/// let sql: SQL<'_, Value> = SQL::raw("SELECT")
///     .append(SQL::ident("name"))
///     .push(Token::FROM)
///     .append(SQL::ident("users"))
///     .push(Token::WHERE)
///     .append(SQL::ident("id"))
///     .push(Token::EQ)
///     .append(SQL::param(Value(7)));
///
/// assert_eq!(sql.sql(), r#"SELECT "name" FROM "users" WHERE "id" = ?"#);
/// assert_eq!(sql.params().collect::<Vec<_>>(), [&Value(7)]);
/// ```
#[derive(Debug, Clone)]
pub struct SQL<'a, V: SQLParam> {
    /// The fragment's chunks, in order.
    pub chunks: SmallVec<[SQLChunk<'a, V>; 8]>,
}

impl<'a, V: SQLParam> SQL<'a, V> {
    const POSITIONAL_PLACEHOLDER: Placeholder = Placeholder::anonymous();

    // ==================== constructors ====================

    /// Creates an empty fragment.
    #[inline]
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            chunks: SmallVec::new_const(),
        }
    }

    /// Creates a fragment holding one keyword or punctuation [`Token`].
    #[inline]
    #[must_use]
    pub fn token(t: Token) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Token(t)],
        }
    }

    /// Creates an empty fragment with room for `capacity` chunks.
    #[inline]
    #[must_use]
    pub fn with_capacity_chunks(capacity: usize) -> Self {
        Self {
            chunks: SmallVec::with_capacity(capacity),
        }
    }

    /// Creates a quoted identifier, such as a table or column name.
    ///
    /// The quote character follows the dialect: `"name"` for SQLite and
    /// PostgreSQL, `` `name` `` for MySQL.
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::SQL;
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// assert_eq!(SQL::<Value>::ident("user name").sql(), r#""user name""#);
    /// ```
    #[inline]
    pub fn ident(name: impl Into<Cow<'a, str>>) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Ident(name.into())],
        }
    }

    /// Creates a comma-separated list of quoted column names, without table
    /// qualifiers: `"id", "name"`.
    #[must_use]
    pub fn columns(columns: &[ColumnRef]) -> Self {
        let mut sql = Self::with_capacity_chunks(columns.len().saturating_mul(2));
        for (index, column) in columns.iter().enumerate() {
            if index > 0 {
                sql.push_mut(Token::COMMA);
            }
            sql.append_mut(Self::ident(column.name));
        }
        sql
    }

    /// Creates a fragment of raw SQL text, written as-is.
    ///
    /// The text is not quoted or escaped. Never pass user input here; bind it
    /// with [`SQL::param`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::SQL;
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// assert_eq!(SQL::<Value>::raw("CURRENT_TIMESTAMP").sql(), "CURRENT_TIMESTAMP");
    /// ```
    #[inline]
    pub fn raw(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Raw(text.into())],
        }
    }

    /// Creates an unsigned integer literal, written into the SQL text rather
    /// than bound.
    #[inline]
    #[must_use]
    pub fn number(value: usize) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Number(value)],
        }
    }

    /// Creates a bound parameter holding `value`.
    ///
    /// The SQL text gets a placeholder (`?` or `$n`); the value travels
    /// separately and is returned by [`SQL::params`].
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::SQL;
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// let sql = SQL::param(Value(1)).append(SQL::raw("+")).append(SQL::param(Value(2)));
    /// assert_eq!(sql.sql(), "? + ?");
    /// assert_eq!(sql.params().count(), 2);
    /// ```
    #[inline]
    pub fn param(value: impl Into<Cow<'a, V>>) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Param(Param {
                value: Some(value.into()),
                placeholder: Self::POSITIONAL_PLACEHOLDER,
            })],
        }
    }

    /// Creates a bound binary parameter (BLOB / `bytea`).
    ///
    /// Prefer this over `SQL::param(Vec<u8>)`, which some value types treat
    /// as a list rather than one binary value.
    #[inline]
    pub fn bytes(bytes: impl Into<Cow<'a, [u8]>>) -> Self
    where
        V: From<&'a [u8]> + From<Vec<u8>> + Into<Cow<'a, V>>,
    {
        match bytes.into() {
            Cow::Borrowed(value) => Self::param(V::from(value)),
            Cow::Owned(value) => Self::param(V::from(value)),
        }
    }

    /// Creates a reference to a table, rendered as its quoted name.
    ///
    /// Right after `SELECT ... FROM`, a table reference also lets the
    /// renderer expand an empty projection into the table's columns.
    #[inline]
    #[must_use]
    pub fn table(table: TableRef) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Table(TableSqlRef::from_table_ref(table))],
        }
    }

    /// Creates a reference to a column, rendered as `"table"."column"`.
    #[inline]
    #[must_use]
    pub fn column(column: ColumnRef) -> Self {
        Self {
            chunks: smallvec::smallvec![SQLChunk::Column(ColumnSqlRef::from_column_ref(column))],
        }
    }

    /// Creates a function call: `NAME(args)`.
    ///
    /// A subquery argument gets its own parentheses: `NAME((SELECT ...))`.
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::SQL;
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// let sql = SQL::<Value>::func("LOWER", SQL::ident("email"));
    /// // SQLite and PostgreSQL put a space before `(`; MySQL does not.
    /// assert_eq!(sql.sql(), r#"LOWER ("email")"#);
    /// ```
    #[inline]
    pub fn func(name: &'static str, args: Self) -> Self {
        let args = args.parens_if_subquery();
        SQL::raw(name)
            .push(Token::LPAREN)
            .append(args)
            .push(Token::RPAREN)
    }

    // ==================== builder methods ====================

    /// Appends another fragment and returns the result.
    #[inline]
    #[must_use]
    pub fn append(mut self, other: impl Into<Self>) -> Self {
        #[cfg(feature = "profiling")]
        profile_sql!("append");
        let other = other.into();

        if self.chunks.is_empty() {
            return other;
        }
        if other.chunks.is_empty() {
            return self;
        }

        self.chunks.extend(other.chunks);
        self
    }

    /// Appends another fragment in place.
    #[inline]
    pub fn append_mut(&mut self, other: impl Into<Self>) {
        #[cfg(feature = "profiling")]
        profile_sql!("append_mut");
        let other = other.into();

        if self.chunks.is_empty() {
            self.chunks = other.chunks;
            return;
        }
        if other.chunks.is_empty() {
            return;
        }

        self.chunks.extend(other.chunks);
    }

    /// Appends one chunk (a [`Token`], parameter, ...) and returns the result.
    #[inline]
    #[must_use]
    pub fn push(mut self, chunk: impl Into<SQLChunk<'a, V>>) -> Self {
        self.chunks.push(chunk.into());
        self
    }

    /// Appends one chunk in place.
    #[inline]
    pub fn push_mut(&mut self, chunk: impl Into<SQLChunk<'a, V>>) {
        self.chunks.push(chunk.into());
    }

    /// Reserves room for `additional` more chunks.
    #[inline]
    #[must_use]
    pub fn with_capacity(mut self, additional: usize) -> Self {
        self.chunks.reserve(additional);
        self
    }

    // ==================== combinators ====================

    /// Joins fragments with a separator token. Returns an empty fragment for
    /// an empty iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::{SQL, Token};
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// let cols = [SQL::<Value>::ident("id"), SQL::ident("name")];
    /// assert_eq!(SQL::join(cols, Token::COMMA).sql(), r#""id", "name""#);
    /// ```
    pub fn join<T>(sqls: T, separator: Token) -> Self
    where
        T: IntoIterator,
        T::Item: ToSQL<'a, V>,
    {
        #[cfg(feature = "profiling")]
        profile_sql!("join");

        let mut iter = sqls.into_iter();
        let Some(first) = iter.next() else {
            return SQL::empty();
        };

        let mut result = first.into_sql();
        let (lower, upper) = iter.size_hint();
        if let Some(upper) = upper {
            result.chunks.reserve(upper.saturating_mul(2));
        } else if lower > 0 {
            result.chunks.reserve(lower * 2);
        }

        for item in iter {
            result.chunks.push(SQLChunk::Token(separator));
            let other = item.into_sql();
            if !other.chunks.is_empty() {
                result.chunks.extend(other.chunks);
            }
        }
        result
    }

    /// Wraps the fragment in parentheses: `(self)`.
    #[inline]
    #[must_use]
    pub fn parens(self) -> Self {
        SQL::token(Token::LPAREN).append(self).push(Token::RPAREN)
    }

    /// Wraps the fragment in parentheses only when it is a subquery (see
    /// [`SQL::is_subquery`]).
    #[inline]
    #[must_use]
    pub fn parens_if_subquery(self) -> Self {
        if self.is_subquery() {
            self.parens()
        } else {
            self
        }
    }

    /// Returns `true` if the fragment starts with a `SELECT` or `WITH` token.
    #[inline]
    pub fn is_subquery(&self) -> bool {
        matches!(
            self.chunks.first(),
            Some(SQLChunk::Token(Token::SELECT | Token::WITH))
        )
    }

    /// Appends an alias: `self AS "name"`.
    #[inline]
    #[must_use]
    pub fn alias(self, name: impl Into<Cow<'a, str>>) -> Self {
        self.push(Token::AS).push(SQLChunk::Ident(name.into()))
    }

    /// Creates a comma-separated list of bound parameters: `?, ?, ?`.
    #[inline]
    pub fn param_list<I>(values: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<Cow<'a, V>>,
    {
        let iter = values.into_iter();
        let (lower, upper) = iter.size_hint();
        let count = upper.unwrap_or(lower);
        let mut chunks = SmallVec::with_capacity(count.saturating_mul(2).saturating_sub(1));
        for (i, v) in iter.enumerate() {
            if i > 0 {
                chunks.push(SQLChunk::Token(Token::COMMA));
            }
            chunks.push(SQLChunk::Param(Param {
                value: Some(v.into()),
                placeholder: Self::POSITIONAL_PLACEHOLDER,
            }));
        }
        SQL { chunks }
    }

    /// Creates comma-separated assignments with bound values:
    /// `"col" = ?, "other" = ?`.
    #[inline]
    pub fn assignments<I, T>(pairs: I) -> Self
    where
        I: IntoIterator<Item = (&'static str, T)>,
        T: Into<Cow<'a, V>>,
    {
        let iter = pairs.into_iter();
        let (lower, upper) = iter.size_hint();
        let count = upper.unwrap_or(lower);
        // Each assignment: Ident + EQ + Param = 3 chunks, plus commas
        let mut chunks = SmallVec::with_capacity(count.saturating_mul(4).saturating_sub(1));
        for (i, (col, val)) in iter.enumerate() {
            if i > 0 {
                chunks.push(SQLChunk::Token(Token::COMMA));
            }
            chunks.push(SQLChunk::Ident(Cow::Borrowed(col)));
            chunks.push(SQLChunk::Token(Token::EQ));
            chunks.push(SQLChunk::Param(Param {
                value: Some(val.into()),
                placeholder: Self::POSITIONAL_PLACEHOLDER,
            }));
        }
        SQL { chunks }
    }

    /// Creates comma-separated assignments from fragments:
    /// `"col" = <expression>`.
    ///
    /// Unlike [`SQL::assignments`], which binds each value as a parameter,
    /// this keeps each fragment as-is, so placeholders and raw expressions
    /// survive.
    #[inline]
    pub fn assignments_sql<I>(pairs: I) -> Self
    where
        I: IntoIterator<Item = (&'static str, Self)>,
    {
        let iter = pairs.into_iter();
        let (lower, upper) = iter.size_hint();
        let count = upper.unwrap_or(lower);
        let mut chunks = SmallVec::with_capacity(count.saturating_mul(4).saturating_sub(1));
        for (i, (col, sql)) in iter.enumerate() {
            if i > 0 {
                chunks.push(SQLChunk::Token(Token::COMMA));
            }
            chunks.push(SQLChunk::Ident(Cow::Borrowed(col)));
            chunks.push(SQLChunk::Token(Token::EQ));
            chunks.extend(sql.chunks);
        }
        SQL { chunks }
    }

    // ==================== output methods ====================

    /// Converts every bound value with `f`, changing the value type to `U`.
    ///
    /// Only parameter chunks change. Useful for converting between owned and
    /// borrowed value types (for example `OwnedPostgresValue` to
    /// `PostgresValue<'a>`).
    pub fn map_params<U: SQLParam>(self, mut f: impl FnMut(V) -> U) -> SQL<'a, U> {
        let chunks = self
            .chunks
            .into_iter()
            .map(|chunk| match chunk {
                SQLChunk::Token(t) => SQLChunk::Token(t),
                SQLChunk::Ident(s) => SQLChunk::Ident(s),
                SQLChunk::Raw(s) => SQLChunk::Raw(s),
                SQLChunk::Number(n) => SQLChunk::Number(n),
                SQLChunk::Param(param) => SQLChunk::Param(Param::new(
                    param.placeholder,
                    param.value.map(|cow| Cow::Owned(f(cow.into_owned()))),
                )),
                SQLChunk::Table(t) => SQLChunk::Table(t),
                SQLChunk::Column(c) => SQLChunk::Column(c),
            })
            .collect();
        SQL { chunks }
    }

    /// Copies every borrowed string into owned storage and converts bound
    /// values with `f`, giving a `'static` fragment.
    ///
    /// Generated models use this to outlive the values they were built from.
    /// Identifiers, raw text, placeholders, tables and columns are all kept.
    pub fn into_owned_with<U: SQLParam>(self, mut f: impl FnMut(V) -> U) -> SQL<'static, U> {
        let chunks = self
            .chunks
            .into_iter()
            .map(|chunk| match chunk {
                SQLChunk::Token(token) => SQLChunk::Token(token),
                SQLChunk::Ident(value) => SQLChunk::Ident(Cow::Owned(value.into_owned())),
                SQLChunk::Raw(value) => SQLChunk::Raw(Cow::Owned(value.into_owned())),
                SQLChunk::Number(value) => SQLChunk::Number(value),
                SQLChunk::Param(param) => SQLChunk::Param(Param::new(
                    param.placeholder,
                    param.value.map(|value| Cow::Owned(f(value.into_owned()))),
                )),
                SQLChunk::Table(table) => SQLChunk::Table(table),
                SQLChunk::Column(column) => SQLChunk::Column(column),
            })
            .collect();
        SQL { chunks }
    }

    /// Converts into an [`OwnedSQL`] with no borrowed data.
    #[inline]
    pub fn into_owned(self) -> OwnedSQL<V> {
        OwnedSQL::from(self)
    }

    /// Renders the SQL text.
    ///
    /// Placeholders follow the dialect of `V`: `$1, $2, ...` for PostgreSQL,
    /// `:name` (named) or `?` for SQLite, and `?` for MySQL. Use
    /// [`SQL::build`] to get the parameters in the same pass.
    pub fn sql(&self) -> String {
        #[cfg(feature = "profiling")]
        profile_sql!("sql");
        #[cfg(feature = "profiling")]
        crate::drizzle_profile_scope!("sql_render", "sql.estimate");
        let (sql_cap, _) = self.render_capacity_estimate();
        let mut buf = String::with_capacity(sql_cap);
        self.write_to(&mut buf);
        buf
    }

    /// Whether this statement has a `RETURNING` clause (outside any
    /// parentheses), so it returns rows although it changes data.
    #[must_use]
    pub fn has_returning(&self) -> bool {
        let mut depth = 0usize;
        for chunk in &self.chunks {
            match chunk {
                SQLChunk::Token(Token::LPAREN) => depth += 1,
                SQLChunk::Token(Token::RPAREN) => depth = depth.saturating_sub(1),
                SQLChunk::Token(Token::RETURNING) if depth == 0 => return true,
                _ => {}
            }
        }
        false
    }

    /// Renders the SQL text with every bound value written as a literal
    /// instead of a placeholder.
    ///
    /// For statements that cannot take parameters, such as the body of a
    /// `CREATE VIEW`. Returns `None` when a placeholder has no bound value,
    /// or a value has no literal form in this dialect (see
    /// [`SQLParam::write_literal`]).
    #[must_use]
    pub fn inline_sql(&self) -> Option<String> {
        let (sql_cap, _) = self.render_capacity_estimate();
        let mut buf = String::with_capacity(sql_cap);
        for (i, chunk) in self.chunks.iter().enumerate() {
            match chunk {
                SQLChunk::Param(param) => {
                    let value = param.value.as_ref()?;
                    if !value.as_ref().write_literal(&mut buf) {
                        return None;
                    }
                }
                _ => chunk.write(&mut buf),
            }

            if self.ends_select_head(i) {
                self.write_select_columns(&mut buf, i);
            }

            if self.needs_space(i) {
                buf.push(' ');
            }
        }
        Some(buf)
    }

    /// Renders the SQL text and collects the bound values in one pass.
    ///
    /// Drivers use this to execute a statement. Placeholders without a bound
    /// value are rendered but not collected. For SQLite, a named placeholder
    /// that appears more than once is collected once, since SQLite gives each
    /// distinct `:name` a single slot.
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::SQL;
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// let sql = SQL::raw("SELECT").append(SQL::param(Value(1)));
    /// let (text, params) = sql.build();
    /// assert_eq!(text, "SELECT ?");
    /// assert_eq!(params.as_slice(), [&Value(1)]);
    /// ```
    pub fn build(&self) -> (String, SmallVec<[&V; 8]>) {
        self.build_with(crate::dialect::ParamStyle::for_dialect(V::DIALECT))
    }

    /// Like [`build`](Self::build), but with a caller-chosen placeholder
    /// style.
    ///
    /// For drivers that speak the dialect but bind parameters differently,
    /// such as the AWS Data API on PostgreSQL, which needs `:1, :2, ...`
    /// instead of `$1, $2, ...`.
    pub fn build_with(&self, style: crate::dialect::ParamStyle) -> (String, SmallVec<[&V; 8]>) {
        use crate::dialect::Dialect;

        #[cfg(feature = "profiling")]
        crate::drizzle_profile_scope!("sql_render", "build");
        #[cfg(feature = "profiling")]
        crate::drizzle_profile_scope!("sql_render", "build.estimate");
        let (sql_cap, param_cap) = self.render_capacity_estimate();
        let mut buf = String::with_capacity(sql_cap);
        let mut params: SmallVec<[&V; 8]> = SmallVec::with_capacity(param_cap);
        let mut param_index = 1usize;
        let mut sqlite_names = SQLiteNamedParams::default();

        #[cfg(feature = "profiling")]
        crate::drizzle_profile_scope!("sql_render", "build.render");
        for (i, chunk) in self.chunks.iter().enumerate() {
            match chunk {
                SQLChunk::Param(param) => {
                    let mut repeated_name = false;
                    if let Some(name) = param.placeholder.name
                        && V::DIALECT == Dialect::SQLite
                    {
                        let _ = buf.write_char(':');
                        let _ = buf.write_str(name);
                        repeated_name = sqlite_names.is_repeat(name);
                    } else {
                        style.write(param_index, &mut buf);
                    }
                    param_index += 1;
                    // SQLite gives every distinct `:name` one parameter
                    // slot, so a repeated name binds its value only once.
                    if !repeated_name && let Some(value) = &param.value {
                        params.push(value.as_ref());
                    }
                }
                _ => chunk.write(&mut buf),
            }

            if self.ends_select_head(i) {
                self.write_select_columns(&mut buf, i);
            }

            if self.needs_space(i) {
                let _ = buf.write_char(' ');
            }
        }

        (buf, params)
    }

    /// Writes the SQL text to `buf`, like [`SQL::sql`] without allocating a
    /// new string.
    #[inline]
    pub fn write_to(&self, buf: &mut impl core::fmt::Write) {
        self.write_to_with(buf, crate::dialect::ParamStyle::for_dialect(V::DIALECT));
    }

    /// Like [`write_to`](Self::write_to), but with a caller-chosen
    /// placeholder style.
    pub fn write_to_with(
        &self,
        buf: &mut impl core::fmt::Write,
        style: crate::dialect::ParamStyle,
    ) {
        use crate::dialect::Dialect;

        #[cfg(feature = "profiling")]
        crate::drizzle_profile_scope!("sql_render", "write_to");
        let mut param_index = 1usize;
        for (i, chunk) in self.chunks.iter().enumerate() {
            match chunk {
                SQLChunk::Param(param) => {
                    if let Some(name) = param.placeholder.name
                        && V::DIALECT == Dialect::SQLite
                    {
                        let _ = buf.write_char(':');
                        let _ = buf.write_str(name);
                    } else {
                        style.write(param_index, buf);
                    }
                    param_index += 1;
                }
                _ => chunk.write(buf),
            }

            if self.ends_select_head(i) {
                self.write_select_columns(buf, i);
            }

            if self.needs_space(i) {
                let _ = buf.write_char(' ');
            }
        }
    }

    /// Writes the chunk at `index` to `buf`, expanding an empty `SELECT`
    /// projection that ends at this chunk.
    ///
    /// Does not write the space that may follow the chunk.
    #[inline]
    pub fn write_chunk_to(
        &self,
        buf: &mut impl core::fmt::Write,
        chunk: &SQLChunk<'a, V>,
        index: usize,
    ) {
        chunk.write(buf);
        if self.ends_select_head(index) {
            self.write_select_columns(buf, index);
        }
    }

    /// Whether the chunk at `index` ends a `SELECT` head with no projection,
    /// so the projection must be expanded before the `FROM` that follows.
    ///
    /// The head is `SELECT`, `SELECT DISTINCT`, or `PostgreSQL`'s
    /// `SELECT DISTINCT ON (...)`.
    fn ends_select_head(&self, index: usize) -> bool {
        if !matches!(
            self.chunks.get(index + 1),
            Some(SQLChunk::Token(Token::FROM))
        ) {
            return false;
        }
        let token_at = |position: Option<usize>| match position.and_then(|p| self.chunks.get(p)) {
            Some(SQLChunk::Token(token)) => Some(*token),
            _ => None,
        };

        match self.chunks[index] {
            SQLChunk::Token(Token::SELECT) => true,
            SQLChunk::Token(Token::DISTINCT) => {
                matches!(token_at(index.checked_sub(1)), Some(Token::SELECT))
            }
            SQLChunk::Token(Token::RPAREN) => {
                // Find the `(` this `)` closes, then look for `SELECT DISTINCT ON`.
                let mut depth = 0usize;
                let mut open = None;
                for position in (0..index).rev() {
                    match self.chunks[position] {
                        SQLChunk::Token(Token::RPAREN) => depth += 1,
                        SQLChunk::Token(Token::LPAREN) if depth == 0 => {
                            open = Some(position);
                            break;
                        }
                        SQLChunk::Token(Token::LPAREN) => depth -= 1,
                        _ => {}
                    }
                }
                open.is_some_and(|open| {
                    matches!(token_at(open.checked_sub(1)), Some(Token::ON))
                        && matches!(token_at(open.checked_sub(2)), Some(Token::DISTINCT))
                        && matches!(token_at(open.checked_sub(3)), Some(Token::SELECT))
                })
            }
            _ => false,
        }
    }

    /// Write the projection of a `SELECT` head that ends at `head_end` and
    /// has no explicit column list: every column of the tables in the
    /// following `FROM` clause, or `*` for any other source.
    #[inline]
    pub(crate) fn write_select_columns(&self, buf: &mut impl core::fmt::Write, head_end: usize) {
        let chunks = self.chunks.get(head_end + 1..head_end + 3);
        match chunks {
            Some([SQLChunk::Token(Token::FROM), SQLChunk::Table(_)]) => {
                let _ = buf.write_char(' ');
                let mut first = true;
                let mut depth = 0usize;

                for (index, chunk) in self.chunks.iter().enumerate().skip(head_end + 2) {
                    match chunk {
                        SQLChunk::Token(Token::LPAREN) => depth += 1,
                        SQLChunk::Token(Token::RPAREN) if depth == 0 => break,
                        SQLChunk::Token(Token::RPAREN) => depth -= 1,
                        SQLChunk::Token(
                            Token::WHERE
                            | Token::GROUP
                            | Token::HAVING
                            | Token::ORDER
                            | Token::LIMIT
                            | Token::OFFSET
                            | Token::WINDOW
                            | Token::FOR
                            | Token::UNION
                            | Token::INTERSECT
                            | Token::EXCEPT
                            | Token::SELECT,
                        ) if depth == 0 => break,
                        SQLChunk::Table(table) if depth == 0 => {
                            if !first {
                                let _ = buf.write_str(", ");
                            }
                            let alias = match self.chunks.get(index + 1..index + 3) {
                                Some([SQLChunk::Token(Token::AS), SQLChunk::Ident(alias)]) => {
                                    Some(alias.as_ref())
                                }
                                _ => None,
                            };
                            Self::write_qualified_columns_as(buf, table, alias);
                            first = false;
                        }
                        _ => {}
                    }
                }
            }
            Some([SQLChunk::Token(Token::FROM), _]) => {
                let _ = buf.write_char(' ');
                let _ = buf.write_str(Token::STAR.as_str());
            }
            _ => {}
        }
    }

    /// Writes every column of `table` as `"table"."column"`, separated by
    /// commas, or `"table".*` when the column list is unknown.
    #[inline]
    pub fn write_qualified_columns(buf: &mut impl core::fmt::Write, table: &TableSqlRef) {
        Self::write_qualified_columns_as(buf, table, None);
    }

    #[inline]
    fn write_qualified_columns_as(
        buf: &mut impl core::fmt::Write,
        table: &TableSqlRef,
        alias: Option<&str>,
    ) {
        if table.column_names.is_empty() {
            if let Some(alias) = alias {
                chunk::write_dialect_quoted_ident(V::DIALECT, buf, alias);
            } else {
                if let Some(schema) = table.schema {
                    chunk::write_dialect_quoted_ident(V::DIALECT, buf, schema);
                    let _ = buf.write_char('.');
                }
                chunk::write_dialect_quoted_ident(V::DIALECT, buf, table.name);
            }
            let _ = buf.write_str(".*");
            return;
        }

        for (i, col_name) in table.column_names.iter().enumerate() {
            if i > 0 {
                let _ = buf.write_str(", ");
            }
            if let Some(alias) = alias {
                chunk::write_dialect_quoted_ident(V::DIALECT, buf, alias);
            } else {
                if let Some(schema) = table.schema {
                    chunk::write_dialect_quoted_ident(V::DIALECT, buf, schema);
                    let _ = buf.write_char('.');
                }
                chunk::write_dialect_quoted_ident(V::DIALECT, buf, table.name);
            }
            let _ = buf.write_char('.');
            chunk::write_dialect_quoted_ident(V::DIALECT, buf, col_name);
        }
    }

    /// Whether a space goes between the chunk at `index` and the next one.
    #[inline]
    fn needs_space(&self, index: usize) -> bool {
        let Some(next) = self.chunks.get(index + 1) else {
            return false;
        };

        let current = &self.chunks[index];
        chunk_needs_space(current, next)
    }

    #[inline]
    fn render_capacity_estimate(&self) -> (usize, usize) {
        let mut sql_cap = 0usize;
        let mut param_cap = 0usize;

        for chunk in &self.chunks {
            sql_cap = sql_cap.saturating_add(match chunk {
                SQLChunk::Ident(_) | SQLChunk::Raw(_) => 20,
                SQLChunk::Column(_) => 30,
                SQLChunk::Table(_) => 15,
                SQLChunk::Token(_) => 8,
                SQLChunk::Number(_) | SQLChunk::Param(_) => 4,
            });
            if matches!(chunk, SQLChunk::Param(_)) {
                param_cap = param_cap.saturating_add(1);
            }
        }

        (sql_cap.max(128), param_cap)
    }

    /// Returns the bound values, in order. Placeholders without a value are
    /// skipped.
    #[inline]
    pub fn params(&self) -> impl Iterator<Item = &V> + use<'_, V> {
        self.chunks.iter().filter_map(|chunk| {
            if let SQLChunk::Param(Param {
                value: Some(value), ..
            }) = chunk
            {
                Some(value.as_ref())
            } else {
                None
            }
        })
    }

    /// Fills named placeholders with values, matching by name.
    ///
    /// Placeholders whose name is not in `params` keep no value. Values can
    /// come from [`TypedPlaceholder::bind`](crate::TypedPlaceholder::bind),
    /// which also checks the value's SQL type.
    ///
    /// # Examples
    ///
    /// ```
    /// use drizzle_core::{ParamBind, Placeholder, SQL, ToSQL, Token};
    /// # use drizzle_core::{Dialect, SQLParam, SQLiteDialect};
    /// # use std::borrow::Cow;
    /// # #[derive(Debug, Clone, PartialEq)]
    /// # struct Value(i64);
    /// # impl SQLParam for Value {
    /// #     const DIALECT: Dialect = Dialect::SQLite;
    /// #     type DialectMarker = SQLiteDialect;
    /// # }
    /// # impl From<Value> for Cow<'_, Value> {
    /// #     fn from(value: Value) -> Self { Cow::Owned(value) }
    /// # }
    ///
    /// let sql: SQL<'_, Value> = SQL::ident("id")
    ///     .push(Token::EQ)
    ///     .append(Placeholder::named("id").into_sql());
    /// assert_eq!(sql.params().count(), 0);
    ///
    /// let bound = sql.bind([ParamBind::new("id", Value(3))]);
    /// assert_eq!(bound.sql(), r#""id" = :id"#);
    /// assert_eq!(bound.params().collect::<Vec<_>>(), [&Value(3)]);
    /// ```
    #[must_use]
    pub fn bind<T: SQLParam + Into<V>>(
        self,
        params: impl IntoIterator<Item: Into<ParamBind<'a, T>>>,
    ) -> Self {
        #[cfg(feature = "profiling")]
        profile_sql!("bind");

        let binds: SmallVec<[(&str, V); 4]> = params
            .into_iter()
            .map(Into::into)
            .map(|p| (p.name, p.value.into()))
            .collect();

        if binds.len() <= 4 {
            let bound_chunks: SmallVec<[SQLChunk<'a, V>; 8]> = self
                .chunks
                .into_iter()
                .map(|chunk| match chunk {
                    SQLChunk::Param(mut param) => {
                        if let Some(name) = param.placeholder.name
                            && let Some((_, value)) =
                                binds.iter().find(|(param_name, _)| *param_name == name)
                        {
                            param.value = Some(Cow::Owned(value.clone()));
                        }
                        SQLChunk::Param(param)
                    }
                    other => other,
                })
                .collect();

            return SQL {
                chunks: bound_chunks,
            };
        }

        let param_map: HashMap<&str, V> = binds.into_iter().collect();
        let bound_chunks: SmallVec<[SQLChunk<'a, V>; 8]> = self
            .chunks
            .into_iter()
            .map(|chunk| match chunk {
                SQLChunk::Param(mut param) => {
                    if let Some(name) = param.placeholder.name
                        && let Some(value) = param_map.get(name)
                    {
                        param.value = Some(Cow::Owned(value.clone()));
                    }
                    SQLChunk::Param(param)
                }
                other => other,
            })
            .collect();

        SQL {
            chunks: bound_chunks,
        }
    }
}

/// Tracks the `:name` parameters already bound for one `SQLite` statement.
///
/// `SQLite` gives every distinct parameter name a single slot, however often
/// the name appears, while each positional `?` takes its own slot. A value
/// list for the statement therefore holds one entry per distinct name, at the
/// position of the name's first occurrence.
#[derive(Default)]
pub(crate) struct SQLiteNamedParams<'n> {
    seen: SmallVec<[&'n str; 4]>,
}

impl<'n> SQLiteNamedParams<'n> {
    /// Records `name` and reports whether an earlier occurrence already took
    /// its slot.
    pub(crate) fn is_repeat(&mut self, name: &'n str) -> bool {
        if name.is_empty() {
            return false;
        }
        if self.seen.contains(&name) {
            true
        } else {
            self.seen.push(name);
            false
        }
    }
}

/// Whether a space goes between two adjacent chunks when rendering.
/// Shared by `SQL::write_to()` and `prepare_render()`.
#[inline]
pub(crate) fn chunk_needs_space<V: SQLParam>(
    current: &SQLChunk<'_, V>,
    next: &SQLChunk<'_, V>,
) -> bool {
    // No space if current raw text ends with space
    if let SQLChunk::Raw(text) = current
        && text.ends_with(' ')
    {
        return false;
    }

    // No space if next raw text starts with space
    if let SQLChunk::Raw(text) = next
        && text.starts_with(' ')
    {
        return false;
    }

    match (current, next) {
        // No space before closing/separator punctuation
        // or after opening punctuation
        (_, SQLChunk::Token(Token::RPAREN | Token::COMMA | Token::SEMI | Token::DOT))
        | (SQLChunk::Token(Token::LPAREN | Token::DOT), _) => false,
        // Space after comma
        (SQLChunk::Token(Token::COMMA), _) => true,
        // Space after closing paren if next is word-like (e.g., ") FROM")
        (SQLChunk::Token(Token::RPAREN), next) => next.is_word_like(),
        // MySQL requires built-in function names to touch the opening
        // parenthesis unless the session enables IGNORE_SPACE. SQL::func uses
        // a raw static function name followed by LPAREN.
        (SQLChunk::Raw(_), SQLChunk::Token(Token::LPAREN))
            if V::DIALECT == crate::Dialect::MySQL =>
        {
            false
        }
        // Space before opening paren if preceded by word-like (e.g., "AS (")
        (current, SQLChunk::Token(Token::LPAREN)) => current.is_word_like(),
        // Space around comparison/arithmetic operators
        (SQLChunk::Token(t), _) if t.is_operator() => true,
        (_, SQLChunk::Token(t)) if t.is_operator() => true,
        // Space between all word-like chunks
        _ => current.is_word_like() && next.is_word_like(),
    }
}

// ==================== trait implementations ====================

impl<V: SQLParam> Default for SQL<'_, V> {
    #[inline]
    fn default() -> Self {
        Self::empty()
    }
}

impl<'a, V: SQLParam + 'a> From<&'a str> for SQL<'a, V> {
    #[inline]
    fn from(s: &'a str) -> Self {
        SQL::raw(s)
    }
}

impl<V: SQLParam> From<Token> for SQL<'_, V> {
    #[inline]
    fn from(value: Token) -> Self {
        SQL::token(value)
    }
}

impl<'a, V: SQLParam + 'a> AsRef<Self> for SQL<'a, V> {
    #[inline]
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<V: SQLParam + core::fmt::Display> Display for SQL<'_, V> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Collect params for Debug formatting (iterator can't be used with :?)
        let params: Vec<_> = self.params().collect();
        write!(f, r#"sql: "{}", params: {:?}"#, self.sql(), params)
    }
}

impl<'a, V: SQLParam + 'a> ToSQL<'a, V> for SQL<'a, V> {
    fn to_sql(&self) -> Self {
        self.clone()
    }

    fn into_sql(self) -> Self {
        self
    }
}

impl<'a, V: SQLParam, T> FromIterator<T> for SQL<'a, V>
where
    SQLChunk<'a, V>: From<T>,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let chunks = iter
            .into_iter()
            .map(SQLChunk::from)
            .collect::<SmallVec<_>>();
        Self { chunks }
    }
}

impl<'a, V: SQLParam> IntoIterator for SQL<'a, V> {
    type Item = SQLChunk<'a, V>;
    type IntoIter = smallvec::IntoIter<[SQLChunk<'a, V>; 8]>;

    fn into_iter(self) -> Self::IntoIter {
        self.chunks.into_iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Dialect, MySQLDialect};

    #[derive(Clone, Debug)]
    struct TestParam;

    impl SQLParam for TestParam {
        const DIALECT: Dialect = Dialect::MySQL;
        type DialectMarker = MySQLDialect;
    }

    impl From<TestParam> for Cow<'_, TestParam> {
        fn from(value: TestParam) -> Self {
            Cow::Owned(value)
        }
    }

    #[test]
    fn owning_mapped_params_preserves_every_chunk_kind() {
        let raw = String::from("COALESCE(");
        let identifier = String::from("display_name");
        let sql = SQL::raw(raw.as_str())
            .append(SQL::ident(identifier.as_str()))
            .push(Token::COMMA)
            .append(SQL::param(TestParam))
            .push(Token::COMMA)
            .push(Param::<TestParam>::from(Placeholder::named("fallback")))
            .push(Token::RPAREN);

        let owned = sql.into_owned_with(|value| value);
        drop(raw);
        drop(identifier);

        assert_eq!(owned.sql(), "COALESCE( `display_name`, ?, ?)");
        assert_eq!(owned.params().count(), 1);
        assert_eq!(
            owned
                .chunks
                .iter()
                .filter(|chunk| matches!(chunk, SQLChunk::Param(param) if param.value.is_none()))
                .count(),
            1
        );
    }

    #[test]
    fn columns_renders_an_identifier_list() {
        let columns = [
            ColumnRef::sql("users", "first"),
            ColumnRef::sql("users", "last`name"),
        ];

        assert_eq!(
            SQL::<TestParam>::columns(&columns).sql(),
            "`first`, `last``name`"
        );
    }

    #[test]
    fn select_star_uses_the_table_alias_to_qualify_columns() {
        let table = TableRef::sql("users", &["id", "name"]);
        let query = SQL::<TestParam>::from(Token::SELECT)
            .push(Token::FROM)
            .append(SQL::table(table).alias("u"));

        assert_eq!(
            query.sql(),
            "SELECT `u`.`id`, `u`.`name` FROM `users` AS `u`"
        );
    }

    #[test]
    fn nested_select_star_keeps_derived_alias_in_outer_projection() {
        let source = SQL::<TestParam>::from(Token::SELECT)
            .push(Token::FROM)
            .append(SQL::table(TableRef::sql("posts", &["id", "name"])))
            .parens()
            .push(Token::AS)
            .append(SQL::table(TableRef::sql("post_rows", &[])));
        let query = SQL::<TestParam>::from(Token::SELECT)
            .push(Token::FROM)
            .append(SQL::table(TableRef::sql("users", &["id"])))
            .append(SQL::raw(" INNER JOIN LATERAL "))
            .append(source)
            .push(Token::ON)
            .append(SQL::raw("TRUE"));

        assert_eq!(
            query.sql(),
            "SELECT `users`.`id`, `post_rows`.* FROM `users` INNER JOIN LATERAL (SELECT `posts`.`id`, `posts`.`name` FROM `posts`) AS `post_rows` ON TRUE"
        );
    }
}