toasty-core 0.2.0

Core types, schema representations, and driver interface for Toasty
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
use super::{Column, ColumnId, Index, IndexId, PrimaryKey};
use crate::{
    schema::db::{column::ColumnsDiff, diff::DiffContext, index::IndicesDiff},
    stmt,
};

use std::{
    collections::{HashMap, HashSet},
    fmt,
    ops::Deref,
};

/// A database table with its columns, primary key, and indices.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::{Table, TableId};
///
/// let table = Table::new(TableId(0), "users".to_string());
/// assert_eq!(table.name, "users");
/// assert!(table.columns.is_empty());
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Table {
    /// Uniquely identifies a table within the schema.
    pub id: TableId,

    /// Name of the table as it appears in the database.
    pub name: String,

    /// The table's columns, in order.
    pub columns: Vec<Column>,

    /// The table's primary key definition.
    pub primary_key: PrimaryKey,

    /// Secondary indices on this table.
    pub indices: Vec<Index>,
}

/// Uniquely identifies a table within a [`Schema`](super::Schema).
///
/// The inner `usize` is a zero-based index into [`Schema::tables`](super::Schema::tables).
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::TableId;
///
/// let id = TableId(0);
/// assert_eq!(id.0, 0);
/// ```
#[derive(PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TableId(pub usize);

impl Table {
    /// Returns the `i`-th column of this table's primary key.
    ///
    /// # Panics
    ///
    /// Panics if `i` is out of bounds for the primary key column list.
    pub fn primary_key_column(&self, i: usize) -> &Column {
        &self.columns[self.primary_key.columns[i].index]
    }

    /// Returns an iterator over the columns that make up this table's primary key.
    pub fn primary_key_columns(&self) -> impl ExactSizeIterator<Item = &Column> + '_ {
        self.primary_key
            .columns
            .iter()
            .map(|column_id| &self.columns[column_id.index])
    }

    /// Returns the column identified by `id`.
    ///
    /// Only the column's `index` field is used; the `table` component is ignored.
    ///
    /// # Panics
    ///
    /// Panics if the column index is out of bounds.
    pub fn column(&self, id: impl Into<ColumnId>) -> &Column {
        &self.columns[id.into().index]
    }

    /// Resolves a single-step [`Projection`](stmt::Projection) to a column.
    ///
    /// # Panics
    ///
    /// Panics if the projection is empty or contains more than one step.
    pub fn resolve(&self, projection: &stmt::Projection) -> &Column {
        let [first, rest @ ..] = projection.as_slice() else {
            panic!("need at most one path step")
        };
        assert!(rest.is_empty());

        &self.columns[*first]
    }

    pub(crate) fn new(id: TableId, name: String) -> Self {
        Self {
            id,
            name,
            columns: vec![],
            primary_key: PrimaryKey {
                columns: vec![],
                index: IndexId {
                    table: id,
                    index: 0,
                },
            },
            indices: vec![],
        }
    }
}

impl TableId {
    pub(crate) fn placeholder() -> Self {
        Self(usize::MAX)
    }
}

impl fmt::Debug for TableId {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "TableId({})", self.0)
    }
}

/// The set of differences between two table lists.
///
/// Computed by [`TablesDiff::from`] and dereferences to
/// `Vec<TablesDiffItem>` for iteration.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::{TablesDiff, DiffContext, RenameHints, Schema};
///
/// let previous = Schema::default();
/// let next = Schema::default();
/// let hints = RenameHints::new();
/// let cx = DiffContext::new(&previous, &next, &hints);
/// let diff = TablesDiff::from(&cx, &[], &[]);
/// assert!(diff.is_empty());
/// ```
pub struct TablesDiff<'a> {
    items: Vec<TablesDiffItem<'a>>,
}

impl<'a> TablesDiff<'a> {
    /// Computes the diff between two table slices.
    ///
    /// Uses [`DiffContext`] to resolve rename hints. Tables matched by name
    /// (or by rename hint) are compared for column and index changes;
    /// unmatched tables in `previous` become drops, and unmatched tables in
    /// `next` become creates.
    pub fn from(cx: &DiffContext<'a>, previous: &'a [Table], next: &'a [Table]) -> Self {
        let mut items = vec![];
        let mut create_ids: HashSet<_> = next.iter().map(|next| next.id).collect();

        let next_map = HashMap::<&str, &'a Table>::from_iter(
            next.iter().map(|next| (next.name.as_str(), next)),
        );

        for previous in previous {
            let next = if let Some(next_id) = cx.rename_hints().get_table(previous.id) {
                cx.next().table(next_id)
            } else if let Some(to) = next_map.get(previous.name.as_str()) {
                to
            } else {
                items.push(TablesDiffItem::DropTable(previous));
                continue;
            };

            create_ids.remove(&next.id);

            let columns = ColumnsDiff::from(cx, &previous.columns, &next.columns);
            let indices = IndicesDiff::from(cx, &previous.indices, &next.indices);
            if previous.name != next.name || !columns.is_empty() || !indices.is_empty() {
                items.push(TablesDiffItem::AlterTable {
                    previous,
                    next,
                    columns,
                    indices,
                });
            }
        }

        for table_id in create_ids {
            items.push(TablesDiffItem::CreateTable(cx.next().table(table_id)));
        }

        Self { items }
    }
}

impl<'a> Deref for TablesDiff<'a> {
    type Target = Vec<TablesDiffItem<'a>>;

    fn deref(&self) -> &Self::Target {
        &self.items
    }
}

/// A single change detected between two table lists.
pub enum TablesDiffItem<'a> {
    /// A new table was created.
    CreateTable(&'a Table),
    /// An existing table was dropped.
    DropTable(&'a Table),
    /// A table was modified (name, columns, or indices changed).
    AlterTable {
        /// The table definition before the change.
        previous: &'a Table,
        /// The table definition after the change.
        next: &'a Table,
        /// Column-level changes within this table.
        columns: ColumnsDiff<'a>,
        /// Index-level changes within this table.
        indices: IndicesDiff<'a>,
    },
}

#[cfg(test)]
mod tests {
    use crate::schema::db::{
        Column, ColumnId, DiffContext, IndexId, PrimaryKey, RenameHints, Schema, Table, TableId,
        TablesDiff, TablesDiffItem, Type,
    };
    use crate::stmt;

    fn make_table(id: usize, name: &str, num_columns: usize) -> Table {
        let mut columns = vec![];
        for i in 0..num_columns {
            columns.push(Column {
                id: ColumnId {
                    table: TableId(id),
                    index: i,
                },
                name: format!("col{}", i),
                ty: stmt::Type::String,
                storage_ty: Type::Text,
                nullable: false,
                primary_key: false,
                auto_increment: false,
            });
        }

        Table {
            id: TableId(id),
            name: name.to_string(),
            columns,
            primary_key: PrimaryKey {
                columns: vec![],
                index: IndexId {
                    table: TableId(id),
                    index: 0,
                },
            },
            indices: vec![],
        }
    }

    fn make_schema(tables: Vec<Table>) -> Schema {
        Schema { tables }
    }

    #[test]
    fn test_no_diff_same_tables() {
        let from_tables = vec![make_table(0, "users", 2), make_table(1, "posts", 3)];
        let to_tables = vec![make_table(0, "users", 2), make_table(1, "posts", 3)];

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        assert_eq!(diff.items.len(), 0);
    }

    #[test]
    fn test_create_table() {
        let from_tables = vec![make_table(0, "users", 2)];
        let to_tables = vec![make_table(0, "users", 2), make_table(1, "posts", 3)];

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], TablesDiffItem::CreateTable(_)));
        if let TablesDiffItem::CreateTable(table) = diff.items[0] {
            assert_eq!(table.name, "posts");
        }
    }

    #[test]
    fn test_drop_table() {
        let from_tables = vec![make_table(0, "users", 2), make_table(1, "posts", 3)];
        let to_tables = vec![make_table(0, "users", 2)];

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], TablesDiffItem::DropTable(_)));
        if let TablesDiffItem::DropTable(table) = diff.items[0] {
            assert_eq!(table.name, "posts");
        }
    }

    #[test]
    fn test_rename_table_with_hint() {
        let from_tables = vec![make_table(0, "old_users", 2)];
        let to_tables = vec![make_table(0, "new_users", 2)];

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());

        let mut hints = RenameHints::new();
        hints.add_table_hint(TableId(0), TableId(0));
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], TablesDiffItem::AlterTable { .. }));
        if let TablesDiffItem::AlterTable { previous, next, .. } = &diff.items[0] {
            assert_eq!(previous.name, "old_users");
            assert_eq!(next.name, "new_users");
        }
    }

    #[test]
    fn test_rename_table_without_hint_is_drop_and_create() {
        let from_tables = vec![make_table(0, "old_users", 2)];
        let to_tables = vec![make_table(0, "new_users", 2)];

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        assert_eq!(diff.items.len(), 2);

        let has_drop = diff
            .items
            .iter()
            .any(|item| matches!(item, TablesDiffItem::DropTable(_)));
        let has_create = diff
            .items
            .iter()
            .any(|item| matches!(item, TablesDiffItem::CreateTable(_)));
        assert!(has_drop);
        assert!(has_create);
    }

    #[test]
    fn test_alter_table_column_change() {
        let from_tables = vec![make_table(0, "users", 2)];
        let to_tables = vec![make_table(0, "users", 3)]; // added a column

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], TablesDiffItem::AlterTable { .. }));
    }

    #[test]
    fn test_multiple_operations() {
        let from_tables = vec![
            make_table(0, "users", 2),
            make_table(1, "posts", 3),
            make_table(2, "old_table", 1),
        ];
        let to_tables = vec![
            make_table(0, "users", 3),     // added column
            make_table(1, "new_posts", 3), // renamed
            make_table(2, "comments", 2),  // new table (reused ID 2)
        ];

        let from_schema = make_schema(from_tables.clone());
        let to_schema = make_schema(to_tables.clone());

        let mut hints = RenameHints::new();
        hints.add_table_hint(TableId(1), TableId(1));
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = TablesDiff::from(&cx, &from_tables, &to_tables);
        // Should have: 1 alter (users added column), 1 alter (posts renamed), 1 drop (old_table), 1 create (comments)
        assert_eq!(diff.items.len(), 4);
    }
}