drizzle-core 0.3.1

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
use crate::SQLConstraintKind;
use crate::prelude::*;
use crate::{Dialect, Param, Placeholder, SQLParam, sql::tokens::Token};

// ==================== Dialect enums ====================

/// One value of an enum column type.
///
/// `label` is what a text column (or a `PostgreSQL` enum) stores, and
/// `discriminant` is what an integer column stores.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EnumVariantRef {
    /// The stored text label, usually the variant name.
    pub label: &'static str,
    /// The integer value of the variant.
    pub discriminant: i64,
}

/// The values an enum column type can hold, in declaration order.
///
/// Implemented by `#[derive(SQLiteEnum)]` and `#[derive(PostgresEnum)]`.
/// The table macros copy these into the column's [`ColumnDialect`]
/// metadata (`enum_variants`), so tools such as `drizzle-seed` can generate
/// only valid values.
pub trait SQLEnumVariants {
    /// Every variant, in declaration order.
    const VARIANTS: &'static [EnumVariantRef];
}

/// Column metadata that applies to one dialect only.
///
/// Generated by the table macros and read by migrations. The fields mirror
/// the column attributes (`default`, `generated`, `collate`, ...).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColumnDialect {
    SQLite {
        autoincrement: bool,
        default: Option<&'static str>,
        generated_expression: Option<&'static str>,
        generated_stored: bool,
        collate: Option<&'static str>,
        /// The values of an enum column, `None` for other columns.
        enum_variants: Option<&'static [EnumVariantRef]>,
    },
    PostgreSQL {
        postgres_type: &'static str,
        dimensions: Option<i32>,
        is_serial: bool,
        is_bigserial: bool,
        is_generated_identity: bool,
        is_identity_always: bool,
        default: Option<&'static str>,
        generated_expression: Option<&'static str>,
        generated_stored: bool,
        collate: Option<&'static str>,
        comment: Option<&'static str>,
        /// The values of an enum column, `None` for other columns.
        enum_variants: Option<&'static [EnumVariantRef]>,
    },
    MySQL {
        auto_increment: bool,
        default: Option<&'static str>,
        generated_expression: Option<&'static str>,
        generated_stored: bool,
        charset: Option<&'static str>,
        collate: Option<&'static str>,
        on_update: Option<&'static str>,
    },
}

/// Table metadata that applies to one dialect only.
///
/// Generated by the table macros and read by migrations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TableDialect {
    PostgreSQL {
        is_unlogged: bool,
        is_temporary: bool,
        inherits: Option<&'static str>,
        tablespace: Option<&'static str>,
        is_rls_enabled: bool,
        comment: Option<&'static str>,
    },
    SQLite {
        without_rowid: bool,
        strict: bool,
    },
    MySQL {
        is_temporary: bool,
        engine: Option<&'static str>,
        charset: Option<&'static str>,
        collate: Option<&'static str>,
        comment: Option<&'static str>,
    },
}

impl Default for TableDialect {
    fn default() -> Self {
        Self::PostgreSQL {
            is_unlogged: false,
            is_temporary: false,
            inherits: None,
            tablespace: None,
            is_rls_enabled: false,
            comment: None,
        }
    }
}

// ==================== Ref structs ====================

/// A foreign key constraint, as static metadata generated by the table
/// macros.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ForeignKeyRef {
    pub name: &'static str,
    pub name_explicit: bool,
    pub target_table: &'static str,
    pub target_schema: &'static str,
    pub source_columns: &'static [&'static str],
    pub target_columns: &'static [&'static str],
    pub on_delete: Option<&'static str>,
    pub on_update: Option<&'static str>,
    pub deferrable: bool,
    pub initially_deferred: bool,
}

/// A table's primary key columns, as static metadata.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PrimaryKeyRef {
    pub columns: &'static [&'static str],
}

/// A table constraint (`UNIQUE`, `CHECK`, ...), as static metadata.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConstraintRef {
    pub name: Option<&'static str>,
    pub name_explicit: bool,
    pub kind: SQLConstraintKind,
    pub columns: &'static [&'static str],
    pub check_expression: Option<&'static str>,
    pub deferrable: bool,
    pub initially_deferred: bool,
}

// ==================== Enhanced TableRef and ColumnRef ====================

/// A table's name, columns, and schema metadata, generated by the table
/// macros.
///
/// SQL rendering only reads `schema`, `name` and `column_names` (through
/// [`TableSqlRef`]). Migrations read the rest.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TableRef {
    // SQL rendering fields
    pub name: &'static str,
    pub column_names: &'static [&'static str],

    // Schema metadata
    pub schema: Option<&'static str>,
    pub qualified_name: &'static str,
    pub columns: &'static [ColumnRef],
    pub primary_key: Option<PrimaryKeyRef>,
    pub foreign_keys: &'static [ForeignKeyRef],
    pub constraints: &'static [ConstraintRef],
    pub dependency_names: &'static [&'static str],

    // Dialect-specific
    pub dialect: TableDialect,
}

impl TableRef {
    /// Creates a `TableRef` with just a name and column names, for SQL
    /// rendering.
    ///
    /// Metadata fields are empty. Use a struct literal when metadata
    /// matters.
    #[must_use]
    pub const fn sql(name: &'static str, column_names: &'static [&'static str]) -> Self {
        Self {
            name,
            column_names,
            schema: None,
            qualified_name: "",
            columns: &[],
            primary_key: None,
            foreign_keys: &[],
            constraints: &[],
            dependency_names: &[],
            dialect: TableDialect::PostgreSQL {
                is_unlogged: false,
                is_temporary: false,
                inherits: None,
                tablespace: None,
                is_rls_enabled: false,
                comment: None,
            },
        }
    }
}

/// The parts of a [`TableRef`] that SQL rendering needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TableSqlRef {
    pub schema: Option<&'static str>,
    pub name: &'static str,
    pub column_names: &'static [&'static str],
}

impl TableSqlRef {
    /// Copies the rendering fields out of a [`TableRef`].
    #[inline]
    #[must_use]
    pub const fn from_table_ref(table: TableRef) -> Self {
        Self {
            schema: table.schema,
            name: table.name,
            column_names: table.column_names,
        }
    }

    /// Copies the rendering fields out of a borrowed [`TableRef`].
    #[inline]
    #[must_use]
    pub const fn from_table_ref_ref(table: &TableRef) -> Self {
        Self {
            schema: table.schema,
            name: table.name,
            column_names: table.column_names,
        }
    }
}

impl From<&TableRef> for TableSqlRef {
    #[inline]
    fn from(value: &TableRef) -> Self {
        Self::from_table_ref_ref(value)
    }
}

impl From<TableRef> for TableSqlRef {
    #[inline]
    fn from(value: TableRef) -> Self {
        Self::from_table_ref(value)
    }
}

/// Column metadata flags for [`ColumnRef`], packed into one byte.
///
/// Holds the `NOT NULL`, primary-key, `UNIQUE` and has-default bits.
///
/// # Examples
///
/// ```
/// use drizzle_core::ColumnFlags;
///
/// let flags = ColumnFlags::NOT_NULL | ColumnFlags::PRIMARY_KEY;
/// assert!(flags.contains(ColumnFlags::NOT_NULL));
/// assert!(!flags.contains(ColumnFlags::UNIQUE));
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct ColumnFlags(u8);

impl ColumnFlags {
    /// Column is declared `NOT NULL`.
    pub const NOT_NULL: Self = Self(1 << 0);
    /// Column participates in the table's primary key.
    pub const PRIMARY_KEY: Self = Self(1 << 1);
    /// Column has a `UNIQUE` constraint.
    pub const UNIQUE: Self = Self(1 << 2);
    /// Column has a `DEFAULT` clause.
    pub const HAS_DEFAULT: Self = Self(1 << 3);

    /// Returns a flag set with no bits set.
    #[must_use]
    pub const fn empty() -> Self {
        Self(0)
    }

    /// Reconstructs a flag set from its raw byte representation.
    #[must_use]
    pub const fn from_bits(bits: u8) -> Self {
        Self(bits)
    }

    /// Returns the raw byte representation.
    #[must_use]
    pub const fn bits(self) -> u8 {
        self.0
    }

    /// Returns `true` when every bit in `other` is set in `self`.
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// Returns the union of two flag sets.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

impl core::ops::BitOr for ColumnFlags {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        self.union(rhs)
    }
}

impl core::ops::BitOrAssign for ColumnFlags {
    fn bitor_assign(&mut self, rhs: Self) {
        *self = self.union(rhs);
    }
}

/// A column's table, name, and schema metadata, generated by the table
/// macros.
///
/// SQL rendering only reads `table` and `name` (through [`ColumnSqlRef`]).
/// Migrations read the rest.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColumnRef {
    // SQL rendering fields
    pub table: &'static str,
    pub name: &'static str,

    // Schema metadata
    pub sql_type: &'static str,
    pub flags: ColumnFlags,

    // Dialect-specific
    pub dialect: ColumnDialect,
}

impl ColumnRef {
    /// Creates a `ColumnRef` with just a table and column name, for SQL
    /// rendering.
    ///
    /// Metadata fields are empty. Use a struct literal when metadata
    /// matters.
    #[must_use]
    pub const fn sql(table: &'static str, name: &'static str) -> Self {
        Self {
            table,
            name,
            sql_type: "",
            flags: ColumnFlags::empty(),
            dialect: ColumnDialect::SQLite {
                autoincrement: false,
                default: None,
                generated_expression: None,
                generated_stored: false,
                collate: None,
                enum_variants: None,
            },
        }
    }

    /// Returns `true` if this column is declared `NOT NULL`.
    #[must_use]
    pub const fn not_null(&self) -> bool {
        self.flags.contains(ColumnFlags::NOT_NULL)
    }

    /// Returns `true` if this column participates in the primary key.
    #[must_use]
    pub const fn primary_key(&self) -> bool {
        self.flags.contains(ColumnFlags::PRIMARY_KEY)
    }

    /// Returns `true` if this column has a `UNIQUE` constraint.
    #[must_use]
    pub const fn unique(&self) -> bool {
        self.flags.contains(ColumnFlags::UNIQUE)
    }

    /// Returns `true` if this column has a `DEFAULT` clause.
    #[must_use]
    pub const fn has_default(&self) -> bool {
        self.flags.contains(ColumnFlags::HAS_DEFAULT)
    }
}

/// The parts of a [`ColumnRef`] that SQL rendering needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColumnSqlRef {
    pub table: &'static str,
    pub name: &'static str,
}

impl ColumnSqlRef {
    /// Copies the rendering fields out of a [`ColumnRef`].
    #[inline]
    #[must_use]
    pub const fn from_column_ref(column: ColumnRef) -> Self {
        Self {
            table: column.table,
            name: column.name,
        }
    }

    /// Copies the rendering fields out of a borrowed [`ColumnRef`].
    #[inline]
    #[must_use]
    pub const fn from_column_ref_ref(column: &ColumnRef) -> Self {
        Self {
            table: column.table,
            name: column.name,
        }
    }
}

impl From<&ColumnRef> for ColumnSqlRef {
    #[inline]
    fn from(value: &ColumnRef) -> Self {
        Self::from_column_ref_ref(value)
    }
}

impl From<ColumnRef> for ColumnSqlRef {
    #[inline]
    fn from(value: ColumnRef) -> Self {
        Self::from_column_ref(value)
    }
}

// ==================== Identifier quoting ====================

/// Writes `name` as a double-quoted SQL identifier, doubling any embedded
/// `"`.
///
/// Always uses double quotes, so it is wrong for MySQL. Rendering a [`SQL`](crate::SQL)
/// fragment picks the right quote for its dialect on its own.
///
/// # Examples
///
/// ```
/// let mut buf = String::new();
/// drizzle_core::sql::write_quoted_ident(&mut buf, r#"odd"name"#);
/// assert_eq!(buf, r#""odd""name""#);
/// ```
#[inline]
pub fn write_quoted_ident(buf: &mut impl core::fmt::Write, name: &str) {
    write_dialect_quoted_ident(Dialect::SQLite, buf, name);
}

/// Writes `name` as a quoted identifier for `dialect`.
///
/// PostgreSQL and SQLite use `"..."`; MySQL uses backticks. Embedded quote
/// characters are doubled so a runtime name cannot end the identifier
/// early.
#[inline]
pub(crate) fn write_dialect_quoted_ident(
    dialect: Dialect,
    buf: &mut impl core::fmt::Write,
    name: &str,
) {
    let delimiter = match dialect {
        Dialect::MySQL => '`',
        Dialect::SQLite | Dialect::PostgreSQL => '"',
    };

    let _ = buf.write_char(delimiter);
    if name.contains(delimiter) {
        for ch in name.chars() {
            if ch == delimiter {
                let _ = buf.write_char(delimiter);
                let _ = buf.write_char(delimiter);
            } else {
                let _ = buf.write_char(ch);
            }
        }
    } else {
        let _ = buf.write_str(name);
    }
    let _ = buf.write_char(delimiter);
}

// ==================== SQLChunk ====================

/// One piece of a [`SQL`](crate::SQL) fragment.
///
/// The renderer puts spaces between chunks where SQL needs them, so chunks
/// never carry their own surrounding whitespace.
#[derive(Clone)]
pub enum SQLChunk<'a, V: SQLParam> {
    /// A keyword, operator or punctuation: `SELECT`, `=`, `(`, ...
    Token(Token),

    /// A quoted identifier (table, column or alias name): `"name"`, or
    /// `` `name` `` for MySQL.
    Ident(Cow<'a, str>),

    /// Raw SQL text, written as-is with no quoting: function names,
    /// expressions.
    Raw(Cow<'a, str>),

    /// An unsigned integer literal written into the SQL text, for clauses
    /// such as `LIMIT` and `OFFSET` that are not parameterized.
    Number(usize),

    /// A placeholder and its bound value: `?`, `$1` or `:name`, depending on
    /// the dialect and the placeholder.
    Param(Param<'a, V>),

    /// A table, rendered as `"schema"."table"` or `"table"`. Its column names
    /// are used to expand an empty `SELECT` projection.
    Table(TableSqlRef),

    /// A column, rendered as `"table"."column"`.
    Column(ColumnSqlRef),
}

impl<'a, V: SQLParam> SQLChunk<'a, V> {
    // ==================== const constructors ====================

    /// Creates a token chunk.
    #[inline]
    #[must_use]
    pub const fn token(t: Token) -> Self {
        Self::Token(t)
    }

    /// Creates a quoted identifier from a static string.
    #[inline]
    #[must_use]
    pub const fn ident_static(name: &'static str) -> Self {
        Self::Ident(Cow::Borrowed(name))
    }

    /// Creates raw SQL text from a static string.
    #[inline]
    #[must_use]
    pub const fn raw_static(text: &'static str) -> Self {
        Self::Raw(Cow::Borrowed(text))
    }

    /// Creates a table chunk.
    #[inline]
    #[must_use]
    pub const fn table(table: TableRef) -> Self {
        Self::Table(TableSqlRef::from_table_ref(table))
    }

    /// Creates a column chunk.
    #[inline]
    #[must_use]
    pub const fn column(column: ColumnRef) -> Self {
        Self::Column(ColumnSqlRef::from_column_ref(column))
    }

    /// Creates a parameter chunk that borrows its value.
    #[inline]
    pub const fn param_borrowed(value: &'a V, placeholder: Placeholder) -> Self {
        Self::Param(Param {
            value: Some(Cow::Borrowed(value)),
            placeholder,
        })
    }

    // ==================== non-const constructors ====================

    /// Creates a quoted identifier.
    #[inline]
    pub fn ident(name: impl Into<Cow<'a, str>>) -> Self {
        Self::Ident(name.into())
    }

    /// Creates raw SQL text.
    #[inline]
    pub fn raw(text: impl Into<Cow<'a, str>>) -> Self {
        Self::Raw(text.into())
    }

    /// Creates an unsigned integer literal chunk.
    #[inline]
    #[must_use]
    pub const fn number(value: usize) -> Self {
        Self::Number(value)
    }

    /// Creates a parameter chunk with a value and placeholder.
    #[inline]
    pub fn param(value: impl Into<Cow<'a, V>>, placeholder: Placeholder) -> Self {
        Self::Param(Param {
            value: Some(value.into()),
            placeholder,
        })
    }

    // ==================== write implementation ====================

    /// Writes the chunk's text to `buf`, without surrounding spaces.
    #[inline]
    pub(crate) fn write(&self, buf: &mut impl core::fmt::Write) {
        match self {
            SQLChunk::Token(token) => {
                let _ = buf.write_str(token.as_str());
            }
            SQLChunk::Ident(name) => {
                write_dialect_quoted_ident(V::DIALECT, buf, name);
            }
            SQLChunk::Raw(text) => {
                let _ = buf.write_str(text);
            }
            SQLChunk::Number(value) => {
                let _ = write!(buf, "{value}");
            }
            SQLChunk::Param(Param { placeholder, .. }) => {
                let _ = write!(buf, "{placeholder}");
            }
            SQLChunk::Table(t) => {
                if let Some(schema) = t.schema {
                    write_dialect_quoted_ident(V::DIALECT, buf, schema);
                    let _ = buf.write_char('.');
                }
                write_dialect_quoted_ident(V::DIALECT, buf, t.name);
            }
            SQLChunk::Column(c) => {
                write_dialect_quoted_ident(V::DIALECT, buf, c.table);
                let _ = buf.write_char('.');
                write_dialect_quoted_ident(V::DIALECT, buf, c.name);
            }
        }
    }

    /// Whether the chunk is word-like, needing a space before another
    /// word-like chunk.
    #[inline]
    pub(crate) const fn is_word_like(&self) -> bool {
        match self {
            SQLChunk::Token(t) => !t.is_punctuation() && !t.is_operator(),
            SQLChunk::Ident(_)
            | SQLChunk::Raw(_)
            | SQLChunk::Number(_)
            | SQLChunk::Param(_)
            | SQLChunk::Table(_)
            | SQLChunk::Column(_) => true,
        }
    }
}

impl<V: SQLParam + core::fmt::Debug> core::fmt::Debug for SQLChunk<'_, V> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            SQLChunk::Token(token) => f.debug_tuple("Token").field(token).finish(),
            SQLChunk::Ident(name) => f.debug_tuple("Ident").field(name).finish(),
            SQLChunk::Raw(text) => f.debug_tuple("Raw").field(text).finish(),
            SQLChunk::Number(value) => f.debug_tuple("Number").field(value).finish(),
            SQLChunk::Param(param) => f.debug_tuple("Param").field(param).finish(),
            SQLChunk::Table(t) => f
                .debug_tuple("Table")
                .field(&t.schema)
                .field(&t.name)
                .finish(),
            SQLChunk::Column(c) => f
                .debug_tuple("Column")
                .field(&format!("{}.{}", c.table, c.name))
                .finish(),
        }
    }
}

// ==================== From implementations ====================

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

impl<V: SQLParam> From<TableRef> for SQLChunk<'_, V> {
    #[inline]
    fn from(value: TableRef) -> Self {
        Self::Table(value.into())
    }
}

impl<V: SQLParam> From<ColumnRef> for SQLChunk<'_, V> {
    #[inline]
    fn from(value: ColumnRef) -> Self {
        Self::Column(value.into())
    }
}

impl<'a, V: SQLParam> From<Param<'a, V>> for SQLChunk<'a, V> {
    #[inline]
    fn from(value: Param<'a, V>) -> Self {
        Self::Param(value)
    }
}

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

    #[allow(dead_code)]
    #[derive(Clone, Debug)]
    struct TestParam([usize; 4]);

    impl SQLParam for TestParam {
        const DIALECT: Dialect = Dialect::SQLite;
        type DialectMarker = SQLiteDialect;
    }

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

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

    #[test]
    fn sql_chunk_stays_slim() {
        // Param is the dominant variant for this 32-byte test parameter.
        assert!(size_of::<SQLChunk<'static, TestParam>>() <= 64);
    }

    #[test]
    fn quoted_ident_uses_the_dialect_delimiter() {
        let mut sqlite = String::new();
        write_dialect_quoted_ident(Dialect::SQLite, &mut sqlite, "account\"owner");
        assert_eq!(sqlite, "\"account\"\"owner\"");

        let mut postgres = String::new();
        write_dialect_quoted_ident(Dialect::PostgreSQL, &mut postgres, "account\"owner");
        assert_eq!(postgres, "\"account\"\"owner\"");

        let mut mysql = String::new();
        write_dialect_quoted_ident(Dialect::MySQL, &mut mysql, "account`owner");
        assert_eq!(mysql, "`account``owner`");
    }

    #[test]
    fn quoted_ident_keeps_injection_text_inside_the_identifier() {
        let mut mysql = String::new();
        write_dialect_quoted_ident(Dialect::MySQL, &mut mysql, "users`; DROP TABLE audit; --");
        assert_eq!(mysql, "`users``; DROP TABLE audit; --`");
    }

    #[test]
    fn table_chunk_preserves_structured_mysql_database_qualification() {
        let table = TableRef {
            schema: Some("tenant`db"),
            ..TableRef::sql("user`accounts", &["id"])
        };
        let chunk = SQLChunk::<MySQLTestParam>::table(table);
        let mut sql = String::new();

        chunk.write(&mut sql);

        assert_eq!(sql, "`tenant``db`.`user``accounts`");
    }
}