drizzle 0.3.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
//! Producer-parity: the schema **parser** and the derive **macros** must
//! produce the same snapshot for the same source.
//!
//! This file *is* its own fixture: the schema structs below are compiled by
//! the real macros (giving `Schema::to_snapshot()`), and the very same file
//! text is fed to `SchemaParser` via `include_str!`. The two producers'
//! DDL entity sets are then compared order-insensitively — so the parser can
//! never drift from what the macros actually emit without this test failing.
//!
//! Layout notes:
//! * The SQLite module comes first so the parser's `result.schema` (first
//!   schema struct in source order) is the SQLite one; the Postgres side is
//!   left unscoped, which matches runtime semantics because every Postgres
//!   item below is a schema member.
//! * The fixtures deliberately exercise the once-divergent shapes so parity
//!   locks them: FK targets with explicit `name = "..."` renames (both
//!   dialects), composite Postgres PKs (ONE entity per table), Postgres
//!   identity sequence options, index `method`/`where`/`concurrently`
//!   (implicit btree stays `None`), `UNIQUE ... NULLS NOT DISTINCT`, and a
//!   `#[postgres_enum(schema = "...")]` enum used across schemas. Opaque
//!   `query(...)` view definitions remain out of scope for the parser.

#[cfg(any(
    feature = "rusqlite",
    feature = "turso",
    feature = "libsql",
    feature = "postgres",
    feature = "mysql"
))]
mod parity_util {
    use std::collections::BTreeMap;

    /// Order-insensitive multiset comparison with a symmetric-difference
    /// report on mismatch.
    pub fn assert_entity_parity(label: &str, macro_side: Vec<String>, parser_side: Vec<String>) {
        let mut counts: BTreeMap<String, i64> = BTreeMap::new();
        for entity in &macro_side {
            *counts.entry(entity.clone()).or_default() += 1;
        }
        for entity in &parser_side {
            *counts.entry(entity.clone()).or_default() -= 1;
        }

        let only_macro: Vec<&String> = counts
            .iter()
            .filter(|(_, n)| **n > 0)
            .map(|(e, _)| e)
            .collect();
        let only_parser: Vec<&String> = counts
            .iter()
            .filter(|(_, n)| **n < 0)
            .map(|(e, _)| e)
            .collect();

        assert!(
            only_macro.is_empty() && only_parser.is_empty(),
            "{label}: parser and macro snapshots diverge\n\n\
             == entities only in the macro (Schema::to_snapshot) side ==\n{}\n\n\
             == entities only in the parser side ==\n{}\n",
            only_macro
                .iter()
                .map(|e| format!("  {e}"))
                .collect::<Vec<_>>()
                .join("\n"),
            only_parser
                .iter()
                .map(|e| format!("  {e}"))
                .collect::<Vec<_>>()
                .join("\n"),
        );
    }
}

// =============================================================================
// SQLite fixture + test
// =============================================================================

#[cfg(any(feature = "rusqlite", feature = "turso", feature = "libsql"))]
mod sqlite_parity {
    use drizzle::sqlite::prelude::*;

    #[SQLiteTable(strict)]
    pub struct Users {
        #[column(primary)]
        pub id: i64,
        #[column(unique)]
        pub email: String,
        #[column(default = "guest")]
        pub display_name: String,
        #[column(default = CURRENT_TIMESTAMP)]
        pub created_at: String,
        #[column(default = strftime("%s", "now"))]
        pub updated_at: i64,
        #[column(collate = NOCASE)]
        pub nickname: Option<String>,
    }

    // Composite primary key.
    #[SQLiteTable]
    pub struct OrderItems {
        #[column(primary)]
        pub order_id: i64,
        #[column(primary)]
        pub item_no: i64,
        pub quantity: i64,
    }

    // Column FK with actions, table-level composite FK + UNIQUE + CHECK,
    // generated stored + virtual columns.
    #[SQLiteTable(
        FOREIGN_KEY(
            columns(order_id, item_no),
            references(OrderItems, order_id, item_no),
            on_delete = "CASCADE"
        ),
        UNIQUE(columns(first, last), name = "shipments_name_unique"),
        CHECK(expr = "weight >= 0")
    )]
    pub struct Shipments {
        #[column(primary)]
        pub id: i64,
        pub order_id: i64,
        pub item_no: i64,
        #[column(references = Users::id, on_delete = SET_NULL, on_update = CASCADE)]
        pub courier_id: Option<i64>,
        pub first: String,
        pub last: String,
        pub weight: i64,
        #[column(generated(stored, "first || ' ' || last"))]
        pub full_name: String,
        #[column(generated(virtual, "weight * 2"))]
        pub double_weight: i64,
    }

    // Renamed FK targets: the explicit table name on `Registry` and the
    // explicit column name on `code` must surface in `RegistryEntries`' FK
    // entities (constraint name, target table, and target columns).
    #[SQLiteTable(name = "registry_master")]
    pub struct Registry {
        #[column(primary)]
        pub id: i64,
        #[column(unique, name = "registry_code")]
        pub code: String,
    }

    #[SQLiteTable(FOREIGN_KEY(
        columns(reg_id, reg_code),
        references(Registry, id, code),
        on_update = "CASCADE"
    ))]
    pub struct RegistryEntries {
        #[column(primary)]
        pub id: i64,
        #[column(name = "entry_registry_id")]
        pub reg_id: i64,
        pub reg_code: String,
        #[column(references = Registry::code, on_delete = SET_NULL)]
        pub linked_code: Option<String>,
    }

    #[SQLiteIndex(unique, where = "email IS NOT NULL")]
    pub struct UsersEmailIdx(Users::email);

    #[SQLiteView(DEFINITION = "SELECT id, email FROM users")]
    pub struct UserEmails {
        pub id: i64,
        pub email: String,
    }

    #[derive(SQLiteSchema)]
    pub struct SqliteParitySchema {
        pub users: Users,
        pub order_items: OrderItems,
        pub shipments: Shipments,
        pub registry: Registry,
        pub registry_entries: RegistryEntries,
        pub users_email_idx: UsersEmailIdx,
        pub user_emails: UserEmails,
    }

    #[test]
    fn sqlite_producer_parity() {
        use drizzle::migrations::parser::SchemaParser;
        use drizzle::migrations::schema::{Schema as _, Snapshot};
        use drizzle_types::Dialect;

        let macro_snapshot = match SqliteParitySchema::new().to_snapshot() {
            Snapshot::Sqlite(s) => s,
            Snapshot::Postgres(_) | Snapshot::MySQL(_) => panic!("expected a SQLite snapshot"),
        };

        let parsed = SchemaParser::parse(include_str!("parser_parity.rs"));
        assert!(
            parsed.errors.is_empty(),
            "parser reported errors on the fixture: {:?}",
            parsed.errors
        );
        let parser_snapshot = match drizzle::migrations::Snapshot::from_parse_result(
            &parsed,
            Dialect::SQLite,
            None,
        ) {
            Snapshot::Sqlite(s) => s,
            Snapshot::Postgres(_) | Snapshot::MySQL(_) => panic!("expected a SQLite snapshot"),
        };

        super::parity_util::assert_entity_parity(
            "sqlite",
            macro_snapshot
                .ddl
                .iter()
                .map(|e| format!("{e:?}"))
                .collect(),
            parser_snapshot
                .ddl
                .iter()
                .map(|e| format!("{e:?}"))
                .collect(),
        );

        // Presence checks: parity alone can't tell "both sides emit X"
        // from "both sides dropped X". Lock the partial-index predicate and
        // renamed-FK-target shapes on the macro side (parity extends them to
        // the parser side).
        use drizzle::migrations::sqlite::SqliteEntity;
        let email_index = macro_snapshot.ddl.iter().find_map(|entity| match entity {
            SqliteEntity::Index(index) if index.name.as_ref() == "users_email_idx" => Some(index),
            _ => None,
        });
        assert_eq!(
            email_index.and_then(|index| index.where_clause.as_deref()),
            Some("email IS NOT NULL"),
            "compiled SQLite schema dropped the partial-index predicate"
        );

        let fks: Vec<_> = macro_snapshot
            .ddl
            .iter()
            .filter_map(|e| match e {
                SqliteEntity::ForeignKey(fk) if fk.table.as_ref() == "registry_entries" => Some(fk),
                _ => None,
            })
            .collect();
        assert!(
            fks.iter().any(|fk| {
                fk.name.as_ref()
                    == "fk_registry_entries_linked_code_registry_master_registry_code_fk"
                    && fk.table_to.as_ref() == "registry_master"
                    && fk
                        .columns_to
                        .iter()
                        .map(AsRef::as_ref)
                        .eq(["registry_code"])
            }),
            "renamed single-column FK target not resolved: {fks:?}"
        );
        assert!(
            fks.iter().any(|fk| {
                fk.name.as_ref()
                    == "fk_registry_entries_entry_registry_id_reg_code_registry_master_id_registry_code_fk"
                    && fk.columns.iter().map(AsRef::as_ref).eq(["entry_registry_id", "reg_code"])
                    && fk.columns_to.iter().map(AsRef::as_ref).eq(["id", "registry_code"])
            }),
            "renamed composite FK source/target not resolved: {fks:?}"
        );
    }
}

// =============================================================================
// Postgres fixture + test
// =============================================================================

#[cfg(feature = "postgres")]
mod postgres_parity {
    use drizzle::postgres::prelude::*;

    #[derive(PostgresEnum, Default, Clone, Copy, PartialEq, Debug)]
    pub enum AccountStatus {
        #[default]
        Active,
        Suspended,
        Closed,
    }

    // Enum created in a non-public schema, used by a table in another
    // schema (`Accounts` lives in `public`).
    #[derive(PostgresEnum, Default, Clone, Copy, PartialEq, Debug)]
    #[postgres_enum(schema = "auth")]
    pub enum AuthRole {
        #[default]
        Member,
        Admin,
    }

    // An enum that is its schema's ONLY occupant: both producers must emit
    // the Schema entity, or the generated CREATE TYPE cannot apply.
    #[derive(PostgresEnum, Default, Clone, Copy, PartialEq, Debug)]
    #[postgres_enum(schema = "lookup")]
    pub enum Currency {
        #[default]
        Usd,
        Eur,
    }

    // Multi-schema: this table lives in `auth`. The explicit column name on
    // `handle` must surface in FK entities that reference it.
    #[PostgresTable(schema = "auth")]
    pub struct AuthUsers {
        #[column(primary)]
        pub id: i64,
        #[column(unique)]
        pub email: String,
        #[column(unique, name = "auth_handle")]
        pub handle: String,
    }

    /// Account records.
    #[PostgresTable(RLS)]
    pub struct Accounts {
        #[column(primary, identity(by_default))]
        pub id: i64,
        /// Current lifecycle state.
        #[column(enum)]
        pub status: AccountStatus,
        #[column(enum)]
        pub role: AuthRole,
        pub tags: Vec<String>,
        #[column(default = "basic")]
        pub tier: String,
        #[column(references = AuthUsers::id, on_delete = CASCADE, deferrable)]
        pub owner_id: i64,
        #[column(references = AuthUsers::handle)]
        pub owner_handle: String,
    }

    // Composite primary key (ONE PrimaryKey entity), identity sequence
    // options, and a table-level UNIQUE with NULLS NOT DISTINCT.
    #[PostgresTable(UNIQUE(columns(label), nulls_not_distinct))]
    pub struct AccountEvents {
        #[column(primary)]
        pub account_id: i64,
        #[column(primary)]
        pub seq: i64,
        #[column(identity(
            always,
            start = 100,
            increment = 5,
            min_value = 10,
            max_value = 100000,
            cache = 10,
            cycle
        ))]
        pub audit_no: i64,
        pub label: Option<String>,
    }

    #[PostgresIndex(unique)]
    pub struct AuthUsersEmailIdx(AuthUsers::email);

    // Explicit method + partial predicate + CONCURRENTLY. Implicit-btree
    // indexes (like AuthUsersEmailIdx above) must keep `method: None`.
    #[PostgresIndex(method = "hash", concurrent, where = "tier <> 'basic'")]
    pub struct AccountsTierIdx(Accounts::tier);

    #[PostgresView(DEFINITION = "SELECT id, tier FROM accounts")]
    pub struct AccountTiers {
        pub id: i64,
        pub tier: String,
    }

    #[PostgresPolicy(
        NAME = "accounts_owner_only",
        AS = "PERMISSIVE",
        FOR = "SELECT",
        TO(authenticated),
        USING = "owner_id = current_setting('app.user_id')::bigint"
    )]
    pub struct AccountsPolicy(Accounts);

    #[derive(PostgresSchema)]
    pub struct PostgresParitySchema {
        pub account_status: AccountStatus,
        pub auth_role: AuthRole,
        pub currency: Currency,
        pub auth_users: AuthUsers,
        pub accounts: Accounts,
        pub account_events: AccountEvents,
        pub auth_users_email_idx: AuthUsersEmailIdx,
        pub accounts_tier_idx: AccountsTierIdx,
        pub account_tiers: AccountTiers,
        pub accounts_policy: AccountsPolicy,
    }

    #[test]
    fn postgres_producer_parity() {
        use drizzle::migrations::parser::SchemaParser;
        use drizzle::migrations::schema::{Schema as _, Snapshot};
        use drizzle_types::Dialect;

        let macro_snapshot = match PostgresParitySchema::new().to_snapshot() {
            Snapshot::Postgres(s) => s,
            Snapshot::Sqlite(_) | Snapshot::MySQL(_) => panic!("expected a Postgres snapshot"),
        };

        let parsed = SchemaParser::parse(include_str!("parser_parity.rs"));
        assert!(
            parsed.errors.is_empty(),
            "parser reported errors on the fixture: {:?}",
            parsed.errors
        );
        let parser_snapshot = match drizzle::migrations::Snapshot::from_parse_result(
            &parsed,
            Dialect::PostgreSQL,
            None,
        ) {
            Snapshot::Postgres(s) => s,
            Snapshot::Sqlite(_) | Snapshot::MySQL(_) => panic!("expected a Postgres snapshot"),
        };

        super::parity_util::assert_entity_parity(
            "postgres",
            macro_snapshot
                .ddl
                .iter()
                .map(|e| format!("{e:?}"))
                .collect(),
            parser_snapshot
                .ddl
                .iter()
                .map(|e| format!("{e:?}"))
                .collect(),
        );

        // Presence checks: parity alone can't tell "both sides emit X"
        // from "both sides dropped X". Lock the once-divergent shapes on the
        // macro side (parity extends them to the parser side).
        use drizzle::migrations::postgres::PostgresEntity;
        let ddl = &macro_snapshot.ddl;

        // ONE composite PrimaryKey entity for account_events.
        let event_pks: Vec<_> = ddl
            .iter()
            .filter_map(|e| match e {
                PostgresEntity::PrimaryKey(pk) if pk.table.as_ref() == "account_events" => Some(pk),
                _ => None,
            })
            .collect();
        assert_eq!(
            event_pks.len(),
            1,
            "expected exactly one PrimaryKey entity: {event_pks:?}"
        );
        assert!(
            event_pks[0].name.as_ref() == "account_events_pkey"
                && event_pks[0]
                    .columns
                    .iter()
                    .map(AsRef::as_ref)
                    .eq(["account_id", "seq"]),
            "composite PK shape wrong: {event_pks:?}"
        );

        // A schema whose only occupant is an enum still gets its Schema
        // entity (CREATE TYPE lookup.currency needs CREATE SCHEMA lookup).
        assert!(
            ddl.iter().any(|e| matches!(
                e,
                PostgresEntity::Schema(s) if s.name.as_ref() == "lookup"
            )),
            "enum-only schema `lookup` must be registered as a Schema entity"
        );

        // Identity sequence options survive into the runtime snapshot.
        let audit_no = ddl
            .iter()
            .find_map(|e| match e {
                PostgresEntity::Column(c)
                    if c.table.as_ref() == "account_events" && c.name.as_ref() == "audit_no" =>
                {
                    Some(c)
                }
                _ => None,
            })
            .expect("audit_no column");
        let identity = audit_no.identity.as_ref().expect("identity");
        assert_eq!(identity.start_with.as_deref(), Some("100"));
        assert_eq!(identity.increment.as_deref(), Some("5"));
        assert_eq!(identity.min_value.as_deref(), Some("10"));
        assert_eq!(identity.max_value.as_deref(), Some("100000"));
        assert_eq!(identity.cache, Some(10));
        assert_eq!(identity.cycle, Some(true));

        // Index method/where/concurrently; implicit btree stays None.
        let tier_idx = ddl
            .iter()
            .find_map(|e| match e {
                PostgresEntity::Index(i) if i.name.as_ref() == "accounts_tier_idx" => Some(i),
                _ => None,
            })
            .expect("accounts_tier_idx");
        assert_eq!(tier_idx.method.as_deref(), Some("hash"));
        assert_eq!(tier_idx.where_clause.as_deref(), Some("tier <> 'basic'"));
        assert!(tier_idx.concurrently);
        let email_idx = ddl
            .iter()
            .find_map(|e| match e {
                PostgresEntity::Index(i) if i.name.as_ref() == "auth_users_email_idx" => Some(i),
                _ => None,
            })
            .expect("auth_users_email_idx");
        assert_eq!(email_idx.method, None, "implicit btree must stay None");

        // Table-level UNIQUE keeps NULLS NOT DISTINCT.
        assert!(
            ddl.iter().any(|e| matches!(
                e,
                PostgresEntity::UniqueConstraint(u)
                    if u.table.as_ref() == "account_events" && u.nulls_not_distinct
            )),
            "nulls_not_distinct dropped"
        );

        // Enum schema + cross-schema enum column type_schema.
        assert!(
            ddl.iter().any(|e| matches!(
                e,
                PostgresEntity::Enum(en)
                    if en.name.as_ref() == "AuthRole" && en.schema.as_ref() == "auth"
            )),
            "enum schema dropped"
        );
        let role_col = ddl
            .iter()
            .find_map(|e| match e {
                PostgresEntity::Column(c)
                    if c.table.as_ref() == "accounts" && c.name.as_ref() == "role" =>
                {
                    Some(c)
                }
                _ => None,
            })
            .expect("accounts.role column");
        assert_eq!(role_col.type_schema.as_deref(), Some("auth"));

        // FK target column resolves the explicit rename on AuthUsers.handle.
        assert!(
            ddl.iter().any(|e| matches!(
                e,
                PostgresEntity::ForeignKey(fk)
                    if fk.name.as_ref() == "accounts_owner_handle_fkey"
                        && fk.columns_to.iter().map(AsRef::as_ref).eq(["auth_handle"])
            )),
            "renamed PG FK target not resolved"
        );
    }
}

// =============================================================================
// MySQL fixture + test
// =============================================================================

#[cfg(feature = "mysql")]
mod mysql_parity {
    use drizzle::mysql::prelude::*;

    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, MySQLEnum)]
    pub enum AccountState {
        #[default]
        Pending,
        Active,
        Suspended,
    }

    #[MySQLTable(
        DATABASE = "parity_db",
        NAME = "mysql_parity_tenants",
        ENGINE = "InnoDB",
        DEFAULT_CHARSET = "utf8mb4",
        COLLATE = "utf8mb4_0900_ai_ci",
        COMMENT = "tenant records"
    )]
    pub struct Tenants {
        #[column(NAME = "tenant_key", PRIMARY, AUTO_INCREMENT)]
        pub id: u64,
        #[column(VARCHAR(255), UNIQUE)]
        pub slug: String,
    }

    #[MySQLTable(
        DATABASE = "parity_db",
        NAME = "mysql_parity_accounts",
        ENGINE = "InnoDB",
        DEFAULT_CHARSET = "utf8mb4",
        COLLATE = "utf8mb4_0900_ai_ci",
        UNIQUE(columns(label, state), name = "accounts_label_state_key"),
        CHECK(name = "accounts_login_count_check", expr = "login_count >= 0")
    )]
    pub struct Accounts {
        #[column(PRIMARY, AUTO_INCREMENT)]
        pub id: u64,
        #[column(REFERENCES = Tenants::id, ON_DELETE = CASCADE, ON_UPDATE = RESTRICT)]
        pub tenant_id: u64,
        #[column(ENUM, CHARSET = "utf8mb4", COLLATE = "utf8mb4_bin")]
        pub state: AccountState,
        #[column(SET("reader", "writer", "admin"))]
        pub roles: String,
        /// Rust API documentation, not MySQL schema metadata.
        #[column(VARCHAR(255))]
        pub label: String,
        #[column(COMMENT = "stored in the schema")]
        pub note: String,
        #[column(DEFAULT = 0, CHECK = "login_count >= 0")]
        pub login_count: u32,
        #[column(
            TIMESTAMP,
            DEFAULT = CURRENT_TIMESTAMP,
            ON_UPDATE = "CURRENT_TIMESTAMP"
        )]
        pub updated_at: String,
        #[column(generated(STORED, "CHAR_LENGTH(label)"))]
        pub label_length: u32,
    }

    #[MySQLIndex(unique, using = "HASH", algorithm = "INPLACE", lock = "NONE")]
    pub struct AccountsLabelIndex(Accounts::label);

    #[MySQLView(
        DATABASE = "parity_db",
        NAME = "active_account_labels",
        DEFINITION = "SELECT id, label FROM mysql_parity_accounts WHERE login_count > 0",
        ALGORITHM = "MERGE",
        SQL_SECURITY = "INVOKER",
        CHECK_OPTION
    )]
    pub struct ActiveAccountLabels {
        pub id: u64,
        pub label: String,
    }

    /// Long derived foreign-key names are hash-shortened (MySQL identifiers
    /// are at most 64 characters), and defaults use the canonical spelling.
    #[MySQLTable(
        DATABASE = "parity_db",
        NAME = "mysql_parity_organization_membership_invitations",
        DEFAULT_CHARSET = "utf8mb4",
        COLLATE = "utf8mb4_0900_ai_ci"
    )]
    pub struct OrganizationMembershipInvitations {
        #[column(PRIMARY, AUTO_INCREMENT)]
        pub id: u64,
        #[column(REFERENCES = Tenants::id)]
        pub inviting_organization_parent_tenant_id: u64,
        #[column(TEXT, DEFAULT = "hello")]
        pub greeting: String,
        #[column(VARCHAR(36), DEFAULT = UUID())]
        pub token: String,
    }

    #[MySQLTable(DATABASE = "parity_db", NAME = "mysql_parity_codes")]
    pub struct Codes {
        #[column(PRIMARY)]
        pub tenant: u64,
        #[column(PRIMARY)]
        pub code: u64,
    }

    /// Two table-level foreign keys starting with the same column must not
    /// derive the same name.
    #[MySQLTable(
        DATABASE = "parity_db",
        NAME = "mysql_parity_code_pairs",
        FOREIGN_KEY(columns(tenant, first_code), references(Codes, tenant, code)),
        FOREIGN_KEY(columns(tenant, second_code), references(Codes, tenant, code))
    )]
    pub struct CodePairs {
        #[column(PRIMARY)]
        pub id: u64,
        pub tenant: u64,
        pub first_code: u64,
        pub second_code: u64,
    }

    #[derive(MySQLSchema)]
    pub struct MySqlParitySchema {
        pub tenants: Tenants,
        pub accounts: Accounts,
        pub accounts_label_index: AccountsLabelIndex,
        pub active_account_labels: ActiveAccountLabels,
        pub invitations: OrganizationMembershipInvitations,
        pub codes: Codes,
        pub code_pairs: CodePairs,
    }

    #[test]
    fn mysql_producer_parity() {
        use drizzle::migrations::mysql::{
            GeneratedType, IndexAlgorithm, IndexLock, IndexMethod, InlineType, MySQLEntity,
            ReferentialAction,
        };
        use drizzle::migrations::parser::SchemaParser;
        use drizzle::migrations::schema::{Schema as _, Snapshot};
        use drizzle_types::Dialect;

        let macro_snapshot = match MySqlParitySchema::new().to_snapshot() {
            Snapshot::MySQL(snapshot) => snapshot,
            Snapshot::Sqlite(_) | Snapshot::Postgres(_) => panic!("expected a MySQL snapshot"),
        };

        let parsed = SchemaParser::parse(include_str!("parser_parity.rs"));
        assert!(
            parsed.errors.is_empty(),
            "parser reported errors on the fixture: {:?}",
            parsed.errors
        );
        let parser_snapshot =
            match drizzle::migrations::Snapshot::from_parse_result(&parsed, Dialect::MySQL, None) {
                Snapshot::MySQL(snapshot) => snapshot,
                Snapshot::Sqlite(_) | Snapshot::Postgres(_) => panic!("expected a MySQL snapshot"),
            };

        super::parity_util::assert_entity_parity(
            "mysql",
            macro_snapshot
                .ddl
                .iter()
                .map(|entity| format!("{entity:?}"))
                .collect(),
            parser_snapshot
                .ddl
                .iter()
                .map(|entity| format!("{entity:?}"))
                .collect(),
        );

        let ddl = &macro_snapshot.ddl;
        let accounts = ddl
            .iter()
            .find_map(|entity| match entity {
                MySQLEntity::Table(table) if table.name.as_ref() == "mysql_parity_accounts" => {
                    Some(table)
                }
                _ => None,
            })
            .expect("accounts table");
        assert_eq!(accounts.database.as_deref(), Some("parity_db"));
        assert_eq!(accounts.engine.as_deref(), Some("InnoDB"));
        assert_eq!(accounts.charset.as_deref(), Some("utf8mb4"));
        assert_eq!(accounts.collation.as_deref(), Some("utf8mb4_0900_ai_ci"));

        let column = |name: &str| {
            ddl.iter()
                .find_map(|entity| match entity {
                    MySQLEntity::Column(column)
                        if column.table.as_ref() == "mysql_parity_accounts"
                            && column.name.as_ref() == name =>
                    {
                        Some(column)
                    }
                    _ => None,
                })
                .unwrap_or_else(|| panic!("accounts.{name} column"))
        };
        assert_eq!(
            column("label").comment,
            None,
            "Rust docs became SQL COMMENT"
        );
        assert_eq!(
            column("note").comment.as_deref(),
            Some("stored in the schema")
        );
        assert!(matches!(
            column("state").inline_type.as_ref(),
            Some(InlineType::Enum(values))
                if values.values.iter().map(AsRef::as_ref).eq(["Pending", "Active", "Suspended"])
        ));
        assert!(matches!(
            column("roles").inline_type.as_ref(),
            Some(InlineType::Set(values))
                if values.values.iter().map(AsRef::as_ref).eq(["reader", "writer", "admin"])
        ));
        assert!(matches!(
            column("label_length").generated.as_ref(),
            Some(generated)
                if generated.expression.as_ref() == "CHAR_LENGTH(label)"
                    && generated.generation_type == GeneratedType::Stored
        ));
        assert_eq!(
            column("updated_at").on_update.as_deref(),
            Some("CURRENT_TIMESTAMP")
        );

        assert!(ddl.iter().any(|entity| matches!(
            entity,
            MySQLEntity::ForeignKey(foreign_key)
                if foreign_key.table.as_ref() == "mysql_parity_accounts"
                    && foreign_key.foreign_columns.iter().map(AsRef::as_ref).eq(["tenant_key"])
                    && foreign_key.on_delete == Some(ReferentialAction::Cascade)
                    && foreign_key.on_update == Some(ReferentialAction::Restrict)
        )));
        let foreign_key_names = ddl
            .iter()
            .filter_map(|entity| match entity {
                MySQLEntity::ForeignKey(foreign_key) => Some(foreign_key.name.as_ref()),
                _ => None,
            })
            .collect::<std::collections::BTreeSet<_>>();
        assert!(
            foreign_key_names.iter().all(|name| name.len() <= 64),
            "{foreign_key_names:?}"
        );
        assert!(
            foreign_key_names.contains(
                drizzle_types::mysql::names::foreign_key_name(
                    "mysql_parity_organization_membership_invitations",
                    &["inviting_organization_parent_tenant_id"],
                )
                .as_str()
            )
        );
        assert!(foreign_key_names.contains("mysql_parity_code_pairs_tenant_first_code_fkey"));
        assert!(foreign_key_names.contains("mysql_parity_code_pairs_tenant_second_code_fkey"));
        let default = |table: &str, name: &str| {
            ddl.iter().find_map(|entity| match entity {
                MySQLEntity::Column(column)
                    if column.table.as_ref() == table && column.name.as_ref() == name =>
                {
                    column.default.as_deref()
                }
                _ => None,
            })
        };
        let invitations = "mysql_parity_organization_membership_invitations";
        assert_eq!(default(invitations, "greeting"), Some("('hello')"));
        assert_eq!(default(invitations, "token"), Some("(UUID())"));

        assert!(ddl.iter().any(|entity| matches!(
            entity,
            MySQLEntity::Index(index)
                if index.name.as_ref() == "accounts_label_index"
                    && index.using == Some(IndexMethod::Hash)
                    && index.algorithm == Some(IndexAlgorithm::Inplace)
                    && index.lock == Some(IndexLock::None)
        )));
        assert!(ddl.iter().any(|entity| matches!(
            entity,
            MySQLEntity::View(view)
                if view.database.as_deref() == Some("parity_db")
                    && view.name.as_ref() == "active_account_labels"
                    && view.definition.as_deref()
                        == Some("SELECT id, label FROM mysql_parity_accounts WHERE login_count > 0")
                    && view.algorithm == Some(drizzle::migrations::mysql::ViewAlgorithm::Merge)
                    && view.sql_security
                        == Some(drizzle::migrations::mysql::ViewSqlSecurity::Invoker)
                    && view.check_option
                        == Some(drizzle::migrations::mysql::ViewCheckOption::Cascaded)
                    && view.definer.is_none()
                    && view.charset.is_none()
                    && view.collation.is_none()
        )));
    }
}