sql-schema 0.6.2

Declarative SQL schema migrations
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
use std::fmt;

use bon::bon;
use diff::Diff;
use migration::Migrate;
use sqlparser::{
    ast::Statement,
    dialect::{self},
    parser::{self, Parser},
};
use thiserror::Error;

mod diff;
mod migration;
pub mod name_gen;
pub mod path_template;

#[derive(Error, Debug)]
#[error("Oops, we couldn't parse that!")]
pub struct ParseError(#[from] parser::ParserError);

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum), clap(rename_all = "lower"))]
#[non_exhaustive]
pub enum Dialect {
    Ansi,
    BigQuery,
    ClickHouse,
    Databricks,
    DuckDb,
    #[default]
    Generic,
    Hive,
    MsSql,
    MySql,
    PostgreSql,
    RedshiftSql,
    Snowflake,
    SQLite,
}

impl Dialect {
    fn to_sqlparser_dialect(self) -> Box<dyn dialect::Dialect> {
        match self {
            Self::Ansi => Box::new(dialect::AnsiDialect {}),
            Self::BigQuery => Box::new(dialect::BigQueryDialect {}),
            Self::ClickHouse => Box::new(dialect::ClickHouseDialect {}),
            Self::Databricks => Box::new(dialect::DatabricksDialect {}),
            Self::DuckDb => Box::new(dialect::DuckDbDialect {}),
            Self::Generic => Box::new(dialect::GenericDialect {}),
            Self::Hive => Box::new(dialect::HiveDialect {}),
            Self::MsSql => Box::new(dialect::MsSqlDialect {}),
            Self::MySql => Box::new(dialect::MySqlDialect {}),
            Self::PostgreSql => Box::new(dialect::PostgreSqlDialect {}),
            Self::RedshiftSql => Box::new(dialect::RedshiftSqlDialect {}),
            Self::Snowflake => Box::new(dialect::SnowflakeDialect {}),
            Self::SQLite => Box::new(dialect::SQLiteDialect {}),
        }
    }
}

impl fmt::Display for Dialect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // NOTE: this must match how clap::ValueEnum displays variants
        write!(
            f,
            "{}",
            format!("{self:?}")
                .to_ascii_lowercase()
                .split('-')
                .collect::<String>()
        )
    }
}

#[derive(Debug, Clone)]
pub struct SyntaxTree(pub(crate) Vec<Statement>);

#[bon]
impl SyntaxTree {
    #[builder]
    pub fn new<'a>(dialect: Option<Dialect>, sql: impl Into<&'a str>) -> Result<Self, ParseError> {
        let dialect = dialect.unwrap_or_default().to_sqlparser_dialect();
        let ast = Parser::parse_sql(dialect.as_ref(), sql.into())?;
        Ok(Self(ast))
    }

    pub fn empty() -> Self {
        Self(vec![])
    }
}

pub use diff::DiffError;
pub use migration::MigrateError;

impl SyntaxTree {
    pub fn diff(&self, other: &SyntaxTree) -> Result<Option<Self>, DiffError> {
        Ok(Diff::diff(&self.0, &other.0)?.map(Self))
    }

    pub fn migrate(self, other: &SyntaxTree) -> Result<Option<Self>, MigrateError> {
        Ok(Migrate::migrate(self.0, &other.0)?.map(Self))
    }
}

impl fmt::Display for SyntaxTree {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut iter = self.0.iter().peekable();
        while let Some(s) = iter.next() {
            let formatted = sqlformat::format(
                format!("{s};").as_str(),
                &sqlformat::QueryParams::None,
                &sqlformat::FormatOptions::default(),
            );
            write!(f, "{formatted}")?;
            if iter.peek().is_some() {
                write!(f, "\n\n")?;
            }
        }
        Ok(())
    }
}

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

    #[derive(Debug)]
    struct TestCase {
        dialect: Dialect,
        sql_a: &'static str,
        sql_b: &'static str,
        expect: &'static str,
    }

    fn run_test_case<F>(tc: &TestCase, testfn: F)
    where
        F: Fn(SyntaxTree, SyntaxTree) -> SyntaxTree,
    {
        let ast_a = SyntaxTree::builder()
            .dialect(tc.dialect)
            .sql(tc.sql_a)
            .build()
            .unwrap();
        let ast_b = SyntaxTree::builder()
            .dialect(tc.dialect)
            .sql(tc.sql_b)
            .build()
            .unwrap();
        SyntaxTree::builder()
            .dialect(tc.dialect)
            .sql(tc.expect)
            .build()
            .unwrap_or_else(|_| panic!("invalid SQL: {:?}", tc.expect));
        let actual = testfn(ast_a, ast_b);
        assert_eq!(actual.to_string(), tc.expect, "{tc:?}");
    }

    fn run_test_cases<F, E: fmt::Debug>(test_cases: Vec<TestCase>, testfn: F)
    where
        F: Fn(SyntaxTree, SyntaxTree) -> Result<Option<SyntaxTree>, E>,
    {
        test_cases.into_iter().for_each(|tc| {
            run_test_case(&tc, |ast_a, ast_b| {
                testfn(ast_a, ast_b)
                    .inspect_err(|err| eprintln!("Error: {err:?}"))
                    .unwrap()
                    .unwrap()
            })
        });
    }

    #[test]
    fn diff_create_table() {
        run_test_cases(
            vec![
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE foo(\
                            id int PRIMARY KEY
                        )",
                    sql_b: "CREATE TABLE foo(\
                            id int PRIMARY KEY
                        );\
                        CREATE TABLE bar (id INT PRIMARY KEY);",
                    expect: "CREATE TABLE bar (id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE foo(\
                            id int PRIMARY KEY
                        )",
                    sql_b: "CREATE TABLE foo(\
                            \"id\" int PRIMARY KEY
                        );\
                        CREATE TABLE bar (id INT PRIMARY KEY);",
                    expect: "CREATE TABLE bar (id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE foo(\
                            \"id\" int PRIMARY KEY
                        )",
                    sql_b: "CREATE TABLE foo(\
                            id int PRIMARY KEY
                        );\
                        CREATE TABLE bar (id INT PRIMARY KEY);",
                    expect: "CREATE TABLE bar (id INT PRIMARY KEY);",
                },
            ],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_drop_table() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE foo(\
                        id int PRIMARY KEY
                    );\
                    CREATE TABLE bar (id INT PRIMARY KEY);",
                sql_b: "CREATE TABLE foo(\
                        id int PRIMARY KEY
                    )",
                expect: "DROP TABLE bar;",
            }],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_add_column() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE foo(\
                        id int PRIMARY KEY
                    )",
                sql_b: "CREATE TABLE foo(\
                        id int PRIMARY KEY,
                        bar text
                    )",
                expect: "ALTER TABLE\n  foo\nADD\n  COLUMN bar TEXT;",
            }],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_drop_column() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE foo(\
                        id int PRIMARY KEY,
                        bar text
                    )",
                sql_b: "CREATE TABLE foo(\
                        id int PRIMARY KEY
                    )",
                expect: "ALTER TABLE\n  foo DROP COLUMN bar;",
            }],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_create_index() {
        run_test_cases(
            vec![
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE UNIQUE INDEX title_idx ON films (title);",
                    sql_b: "CREATE UNIQUE INDEX title_idx ON films ((lower(title)));",
                    expect: "DROP INDEX title_idx;\n\nCREATE UNIQUE INDEX title_idx ON films((lower(title)));",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE UNIQUE INDEX IF NOT EXISTS title_idx ON films (title);",
                    sql_b: "CREATE UNIQUE INDEX IF NOT EXISTS title_idx ON films ((lower(title)));",
                    expect: "DROP INDEX IF EXISTS title_idx;\n\nCREATE UNIQUE INDEX IF NOT EXISTS title_idx ON films((lower(title)));",
                },
            ],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_create_type() {
        run_test_cases(
            vec![
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('new', 'open');",
                    sql_b: "CREATE TYPE foo AS ENUM ('bar');",
                    expect: "DROP TYPE bug_status;\n\nCREATE TYPE foo AS ENUM ('bar');",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');",
                    sql_b: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'assigned', 'closed');",
                    expect: "ALTER TYPE bug_status\nADD\n  VALUE 'assigned'\nAFTER\n  'open';",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('open', 'closed');",
                    sql_b: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');",
                    expect: "ALTER TYPE bug_status\nADD\n  VALUE 'new' BEFORE 'open';",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('new', 'open');",
                    sql_b: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');",
                    expect: "ALTER TYPE bug_status\nADD\n  VALUE 'closed';",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('new', 'open');",
                    sql_b: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'assigned', 'closed');",
                    expect: "ALTER TYPE bug_status\nADD\n  VALUE 'assigned';\n\nALTER TYPE bug_status\nADD\n  VALUE 'closed';",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('open', 'critical');",
                    sql_b: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'assigned', 'closed', 'critical');",
                    expect: "ALTER TYPE bug_status\nADD\n  VALUE 'new' BEFORE 'open';\n\nALTER TYPE bug_status\nADD\n  VALUE 'assigned'\nAFTER\n  'open';\n\nALTER TYPE bug_status\nADD\n  VALUE 'closed'\nAFTER\n  'assigned';",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('open');",
                    sql_b: "CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');",
                    expect: "ALTER TYPE bug_status\nADD\n  VALUE 'new' BEFORE 'open';\n\nALTER TYPE bug_status\nADD\n  VALUE 'closed';",
                },
            ],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_create_extension() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE EXTENSION hstore;",
                sql_b: "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";",
                expect: "DROP EXTENSION hstore;\n\nCREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";",
            }],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_create_domain() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::PostgreSql,
                sql_a: "",
                sql_b: "CREATE DOMAIN email AS VARCHAR(255) CHECK (VALUE ~ '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$');",
                expect: "CREATE DOMAIN email AS VARCHAR(255) CHECK (\n  VALUE ~ '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n);",
            }],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn diff_edit_domain() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::PostgreSql,
                sql_a: "CREATE DOMAIN positive_int AS INTEGER CHECK (VALUE > 0);",
                sql_b: "CREATE DOMAIN positive_int AS BIGINT CHECK (VALUE > 0 AND VALUE < 1000000);",
                expect: "DROP DOMAIN IF EXISTS positive_int;\n\nCREATE DOMAIN positive_int AS BIGINT CHECK (\n  VALUE > 0\n  AND VALUE < 1000000\n);",
            }],
            |ast_a, ast_b| ast_a.diff(&ast_b),
        );
    }

    #[test]
    fn apply_create_table() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE bar (id INT PRIMARY KEY);",
                sql_b: "CREATE TABLE foo (id INT PRIMARY KEY);",
                expect: "CREATE TABLE bar (id INT PRIMARY KEY);\n\nCREATE TABLE foo (id INT PRIMARY KEY);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_drop_table() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE bar (id INT PRIMARY KEY)",
                sql_b: "DROP TABLE bar; CREATE TABLE foo (id INT PRIMARY KEY)",
                expect: "CREATE TABLE foo (id INT PRIMARY KEY);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_table_add_column() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE bar (id INT PRIMARY KEY)",
                sql_b: "ALTER TABLE bar ADD COLUMN bar TEXT",
                expect: "CREATE TABLE bar (id INT PRIMARY KEY, bar TEXT);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_table_drop_column() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TABLE bar (bar TEXT, id INT PRIMARY KEY)",
                sql_b: "ALTER TABLE bar DROP COLUMN bar",
                expect: "CREATE TABLE bar (id INT PRIMARY KEY);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_table_drop_columns_snowflake() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Snowflake,
                sql_a: "CREATE TABLE bar (foo TEXT, bar TEXT, id INT PRIMARY KEY)",
                sql_b: "ALTER TABLE bar DROP COLUMN foo, bar",
                expect: "CREATE TABLE bar (id INT PRIMARY KEY);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_table_alter_column() {
        run_test_cases(
            vec![
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE bar (bar TEXT, id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar SET NOT NULL",
                    expect: "CREATE TABLE bar (bar TEXT NOT NULL, id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE bar (bar TEXT NOT NULL, id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar DROP NOT NULL",
                    expect: "CREATE TABLE bar (bar TEXT, id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE bar (bar TEXT NOT NULL DEFAULT 'foo', id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar DROP DEFAULT",
                    expect: "CREATE TABLE bar (bar TEXT NOT NULL, id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE bar (bar TEXT, id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar SET DATA TYPE INTEGER",
                    expect: "CREATE TABLE bar (bar INTEGER, id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::PostgreSql,
                    sql_a: "CREATE TABLE bar (bar TEXT, id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar SET DATA TYPE timestamp with time zone\n USING timestamp with time zone 'epoch' + foo_timestamp * interval '1 second'",
                    expect: "CREATE TABLE bar (bar TIMESTAMP WITH TIME ZONE, id INT PRIMARY KEY);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE bar (bar INTEGER, id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar ADD GENERATED BY DEFAULT AS IDENTITY",
                    expect: "CREATE TABLE bar (\n  bar INTEGER GENERATED BY DEFAULT AS IDENTITY,\n  id INT PRIMARY KEY\n);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TABLE bar (bar INTEGER, id INT PRIMARY KEY)",
                    sql_b: "ALTER TABLE bar ALTER COLUMN bar ADD GENERATED ALWAYS AS IDENTITY (START WITH 10)",
                    expect: "CREATE TABLE bar (\n  bar INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 10),\n  id INT PRIMARY KEY\n);",
                },
            ],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_create_index() {
        run_test_cases(
            vec![
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE UNIQUE INDEX title_idx ON films (title);",
                    sql_b: "CREATE INDEX code_idx ON films (code);",
                    expect: "CREATE UNIQUE INDEX title_idx ON films(title);\n\nCREATE INDEX code_idx ON films(code);",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE UNIQUE INDEX title_idx ON films (title);",
                    sql_b: "DROP INDEX title_idx;",
                    expect: "",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE UNIQUE INDEX title_idx ON films (title);",
                    sql_b: "DROP INDEX title_idx;CREATE INDEX code_idx ON films (code);",
                    expect: "CREATE INDEX code_idx ON films(code);",
                },
            ],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_create_type() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TYPE bug_status AS ENUM ('open', 'closed');",
                sql_b: "CREATE TYPE compfoo AS (f1 int, f2 text);",
                expect: "CREATE TYPE bug_status AS ENUM ('open', 'closed');\n\nCREATE TYPE compfoo AS (f1 INT, f2 TEXT);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_type_rename() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TYPE bug_status AS ENUM ('open', 'closed');",
                sql_b: "ALTER TYPE bug_status RENAME TO issue_status",
                expect: "CREATE TYPE issue_status AS ENUM ('open', 'closed');",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_type_add_value() {
        run_test_cases(
            vec![
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('open');",
                    sql_b: "ALTER TYPE bug_status ADD VALUE 'new' BEFORE 'open';",
                    expect: "CREATE TYPE bug_status AS ENUM ('new', 'open');",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('open');",
                    sql_b: "ALTER TYPE bug_status ADD VALUE 'closed' AFTER 'open';",
                    expect: "CREATE TYPE bug_status AS ENUM ('open', 'closed');",
                },
                TestCase {
                    dialect: Dialect::Generic,
                    sql_a: "CREATE TYPE bug_status AS ENUM ('open');",
                    sql_b: "ALTER TYPE bug_status ADD VALUE 'closed';",
                    expect: "CREATE TYPE bug_status AS ENUM ('open', 'closed');",
                },
            ],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_alter_type_rename_value() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE TYPE bug_status AS ENUM ('new', 'closed');",
                sql_b: "ALTER TYPE bug_status RENAME VALUE 'new' TO 'open';",
                expect: "CREATE TYPE bug_status AS ENUM ('open', 'closed');",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_create_extension() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::Generic,
                sql_a: "CREATE EXTENSION hstore;",
                sql_b: "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";",
                expect: "CREATE EXTENSION hstore;\n\nCREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }

    #[test]
    fn apply_create_domain() {
        run_test_cases(
            vec![TestCase {
                dialect: Dialect::PostgreSql,
                sql_a: "CREATE DOMAIN positive_int AS INTEGER CHECK (VALUE > 0);",
                sql_b: "CREATE DOMAIN email AS VARCHAR(255) CHECK (VALUE ~ '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$');",
                expect: "CREATE DOMAIN positive_int AS INTEGER CHECK (VALUE > 0);\n\nCREATE DOMAIN email AS VARCHAR(255) CHECK (\n  VALUE ~ '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n);",
            }],
            |ast_a, ast_b| ast_a.migrate(&ast_b),
        );
    }
}