drizzle-cli 0.4.2

Command-line interface for drizzle-rs 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
//! Rename-or-create decisions without a terminal: drizzle-kit's hints mode.
//!
//! Tests run with stdin not a terminal, so `generate` and `push` never
//! prompt: ambiguous renames need `--hints` / `--hints-file`, and without
//! them the command lists the decisions and exits with code 2.

use assert_cmd::cargo::cargo_bin_cmd;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::tempdir;

const USERS: &str = r"
use drizzle::sqlite::prelude::*;

#[SQLiteTable]
pub struct Users {
  #[column(primary)]
  pub id: i64,
  pub name: String,
}
";

const ACCOUNTS: &str = r"
use drizzle::sqlite::prelude::*;

#[SQLiteTable]
pub struct Accounts {
  #[column(primary)]
  pub id: i64,
  pub full_name: String,
}
";

const RENAME_TABLE_AND_COLUMN: &str = r#"[
  {"type": "rename", "kind": "table", "from": ["public", "users"], "to": ["public", "accounts"]},
  {"type": "rename", "kind": "column", "from": ["public", "accounts", "name"], "to": ["public", "accounts", "full_name"]}
]"#;

fn write_project(root: &Path, schema: &str) {
    fs::write(root.join("schema.rs"), schema).expect("write schema");
    fs::write(
        root.join("drizzle.config.toml"),
        format!(
            "dialect = \"sqlite\"\nschema = '{}'\nout = '{}'\n\n[migrations]\nprefix = \"index\"\n\n[dbCredentials]\nurl = '{}'\n",
            root.join("schema.rs").to_string_lossy(),
            root.join("migrations").to_string_lossy(),
            root.join("dev.db").to_string_lossy(),
        ),
    )
    .expect("write config");
}

fn migrations(root: &Path) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = fs::read_dir(root.join("migrations"))
        .expect("read migrations")
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| path.join("migration.sql").is_file())
        .collect();
    dirs.sort();
    dirs
}

fn latest_sql(root: &Path) -> String {
    let dir = migrations(root).pop().expect("a migration");
    fs::read_to_string(dir.join("migration.sql")).expect("read migration.sql")
}

/// A project whose first migration created `users`, with the schema now
/// declaring `accounts` instead.
fn renamed_project() -> tempfile::TempDir {
    let dir = tempdir().expect("tempdir");
    write_project(dir.path(), USERS);
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args(["generate", "--name", "init"])
        .assert()
        .success();
    fs::write(dir.path().join("schema.rs"), ACCOUNTS).expect("rewrite schema");
    dir
}

#[test]
fn generate_without_hints_lists_the_unresolved_renames_and_exits_2() {
    let dir = renamed_project();
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args(["generate", "--name", "renamed"])
        .assert()
        .code(2)
        .stdout(
            contains("missing_hints: 1 unresolved decisions")
                .and(contains("1. Rename or create"))
                .and(contains("table"))
                .and(contains("public.accounts"))
                .and(contains("Deleted candidates: [\"public\", \"users\"]"))
                .and(contains(
                    r#"{ "type": "rename", "kind": "table", "from": ["<schema>", "<old_name>"], "to": ["public", "accounts"] }"#,
                ))
                .and(contains(
                    r#"{ "type": "create", "kind": "table", "entity": ["public", "accounts"] }"#,
                ))
                .and(contains("Re-run with --hints")),
        );
    assert_eq!(migrations(dir.path()).len(), 1, "nothing was written");
}

#[test]
fn generate_lists_column_questions_after_a_hinted_table_rename() {
    let dir = renamed_project();
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args([
            "generate",
            "--hints",
            r#"[{"type":"rename","kind":"table","from":["public","users"],"to":["public","accounts"]}]"#,
        ])
        .assert()
        .code(2)
        .stdout(
            contains("missing_hints: 1 unresolved decisions")
                .and(contains("column"))
                .and(contains("public.accounts.full_name"))
                .and(contains(r#""entity": ["public", "accounts", "full_name"]"#)),
        );
}

#[test]
fn generate_with_rename_hints_writes_renames() {
    let dir = renamed_project();
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args([
            "generate",
            "--name",
            "renamed",
            "--hints",
            RENAME_TABLE_AND_COLUMN,
        ])
        .assert()
        .success()
        .stdout(contains("Migration generated"));
    assert_eq!(
        latest_sql(dir.path()),
        "ALTER TABLE `users` RENAME TO `accounts`;\n--> statement-breakpoint\nALTER TABLE `accounts` RENAME COLUMN `name` TO `full_name`;"
    );
}

#[test]
fn generate_with_create_hints_from_a_file_drops_and_creates() {
    let dir = renamed_project();
    let hints = dir.path().join("hints.json");
    fs::write(
        &hints,
        r#"[{"type": "create", "kind": "table", "entity": ["public", "accounts"]}]"#,
    )
    .expect("write hints");
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args(["generate", "--name", "recreated", "--hints-file"])
        .arg(&hints)
        .assert()
        .success();
    let sql = latest_sql(dir.path());
    assert!(sql.contains("CREATE TABLE `accounts`"), "{sql}");
    assert!(sql.contains("DROP TABLE `users`"), "{sql}");
    assert!(!sql.contains("RENAME"), "{sql}");
}

#[test]
fn generate_rejects_a_rename_hint_from_a_table_that_was_not_deleted() {
    let dir = renamed_project();
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args([
            "generate",
            "--hints",
            r#"[{"type":"rename","kind":"table","from":["public","people"],"to":["public","accounts"]}]"#,
        ])
        .assert()
        .code(1)
        .stderr(contains(
            "Invalid hints: rename hint's `from` [\"public\", \"people\"] doesn't match any deleted table",
        ));
    assert_eq!(migrations(dir.path()).len(), 1);
}

#[test]
fn generate_rejects_malformed_hints() {
    let dir = renamed_project();
    cargo_bin_cmd!("drizzle")
        .current_dir(dir.path())
        .args([
            "generate",
            "--hints",
            r#"[{"type":"rename","kind":"table"}]"#,
        ])
        .assert()
        .code(1)
        .stderr(contains("Invalid hints: Invalid hint shape at [0].from"));
}

#[test]
fn generate_uses_drizzle_kit_ids_for_postgres_and_mysql() {
    let cases = [
        (
            "postgresql",
            "#[PostgresTable(schema = \"app\")]",
            r#"["app", "accounts"]"#,
            r#"[{"type":"rename","kind":"table","from":["app","users"],"to":["app","accounts"]}]"#,
            "ALTER TABLE \"app\".\"users\" RENAME TO \"accounts\";",
        ),
        (
            "mysql",
            "#[MySQLTable]",
            r#"["public", "accounts"]"#,
            r#"[{"type":"rename","kind":"table","from":["public","users"],"to":["public","accounts"]}]"#,
            "RENAME TABLE `users` TO `accounts`;",
        ),
    ];
    for (dialect, attribute, id, hints, expected) in cases {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        let schema = |name: &str| {
            format!("{attribute}\npub struct {name} {{\n  #[column(primary)]\n  pub id: i32,\n}}\n")
        };
        fs::write(root.join("schema.rs"), schema("Users")).expect("write schema");
        fs::write(
            root.join("drizzle.config.toml"),
            format!(
                "dialect = \"{dialect}\"\nschema = '{}'\nout = '{}'\n\n[migrations]\nprefix = \"index\"\n",
                root.join("schema.rs").to_string_lossy(),
                root.join("migrations").to_string_lossy(),
            ),
        )
        .expect("write config");
        cargo_bin_cmd!("drizzle")
            .current_dir(root)
            .args(["generate", "--name", "init"])
            .assert()
            .success();
        fs::write(root.join("schema.rs"), schema("Accounts")).expect("rewrite schema");

        cargo_bin_cmd!("drizzle")
            .current_dir(root)
            .arg("generate")
            .assert()
            .code(2)
            .stdout(contains(format!(
                r#"{{ "type": "create", "kind": "table", "entity": {id} }}"#
            )));
        cargo_bin_cmd!("drizzle")
            .current_dir(root)
            .args(["generate", "--name", "renamed", "--hints", hints])
            .assert()
            .success();
        // Only the table is renamed: on PostgreSQL the primary key keeps
        // its implicit name (`users_pkey`), as in drizzle-kit.
        let sql = latest_sql(root);
        assert_eq!(sql.trim(), expected, "{dialect}");
        // The snapshot records the kept name, so nothing is left to do.
        cargo_bin_cmd!("drizzle")
            .current_dir(root)
            .arg("generate")
            .assert()
            .success()
            .stdout(contains("No schema changes"));
    }
}

/// A renamed, explicitly named PostgreSQL constraint is asked about like
/// drizzle-kit does, and a `unique` hint renames it in place.
#[test]
fn generate_renames_an_explicitly_named_postgres_constraint() {
    let dir = tempdir().expect("tempdir");
    let root = dir.path();
    let schema = |name: &str| {
        format!(
            "#[PostgresTable(unique(columns(email), name = \"{name}\"))]\npub struct Users {{\n  #[column(primary)]\n  pub id: i32,\n  pub email: String,\n}}\n"
        )
    };
    fs::write(root.join("schema.rs"), schema("users_email_uq")).expect("write schema");
    fs::write(
        root.join("drizzle.config.toml"),
        format!(
            "dialect = \"postgresql\"\nschema = '{}'\nout = '{}'\n\n[migrations]\nprefix = \"index\"\n",
            root.join("schema.rs").to_string_lossy(),
            root.join("migrations").to_string_lossy(),
        ),
    )
    .expect("write config");
    cargo_bin_cmd!("drizzle")
        .current_dir(root)
        .args(["generate", "--name", "init"])
        .assert()
        .success();
    fs::write(root.join("schema.rs"), schema("users_email_key")).expect("rewrite schema");

    cargo_bin_cmd!("drizzle")
        .current_dir(root)
        .args([
            "generate",
            "--name",
            "renamed",
            "--hints",
            r#"[{"type":"rename","kind":"unique","from":["public","users","users_email_uq"],"to":["public","users","users_email_key"]}]"#,
        ])
        .assert()
        .success();
    assert_eq!(
        latest_sql(root).trim(),
        "ALTER TABLE \"users\" RENAME CONSTRAINT \"users_email_uq\" TO \"users_email_key\";"
    );

    // A constraint holds no data, so without a hint it is dropped and
    // created rather than stopping the command.
    fs::write(root.join("schema.rs"), schema("users_email_unique")).expect("rewrite schema");
    cargo_bin_cmd!("drizzle")
        .current_dir(root)
        .args(["generate", "--name", "recreated"])
        .assert()
        .success();
    let sql = latest_sql(root);
    assert!(sql.contains("DROP CONSTRAINT \"users_email_key\""), "{sql}");
    assert!(
        sql.contains("ADD CONSTRAINT \"users_email_unique\""),
        "{sql}"
    );
}

#[cfg(feature = "rusqlite")]
mod push {
    use super::*;

    fn seeded_project() -> tempfile::TempDir {
        let dir = tempdir().expect("tempdir");
        write_project(dir.path(), ACCOUNTS);
        let conn = rusqlite::Connection::open(dir.path().join("dev.db")).expect("open db");
        conn.execute_batch(
            "CREATE TABLE `users` (`id` integer PRIMARY KEY NOT NULL, `name` text NOT NULL);
             INSERT INTO `users` VALUES (1, 'Ada');",
        )
        .expect("seed db");
        dir
    }

    fn tables(root: &Path) -> Vec<String> {
        let conn = rusqlite::Connection::open(root.join("dev.db")).expect("open db");
        let mut stmt = conn
            .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
            .expect("prepare");
        stmt.query_map([], |row| row.get(0))
            .expect("query")
            .map(Result::unwrap)
            .collect()
    }

    #[test]
    fn push_without_hints_exits_2_even_with_force() {
        let dir = seeded_project();
        for args in [&["push"][..], &["push", "--force"], &["push", "--explain"]] {
            cargo_bin_cmd!("drizzle")
                .current_dir(dir.path())
                .args(args)
                .assert()
                .code(2)
                .stdout(contains("missing_hints: 1 unresolved decisions").and(contains(
                    r#"{ "type": "create", "kind": "table", "entity": ["public", "accounts"] }"#,
                )));
        }
        assert_eq!(tables(dir.path()), ["users"]);
    }

    #[test]
    fn push_explain_shows_hinted_renames() {
        let dir = seeded_project();
        cargo_bin_cmd!("drizzle")
            .current_dir(dir.path())
            .args(["push", "--explain", "--hints", RENAME_TABLE_AND_COLUMN])
            .assert()
            .success()
            .stdout(
                contains("--- Planned SQL ---")
                    .and(contains("ALTER TABLE `users` RENAME TO `accounts`;"))
                    .and(contains(
                        "ALTER TABLE `accounts` RENAME COLUMN `name` TO `full_name`;",
                    ))
                    .and(contains("DROP TABLE").not()),
            );
        assert_eq!(tables(dir.path()), ["users"]);
    }

    #[test]
    fn push_with_rename_hints_keeps_the_data() {
        let dir = seeded_project();
        cargo_bin_cmd!("drizzle")
            .current_dir(dir.path())
            .args(["push", "--hints", RENAME_TABLE_AND_COLUMN])
            .assert()
            .success()
            .stdout(contains("Push complete!"));
        assert_eq!(tables(dir.path()), ["accounts"]);
        let conn = rusqlite::Connection::open(dir.path().join("dev.db")).expect("open db");
        let name: String = conn
            .query_row("SELECT full_name FROM accounts WHERE id = 1", [], |row| {
                row.get(0)
            })
            .expect("row survived the rename");
        assert_eq!(name, "Ada");
    }

    /// Dropping a table that holds rows needs confirmation, which a
    /// non-interactive run cannot give; an empty table drops without asking.
    #[test]
    fn push_asks_only_when_a_drop_loses_rows() {
        let create_accounts =
            r#"[{"type":"create","kind":"table","entity":["public","accounts"]}]"#;

        let dir = seeded_project();
        cargo_bin_cmd!("drizzle")
            .current_dir(dir.path())
            .args(["push", "--hints", create_accounts])
            .assert()
            .failure()
            .stdout(contains("table `users` holds 1 row(s); push drops it"))
            .stderr(contains(
                "Refusing to apply potentially destructive changes",
            ));
        assert_eq!(tables(dir.path()), ["users"]);

        let dir = seeded_project();
        rusqlite::Connection::open(dir.path().join("dev.db"))
            .expect("open db")
            .execute("DELETE FROM `users`", [])
            .expect("empty the table");
        cargo_bin_cmd!("drizzle")
            .current_dir(dir.path())
            .args(["push", "--hints", create_accounts])
            .assert()
            .success();
        assert_eq!(tables(dir.path()), ["accounts"]);
    }

    #[test]
    fn push_with_create_hints_and_force_drops_and_creates() {
        let dir = seeded_project();
        cargo_bin_cmd!("drizzle")
            .current_dir(dir.path())
            .args([
                "push",
                "--force",
                "--hints",
                r#"[{"type":"create","kind":"table","entity":["public","accounts"]}]"#,
            ])
            .assert()
            .success();
        assert_eq!(tables(dir.path()), ["accounts"]);
    }
}