drizzle-migrations 0.1.12

Migration infrastructure for drizzle-rs
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
//! `SQLite` DDL collection — typed access to schema entities.
//!
//! The generic [`EntityCollection<T>`] storage backbone lives in
//! [`crate::collection`]; this file supplies the per-entity-type lookup
//! helpers (`one`, `for_table`, `delete`) whose shape depends on each
//! SQLite entity's identity (single-name for `Table`/`Index`; `(table,
//! name)` for `Column`).

use super::ddl::{
    CheckConstraint, Column, ForeignKey, Index, PrimaryKey, SqliteEntity, Table, UniqueConstraint,
    View,
};
use crate::collection::EntityCollection;
use crate::traits::EntityKind;
use std::borrow::Cow;
use std::collections::HashMap;

// =============================================================================
// Per-entity-type lookup helpers
// =============================================================================

// Table-specific operations
impl EntityCollection<Table> {
    /// Find a table by name
    #[must_use]
    pub fn one(&self, name: &str) -> Option<&Table> {
        self.entities.iter().find(|t| t.name == name)
    }

    /// Delete a table by name
    pub fn delete(&mut self, name: &str) -> Option<Table> {
        if let Some(pos) = self.entities.iter().position(|t| t.name == name) {
            Some(self.entities.remove(pos))
        } else {
            None
        }
    }
}

// Column-specific operations
impl EntityCollection<Column> {
    /// Find a column by table and name
    #[must_use]
    pub fn one(&self, table: &str, name: &str) -> Option<&Column> {
        self.entities
            .iter()
            .find(|c| c.table == table && c.name == name)
    }

    /// List columns for a table
    #[must_use]
    pub fn for_table(&self, table: &str) -> Vec<&Column> {
        self.entities.iter().filter(|c| c.table == table).collect()
    }

    /// Delete a column by table and name
    pub fn delete(&mut self, table: &str, name: &str) -> Option<Column> {
        if let Some(pos) = self
            .entities
            .iter()
            .position(|c| c.table == table && c.name == name)
        {
            Some(self.entities.remove(pos))
        } else {
            None
        }
    }
}

// Index-specific operations
impl EntityCollection<Index> {
    /// Find an index by name
    #[must_use]
    pub fn one(&self, name: &str) -> Option<&Index> {
        self.entities.iter().find(|i| i.name == name)
    }

    /// List indexes for a table
    #[must_use]
    pub fn for_table(&self, table: &str) -> Vec<&Index> {
        self.entities.iter().filter(|i| i.table == table).collect()
    }
}

// ForeignKey-specific operations
impl EntityCollection<ForeignKey> {
    /// Find a foreign key by name
    #[must_use]
    pub fn one(&self, name: &str) -> Option<&ForeignKey> {
        self.entities.iter().find(|f| f.name == name)
    }

    /// List foreign keys for a table
    #[must_use]
    pub fn for_table(&self, table: &str) -> Vec<&ForeignKey> {
        self.entities.iter().filter(|f| f.table == table).collect()
    }
}

// PrimaryKey-specific operations
impl EntityCollection<PrimaryKey> {
    /// Find a primary key by table
    #[must_use]
    pub fn for_table(&self, table: &str) -> Option<&PrimaryKey> {
        self.entities.iter().find(|p| p.table == table)
    }
}

// UniqueConstraint-specific operations
impl EntityCollection<UniqueConstraint> {
    /// Find by name
    #[must_use]
    pub fn one(&self, name: &str) -> Option<&UniqueConstraint> {
        self.entities.iter().find(|u| u.name == name)
    }

    /// List for a table
    #[must_use]
    pub fn for_table(&self, table: &str) -> Vec<&UniqueConstraint> {
        self.entities.iter().filter(|u| u.table == table).collect()
    }
}

// CheckConstraint-specific operations
impl EntityCollection<CheckConstraint> {
    /// Find by name
    #[must_use]
    pub fn one(&self, name: &str) -> Option<&CheckConstraint> {
        self.entities.iter().find(|c| c.name == name)
    }

    /// List for a table
    #[must_use]
    pub fn for_table(&self, table: &str) -> Vec<&CheckConstraint> {
        self.entities.iter().filter(|c| c.table == table).collect()
    }
}

// View-specific operations
impl EntityCollection<View> {
    /// Find a view by name
    #[must_use]
    pub fn one(&self, name: &str) -> Option<&View> {
        self.entities.iter().find(|v| v.name == name)
    }
}

// =============================================================================
// SQLite DDL - Main Collection Type
// =============================================================================

/// `SQLite` DDL collection - stores all schema entities
///
/// This is the main type for working with DDL entities.
/// It provides typed access to each entity type with collection operations.
#[derive(Debug, Clone, Default)]
pub struct SQLiteDDL {
    pub tables: EntityCollection<Table>,
    pub columns: EntityCollection<Column>,
    pub indexes: EntityCollection<Index>,
    pub fks: EntityCollection<ForeignKey>,
    pub pks: EntityCollection<PrimaryKey>,
    pub uniques: EntityCollection<UniqueConstraint>,
    pub checks: EntityCollection<CheckConstraint>,
    pub views: EntityCollection<View>,
}

impl SQLiteDDL {
    /// Create a new empty DDL collection
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create DDL from a list of entities
    #[must_use]
    pub fn from_entities(entities: Vec<SqliteEntity>) -> Self {
        let mut ddl = Self::new();
        for entity in entities {
            ddl.push_entity(entity);
        }
        ddl
    }

    /// Push any entity type
    pub fn push_entity(&mut self, entity: SqliteEntity) {
        match entity {
            SqliteEntity::Table(t) => self.tables.push(t),
            SqliteEntity::Column(c) => self.columns.push(c),
            SqliteEntity::Index(i) => self.indexes.push(i),
            SqliteEntity::ForeignKey(f) => self.fks.push(f),
            SqliteEntity::PrimaryKey(p) => self.pks.push(p),
            SqliteEntity::UniqueConstraint(u) => self.uniques.push(u),
            SqliteEntity::CheckConstraint(c) => self.checks.push(c),
            SqliteEntity::View(v) => self.views.push(v),
        };
    }

    /// Convert to entity array for snapshot serialization
    #[must_use]
    pub fn to_entities(&self) -> Vec<SqliteEntity> {
        let mut entities = Vec::new();

        // Tables first
        for t in self.tables.list() {
            entities.push(SqliteEntity::Table(t.clone()));
        }
        // Then columns
        for c in self.columns.list() {
            entities.push(SqliteEntity::Column(c.clone()));
        }
        // Then other entities
        for i in self.indexes.list() {
            entities.push(SqliteEntity::Index(i.clone()));
        }
        for f in self.fks.list() {
            entities.push(SqliteEntity::ForeignKey(f.clone()));
        }
        for p in self.pks.list() {
            entities.push(SqliteEntity::PrimaryKey(p.clone()));
        }
        for u in self.uniques.list() {
            entities.push(SqliteEntity::UniqueConstraint(u.clone()));
        }
        for c in self.checks.list() {
            entities.push(SqliteEntity::CheckConstraint(c.clone()));
        }
        for v in self.views.list() {
            entities.push(SqliteEntity::View(v.clone()));
        }

        entities
    }

    /// Check if DDL is empty
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.tables.is_empty()
            && self.columns.is_empty()
            && self.indexes.is_empty()
            && self.fks.is_empty()
            && self.pks.is_empty()
            && self.uniques.is_empty()
            && self.checks.is_empty()
            && self.views.is_empty()
    }

    /// Get all entities for a specific table
    #[must_use]
    pub fn table_entities<'a>(&'a self, table_name: &str) -> TableEntities<'a> {
        TableEntities {
            columns: self.columns.for_table(table_name),
            indexes: self.indexes.for_table(table_name),
            fks: self.fks.for_table(table_name),
            pk: self.pks.for_table(table_name),
            uniques: self.uniques.for_table(table_name),
            checks: self.checks.for_table(table_name),
        }
    }
}

/// All entities belonging to a specific table
pub struct TableEntities<'a> {
    pub columns: Vec<&'a Column>,
    pub indexes: Vec<&'a Index>,
    pub fks: Vec<&'a ForeignKey>,
    pub pk: Option<&'a PrimaryKey>,
    pub uniques: Vec<&'a UniqueConstraint>,
    pub checks: Vec<&'a CheckConstraint>,
}

// =============================================================================
// Diff Types
// =============================================================================

// Re-export shared DiffType from traits module
pub use crate::traits::DiffType;

/// A diff statement for any entity
#[derive(Debug, Clone)]
pub struct EntityDiff {
    pub diff_type: DiffType,
    pub kind: EntityKind,
    pub table: Option<String>,
    pub name: String,
    /// For alter: changed fields with (from, to) values
    pub changes: HashMap<String, (String, String)>,
    /// Original entity (for drop/alter)
    pub left: Option<SqliteEntity>,
    /// New entity (for create/alter)
    pub right: Option<SqliteEntity>,
}

/// Compute diff between two DDL collections
#[must_use]
pub fn diff_ddl(left: &SQLiteDDL, right: &SQLiteDDL) -> Vec<EntityDiff> {
    let mut diffs = Vec::new();

    // Diff tables (no table_fn needed since these ARE tables)
    diff_entity_type(
        left.tables.list(),
        right.tables.list(),
        |t| t.name.to_string(),
        |t| SqliteEntity::Table(t.clone()),
        None,
        EntityKind::Table,
        &mut diffs,
    );

    // Diff columns - extract table name from column
    diff_entity_type_with(
        left.columns.list(),
        right.columns.list(),
        |c| format!("{}:{}", c.table, c.name),
        |c| SqliteEntity::Column(c.clone()),
        Some(&|c: &Column| c.table.to_string()),
        EntityKind::Column,
        columns_equivalent,
        &mut diffs,
    );

    // Diff indexes - extract table name from index
    diff_entity_type(
        left.indexes.list(),
        right.indexes.list(),
        |i| i.name.to_string(),
        |i| SqliteEntity::Index(i.clone()),
        Some(&|i: &Index| i.table.to_string()),
        EntityKind::Index,
        &mut diffs,
    );

    // Diff foreign keys - extract table name from FK
    diff_entity_type_with(
        left.fks.list(),
        right.fks.list(),
        |f| f.name.to_string(),
        |f| SqliteEntity::ForeignKey(f.clone()),
        Some(&|f: &ForeignKey| f.table.to_string()),
        EntityKind::ForeignKey,
        foreign_keys_equivalent,
        &mut diffs,
    );

    // Diff primary keys - extract table name from PK
    diff_entity_type(
        left.pks.list(),
        right.pks.list(),
        |p| p.table.to_string(),
        |p| SqliteEntity::PrimaryKey(p.clone()),
        Some(&|p: &PrimaryKey| p.table.to_string()),
        EntityKind::PrimaryKey,
        &mut diffs,
    );

    // Diff unique constraints - extract table name from unique
    diff_entity_type(
        left.uniques.list(),
        right.uniques.list(),
        |u| u.name.to_string(),
        |u| SqliteEntity::UniqueConstraint(u.clone()),
        Some(&|u: &UniqueConstraint| u.table.to_string()),
        EntityKind::UniqueConstraint,
        &mut diffs,
    );

    // Diff check constraints - extract table name from check
    diff_entity_type(
        left.checks.list(),
        right.checks.list(),
        |c| c.name.to_string(),
        |c| SqliteEntity::CheckConstraint(c.clone()),
        Some(&|c: &CheckConstraint| c.table.to_string()),
        EntityKind::CheckConstraint,
        &mut diffs,
    );

    // Diff views (no table_fn needed since views are standalone)
    diff_entity_type(
        left.views.list(),
        right.views.list(),
        |v| v.name.to_string(),
        |v| SqliteEntity::View(v.clone()),
        None,
        EntityKind::View,
        &mut diffs,
    );

    diffs
}

/// Helper to diff a single entity type
fn diff_entity_type<T: Clone + PartialEq>(
    left: &[T],
    right: &[T],
    key_fn: impl Fn(&T) -> String,
    to_entity: impl Fn(&T) -> SqliteEntity,
    table_fn: Option<&dyn Fn(&T) -> String>,
    kind: EntityKind,
    diffs: &mut Vec<EntityDiff>,
) {
    diff_entity_type_with(
        left,
        right,
        key_fn,
        to_entity,
        table_fn,
        kind,
        PartialEq::eq,
        diffs,
    );
}

#[allow(clippy::too_many_arguments)]
fn diff_entity_type_with<T: Clone>(
    left: &[T],
    right: &[T],
    key_fn: impl Fn(&T) -> String,
    to_entity: impl Fn(&T) -> SqliteEntity,
    table_fn: Option<&dyn Fn(&T) -> String>,
    kind: EntityKind,
    equivalent: impl Fn(&T, &T) -> bool,
    diffs: &mut Vec<EntityDiff>,
) {
    let left_map: HashMap<String, &T> = left.iter().map(|e| (key_fn(e), e)).collect();
    let right_map: HashMap<String, &T> = right.iter().map(|e| (key_fn(e), e)).collect();

    // Find dropped (in left but not in right)
    for left_entity in left {
        let key = key_fn(left_entity);
        if !right_map.contains_key(&key) {
            diffs.push(EntityDiff {
                diff_type: DiffType::Drop,
                kind,
                table: table_fn.map(|f| f(left_entity)),
                name: key,
                changes: HashMap::new(),
                left: Some(to_entity(left_entity)),
                right: None,
            });
        }
    }

    // Find created (in right but not in left)
    for right_entity in right {
        let key = key_fn(right_entity);
        if !left_map.contains_key(&key) {
            diffs.push(EntityDiff {
                diff_type: DiffType::Create,
                kind,
                table: table_fn.map(|f| f(right_entity)),
                name: key,
                changes: HashMap::new(),
                left: None,
                right: Some(to_entity(right_entity)),
            });
        }
    }

    // Find altered (in both, but different)
    for left_entity in left {
        let key = key_fn(left_entity);
        if let Some(right_entity) = right_map.get(&key)
            && !equivalent(left_entity, right_entity)
        {
            diffs.push(EntityDiff {
                diff_type: DiffType::Alter,
                kind,
                table: table_fn.map(|f| f(right_entity)),
                name: key,
                changes: HashMap::new(), // Field-level comparison available via left/right entities
                left: Some(to_entity(left_entity)),
                right: Some(to_entity(right_entity)),
            });
        }
    }
}

fn columns_equivalent(left: &Column, right: &Column) -> bool {
    let mut left = left.clone();
    let mut right = right.clone();
    left.sql_type = Cow::Owned(left.sql_type.to_ascii_lowercase());
    right.sql_type = Cow::Owned(right.sql_type.to_ascii_lowercase());
    left == right
}

fn normalize_fk_action(action: &Option<Cow<'static, str>>) -> Option<Cow<'static, str>> {
    match action.as_deref() {
        None => None,
        Some(action) if action.eq_ignore_ascii_case("NO ACTION") => None,
        Some(action) => Some(Cow::Owned(action.to_ascii_uppercase())),
    }
}

fn foreign_keys_equivalent(left: &ForeignKey, right: &ForeignKey) -> bool {
    let mut left = left.clone();
    let mut right = right.clone();
    left.on_delete = normalize_fk_action(&left.on_delete);
    left.on_update = normalize_fk_action(&left.on_update);
    right.on_delete = normalize_fk_action(&right.on_delete);
    right.on_update = normalize_fk_action(&right.on_update);
    left == right
}

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

    #[test]
    fn test_ddl_collection_push() {
        let mut ddl = SQLiteDDL::new();

        ddl.tables.push(Table::new("users"));
        ddl.columns.push(Column::new("users", "id", "integer"));
        ddl.columns.push(Column::new("users", "name", "text"));

        assert_eq!(ddl.tables.len(), 1);
        assert_eq!(ddl.columns.len(), 2);
        assert_eq!(ddl.columns.for_table("users").len(), 2);
    }

    #[test]
    fn test_ddl_to_entities() {
        let mut ddl = SQLiteDDL::new();
        ddl.tables.push(Table::new("users"));
        ddl.columns
            .push(Column::new("users", "id", "integer").not_null());

        let entities = ddl.to_entities();
        assert_eq!(entities.len(), 2);
    }

    #[test]
    fn test_diff_create() {
        let left = SQLiteDDL::new();
        let mut right = SQLiteDDL::new();
        right.tables.push(Table::new("users"));

        let diffs = diff_ddl(&left, &right);
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs[0].diff_type, DiffType::Create);
        assert_eq!(diffs[0].kind, EntityKind::Table);
    }

    #[test]
    fn test_diff_drop() {
        let mut left = SQLiteDDL::new();
        left.tables.push(Table::new("users"));
        let right = SQLiteDDL::new();

        let diffs = diff_ddl(&left, &right);
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs[0].diff_type, DiffType::Drop);
    }

    #[test]
    fn introspected_types_and_no_action_fks_match_macro_snapshots() {
        let mut introspected = SQLiteDDL::new();
        introspected.tables.push(Table::new("child"));
        introspected.tables.push(Table::new("parent"));
        introspected
            .columns
            .push(Column::new("child", "id", "integer").not_null());
        introspected
            .columns
            .push(Column::new("child", "parent_id", "integer").not_null());
        introspected.fks.push(
            ForeignKey::from_strings(
                "child".to_string(),
                "child_parent_id_fk".to_string(),
                vec!["parent_id".to_string()],
                "parent".to_string(),
                vec!["id".to_string()],
            )
            .on_delete("NO ACTION")
            .on_update("no action"),
        );

        let mut macro_snapshot = SQLiteDDL::new();
        macro_snapshot.tables.push(Table::new("child"));
        macro_snapshot.tables.push(Table::new("parent"));
        macro_snapshot
            .columns
            .push(Column::new("child", "id", "INTEGER").not_null());
        macro_snapshot
            .columns
            .push(Column::new("child", "parent_id", "INTEGER").not_null());
        macro_snapshot.fks.push(ForeignKey::from_strings(
            "child".to_string(),
            "child_parent_id_fk".to_string(),
            vec!["parent_id".to_string()],
            "parent".to_string(),
            vec!["id".to_string()],
        ));

        let diffs = diff_ddl(&introspected, &macro_snapshot);
        assert!(diffs.is_empty(), "unexpected diffs: {diffs:#?}");
    }
}