drizzle-types 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
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
//! MySQL schema objects as stored in migration snapshots.
//!
//! The migration tooling builds these from your schema or by introspecting a
//! live database, saves them in snapshot files, and diffs two sets to plan a
//! migration. A full schema is a list of [`MySQLEntity`] values.
//!
//! Every entity has a `database` field. `None` means the connection's current
//! database. SQL fragments (`sql_type`, defaults, expressions, view
//! definitions) are stored as written and are trusted schema SQL.

use crate::alloc_prelude::*;

#[cfg(feature = "serde")]
use crate::serde_helpers::{cow_from_string, cow_option_from_string, cow_vec_from_strings};

/// Storage mode for a generated MySQL column.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum GeneratedType {
    /// `VIRTUAL`: computed when read.
    Virtual,
    /// `STORED`: computed on write and stored. The default.
    #[default]
    Stored,
}

/// The `GENERATED ALWAYS AS (...)` part of a column definition.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Generated {
    #[cfg_attr(
        feature = "serde",
        serde(rename = "as", deserialize_with = "cow_from_string")
    )]
    /// SQL expression that computes the value (serialized as `as`).
    pub expression: Cow<'static, str>,
    /// Whether the value is stored or virtual (serialized as `type`).
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub generation_type: GeneratedType,
}

impl Generated {
    /// Creates a `STORED` generated column from a SQL expression.
    #[must_use]
    pub fn stored(expression: impl Into<Cow<'static, str>>) -> Self {
        Self {
            expression: expression.into(),
            generation_type: GeneratedType::Stored,
        }
    }

    /// Creates a `VIRTUAL` generated column from a SQL expression.
    #[must_use]
    pub fn virtual_column(expression: impl Into<Cow<'static, str>>) -> Self {
        Self {
            expression: expression.into(),
            generation_type: GeneratedType::Virtual,
        }
    }
}

/// The allowed values of an inline `ENUM(...)` or `SET(...)` column type, in
/// declaration order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct InlineEnum {
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_vec_from_strings"))]
    pub values: Vec<Cow<'static, str>>,
}

impl InlineEnum {
    /// Creates the value list from any iterable of strings.
    #[must_use]
    pub fn new(values: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            values: values
                .into_iter()
                .map(|value| Cow::Owned(value.into()))
                .collect(),
        }
    }
}

/// The values of an inline `ENUM` or `SET` column, kept beside its rendered
/// `sql_type` so a diff can compare them without parsing SQL.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(tag = "kind", content = "definition", rename_all = "lowercase")
)]
pub enum InlineType {
    /// `ENUM('a', 'b', ...)`: exactly one of the values.
    Enum(InlineEnum),
    /// `SET('a', 'b', ...)`: any combination of the values.
    Set(InlineEnum),
}

/// A table, with its table options. Columns, keys and indexes are separate
/// entities that name the table.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Table {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "core::ops::Not::not")
    )]
    /// `CREATE TEMPORARY TABLE`.
    pub temporary: bool,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    /// Storage engine, such as `InnoDB`.
    pub engine: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub charset: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub collation: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub comment: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    /// Other table options, which drizzle keeps but cannot change.
    pub options: Vec<TableOption>,
}

impl Table {
    /// Creates a table in the current database with no options set.
    #[must_use]
    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
        Self {
            database: None,
            name: name.into(),
            temporary: false,
            engine: None,
            charset: None,
            collation: None,
            comment: None,
            options: Vec::new(),
        }
    }
}

/// A table column and its full MySQL definition.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Column {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    #[cfg_attr(
        feature = "serde",
        serde(rename = "type", deserialize_with = "cow_from_string")
    )]
    /// Column type as written in DDL, such as `varchar(255)` or
    /// `int unsigned` (serialized as `type`).
    pub sql_type: Cow<'static, str>,
    /// `NOT NULL`.
    #[cfg_attr(feature = "serde", serde(default))]
    pub not_null: bool,
    /// `AUTO_INCREMENT`.
    #[cfg_attr(feature = "serde", serde(default))]
    pub autoincrement: bool,
    /// Whether the column is part of the primary key.
    #[cfg_attr(feature = "serde", serde(default))]
    pub primary_key: bool,
    /// Whether the column has a single-column unique constraint.
    #[cfg_attr(feature = "serde", serde(default))]
    pub unique: bool,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    /// `DEFAULT` value, as SQL.
    pub default: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    /// `ON UPDATE` value, as SQL, such as `CURRENT_TIMESTAMP`.
    pub on_update: Option<Cow<'static, str>>,
    /// `GENERATED ALWAYS AS (...)`, for a generated column.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub generated: Option<Generated>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// Values of an `ENUM` or `SET` column.
    pub inline_type: Option<InlineType>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub charset: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub collation: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub comment: Option<Cow<'static, str>>,
}

impl Column {
    /// Creates a nullable column with no default, constraints or options.
    #[must_use]
    pub fn new(
        table: impl Into<Cow<'static, str>>,
        name: impl Into<Cow<'static, str>>,
        sql_type: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            database: None,
            table: table.into(),
            name: name.into(),
            sql_type: sql_type.into(),
            not_null: false,
            autoincrement: false,
            primary_key: false,
            unique: false,
            default: None,
            on_update: None,
            generated: None,
            inline_type: None,
            charset: None,
            collation: None,
            comment: None,
        }
    }
}

/// One key part of an index: a column name or a SQL expression.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct IndexColumn {
    #[cfg_attr(
        feature = "serde",
        serde(alias = "value", deserialize_with = "cow_from_string")
    )]
    /// The column name, or the SQL expression when `is_expression` is set.
    /// drizzle-kit writes it as `value`.
    pub expression: Cow<'static, str>,
    /// Whether `expression` is a SQL expression rather than a column name.
    #[cfg_attr(feature = "serde", serde(default))]
    pub is_expression: bool,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// Prefix length, as in `name(10)`.
    pub length: Option<u32>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// Sort order: `Some(true)` for `ASC`, `Some(false)` for `DESC`, `None`
    /// when not written (ascending).
    pub ascending: Option<bool>,
}

impl IndexColumn {
    /// Creates a key part for a column.
    #[must_use]
    pub fn column(name: impl Into<Cow<'static, str>>) -> Self {
        Self {
            expression: name.into(),
            is_expression: false,
            length: None,
            ascending: None,
        }
    }

    /// Creates a key part for a SQL expression.
    #[must_use]
    pub fn expression(sql: impl Into<Cow<'static, str>>) -> Self {
        Self {
            expression: sql.into(),
            is_expression: true,
            length: None,
            ascending: None,
        }
    }
}

/// A table option drizzle does not model, kept as a name and value so it is
/// not silently dropped. The planner reports changes to these as unsupported.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TableOption {
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    /// Option name.
    pub name: Cow<'static, str>,
    /// Option value, as SQL.
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub value: Cow<'static, str>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
/// Index type, from `USING BTREE` or `USING HASH`.
pub enum IndexMethod {
    /// `BTREE`.
    Btree,
    /// `HASH`.
    Hash,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
/// `ALGORITHM` option used when creating an index.
pub enum IndexAlgorithm {
    /// `ALGORITHM = DEFAULT`.
    Default,
    /// `ALGORITHM = INPLACE`.
    Inplace,
    /// `ALGORITHM = COPY`.
    Copy,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
/// `LOCK` option used when creating an index.
pub enum IndexLock {
    /// `LOCK = DEFAULT`.
    Default,
    /// `LOCK = NONE`.
    None,
    /// `LOCK = SHARED`.
    Shared,
    /// `LOCK = EXCLUSIVE`.
    Exclusive,
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
/// An index on a table.
pub struct Index {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    /// Key parts, in order.
    pub columns: Vec<IndexColumn>,
    /// `UNIQUE INDEX`.
    #[cfg_attr(feature = "serde", serde(default))]
    pub unique: bool,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub using: Option<IndexMethod>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub algorithm: Option<IndexAlgorithm>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub lock: Option<IndexLock>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub comment: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// `VISIBLE` (`Some(true)`) or `INVISIBLE` (`Some(false)`); `None`
    /// means not written (visible).
    pub visible: Option<bool>,
}

impl Index {
    /// Creates a non-unique index with no options.
    #[must_use]
    pub fn new(
        table: impl Into<Cow<'static, str>>,
        name: impl Into<Cow<'static, str>>,
        columns: Vec<IndexColumn>,
    ) -> Self {
        Self {
            database: None,
            table: table.into(),
            name: name.into(),
            columns,
            unique: false,
            using: None,
            algorithm: None,
            lock: None,
            comment: None,
            visible: None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
/// A table's primary key.
pub struct PrimaryKey {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub name: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_vec_from_strings"))]
    pub columns: Vec<Cow<'static, str>>,
}

impl PrimaryKey {
    /// Creates a primary key over `columns`, named `PRIMARY` (MySQL's fixed
    /// name for primary keys).
    #[must_use]
    pub fn new(
        table: impl Into<Cow<'static, str>>,
        columns: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
    ) -> Self {
        Self {
            database: None,
            table: table.into(),
            name: Some(Cow::Borrowed("PRIMARY")),
            columns: columns.into_iter().map(Into::into).collect(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
/// A named unique constraint.
pub struct UniqueConstraint {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_vec_from_strings"))]
    pub columns: Vec<Cow<'static, str>>,
}

impl UniqueConstraint {
    /// Creates a unique constraint over `columns`.
    #[must_use]
    pub fn new(
        table: impl Into<Cow<'static, str>>,
        name: impl Into<Cow<'static, str>>,
        columns: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
    ) -> Self {
        Self {
            database: None,
            table: table.into(),
            name: name.into(),
            columns: columns.into_iter().map(Into::into).collect(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Foreign key `ON DELETE` / `ON UPDATE` action. Serialized as the SQL
/// keywords (`"CASCADE"`, `"SET NULL"`, ...).
pub enum ReferentialAction {
    /// `CASCADE`.
    #[cfg_attr(feature = "serde", serde(rename = "CASCADE"))]
    Cascade,
    /// `SET NULL`.
    #[cfg_attr(feature = "serde", serde(rename = "SET NULL"))]
    SetNull,
    /// `RESTRICT`.
    #[cfg_attr(feature = "serde", serde(rename = "RESTRICT"))]
    Restrict,
    /// `NO ACTION`.
    #[cfg_attr(feature = "serde", serde(rename = "NO ACTION"))]
    NoAction,
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
/// A foreign key from `table(columns)` to `foreign_table(foreign_columns)`.
pub struct ForeignKey {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_vec_from_strings"))]
    pub columns: Vec<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    /// Database of the referenced table; `None` for the current database.
    pub foreign_database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub foreign_table: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_vec_from_strings"))]
    pub foreign_columns: Vec<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// `ON DELETE` action; `None` when not written.
    pub on_delete: Option<ReferentialAction>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// `ON UPDATE` action; `None` when not written.
    pub on_update: Option<ReferentialAction>,
}

impl ForeignKey {
    /// Creates a foreign key with no `ON DELETE` / `ON UPDATE` actions.
    #[must_use]
    pub fn new(
        table: impl Into<Cow<'static, str>>,
        name: impl Into<Cow<'static, str>>,
        columns: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
        foreign_table: impl Into<Cow<'static, str>>,
        foreign_columns: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
    ) -> Self {
        Self {
            database: None,
            table: table.into(),
            name: name.into(),
            columns: columns.into_iter().map(Into::into).collect(),
            foreign_database: None,
            foreign_table: foreign_table.into(),
            foreign_columns: foreign_columns.into_iter().map(Into::into).collect(),
            on_delete: None,
            on_update: None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
/// A named `CHECK` constraint.
pub struct CheckConstraint {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    /// The check expression. drizzle-kit writes it as `value`.
    #[cfg_attr(
        feature = "serde",
        serde(alias = "value", deserialize_with = "cow_from_string")
    )]
    pub expression: Cow<'static, str>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// `ENFORCED` (`Some(true)`) or `NOT ENFORCED` (`Some(false)`); `None`
    /// means not written (enforced).
    pub enforced: Option<bool>,
}

impl CheckConstraint {
    /// Creates a check constraint from a SQL boolean expression.
    #[must_use]
    pub fn new(
        table: impl Into<Cow<'static, str>>,
        name: impl Into<Cow<'static, str>>,
        expression: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            database: None,
            table: table.into(),
            name: name.into(),
            expression: expression.into(),
            enforced: None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
/// View `ALGORITHM`.
pub enum ViewAlgorithm {
    /// `UNDEFINED`: MySQL chooses.
    Undefined,
    /// `MERGE`.
    Merge,
    /// `TEMPTABLE`.
    Temptable,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
/// View `SQL SECURITY`: whose privileges the view runs with.
pub enum ViewSqlSecurity {
    /// `DEFINER`.
    Definer,
    /// `INVOKER`.
    Invoker,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
/// View `WITH ... CHECK OPTION`.
pub enum ViewCheckOption {
    /// `WITH CASCADED CHECK OPTION`.
    Cascaded,
    /// `WITH LOCAL CHECK OPTION`.
    Local,
}

/// A view.
///
/// A view with `is_existing` set is managed outside drizzle: it is referenced
/// but never created or dropped, and needs no `definition`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct View {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub database: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    /// The view's `SELECT` statement. Required unless `is_existing` is set.
    pub definition: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub algorithm: Option<ViewAlgorithm>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    /// `DEFINER` account, such as `` `app`@`%` ``.
    pub definer: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub sql_security: Option<ViewSqlSecurity>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub check_option: Option<ViewCheckOption>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub charset: Option<Cow<'static, str>>,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "cow_option_from_string",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub collation: Option<Cow<'static, str>>,
    #[cfg_attr(feature = "serde", serde(default))]
    /// Whether the view exists outside drizzle's control.
    pub is_existing: bool,
}

impl View {
    /// Creates a view from its `SELECT` statement, with no options.
    #[must_use]
    pub fn new(
        name: impl Into<Cow<'static, str>>,
        definition: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            database: None,
            name: name.into(),
            definition: Some(definition.into()),
            algorithm: None,
            definer: None,
            sql_security: None,
            check_option: None,
            charset: None,
            collation: None,
            is_existing: false,
        }
    }
}

/// Any MySQL schema object: one element of a snapshot's `ddl` array.
///
/// With `serde`, the variant is stored in an `entityType` field (`"tables"`,
/// `"columns"`, `"indexes"`, `"pks"`, `"uniques"`, `"fks"`, `"checks"`,
/// `"views"`).
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "entityType"))]
pub enum MySQLEntity {
    #[cfg_attr(feature = "serde", serde(rename = "tables"))]
    Table(Table),
    #[cfg_attr(feature = "serde", serde(rename = "columns"))]
    Column(Column),
    #[cfg_attr(feature = "serde", serde(rename = "indexes"))]
    Index(Index),
    #[cfg_attr(feature = "serde", serde(rename = "pks"))]
    PrimaryKey(PrimaryKey),
    #[cfg_attr(feature = "serde", serde(rename = "uniques"))]
    UniqueConstraint(UniqueConstraint),
    #[cfg_attr(feature = "serde", serde(rename = "fks"))]
    ForeignKey(ForeignKey),
    #[cfg_attr(feature = "serde", serde(rename = "checks"))]
    CheckConstraint(CheckConstraint),
    #[cfg_attr(feature = "serde", serde(rename = "views"))]
    View(View),
}

impl MySQLEntity {
    /// Returns the entity's database, or `None` for the current database.
    #[must_use]
    pub fn database(&self) -> Option<&str> {
        match self {
            Self::Table(entity) => entity.database.as_deref(),
            Self::Column(entity) => entity.database.as_deref(),
            Self::Index(entity) => entity.database.as_deref(),
            Self::PrimaryKey(entity) => entity.database.as_deref(),
            Self::UniqueConstraint(entity) => entity.database.as_deref(),
            Self::ForeignKey(entity) => entity.database.as_deref(),
            Self::CheckConstraint(entity) => entity.database.as_deref(),
            Self::View(entity) => entity.database.as_deref(),
        }
    }
}