toasty-core 0.3.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
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
use super::{Column, ColumnId, DiffContext, Schema, TableId};
use crate::stmt;

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

/// A database index over one or more columns of a table.
///
/// Indices can be unique or non-unique, and can cover the primary key.
/// Each indexed column specifies an [`IndexOp`] (equality or sort) and an
/// [`IndexScope`] (partition or local).
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::{Index, IndexColumn, IndexId, IndexOp, IndexScope, ColumnId, TableId};
///
/// let index = Index {
///     id: IndexId { table: TableId(0), index: 0 },
///     name: "idx_users_email".to_string(),
///     on: TableId(0),
///     columns: vec![IndexColumn {
///         column: ColumnId { table: TableId(0), index: 1 },
///         op: IndexOp::Eq,
///         scope: IndexScope::Local,
///     }],
///     unique: true,
///     primary_key: false,
/// };
///
/// assert!(index.unique);
/// assert_eq!(index.columns.len(), 1);
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Index {
    /// Uniquely identifies the index within the schema
    pub id: IndexId,

    /// Index name is unique within the schema
    pub name: String,

    /// The table being indexed
    pub on: TableId,

    /// Fields included in the index.
    pub columns: Vec<IndexColumn>,

    /// When `true`, indexed entries are unique
    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub unique: bool,

    /// When `true`, the index indexes the model's primary key fields.
    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
    pub primary_key: bool,
}

#[cfg(feature = "serde")]
fn is_false(b: &bool) -> bool {
    !*b
}

/// Uniquely identifies an index within a schema.
///
/// Combines the [`TableId`] of the owning table with the index's positional
/// offset in that table's index list.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::{IndexId, TableId};
///
/// let id = IndexId { table: TableId(0), index: 1 };
/// assert_eq!(id.index, 1);
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IndexId {
    /// The table this index belongs to.
    pub table: TableId,
    /// Zero-based position of this index in the table's index list.
    pub index: usize,
}

/// A single column entry within an [`Index`].
///
/// Specifies which column is indexed, the comparison operation, and the scope
/// (partition vs. local).
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::{IndexColumn, IndexOp, IndexScope, ColumnId, TableId};
///
/// let ic = IndexColumn {
///     column: ColumnId { table: TableId(0), index: 0 },
///     op: IndexOp::Eq,
///     scope: IndexScope::Local,
/// };
///
/// assert!(ic.scope.is_local());
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IndexColumn {
    /// The column being indexed
    pub column: ColumnId,

    /// The comparison operation used to index the column
    pub op: IndexOp,

    /// Scope of the index
    pub scope: IndexScope,
}

/// The comparison operation used by an index column.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::IndexOp;
/// use toasty_core::stmt::Direction;
///
/// let op = IndexOp::Sort(Direction::Asc);
/// assert!(matches!(op, IndexOp::Sort(_)));
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IndexOp {
    /// Equality lookup.
    Eq,
    /// Sorted scan in the given direction.
    Sort(stmt::Direction),
}

/// Scope of an index column, relevant for distributed databases.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::schema::db::IndexScope;
///
/// let scope = IndexScope::Partition;
/// assert!(scope.is_partition());
/// assert!(!scope.is_local());
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IndexScope {
    /// The index column is used to partition rows across nodes of a distributed database.
    Partition,

    /// The index column is scoped to a physical node.
    Local,
}

impl IndexColumn {
    /// Returns the [`Column`] referenced by this index column.
    pub fn table_column<'a>(&self, schema: &'a Schema) -> &'a Column {
        schema.column(self.column)
    }
}

impl IndexScope {
    /// Returns `true` if this is the [`Partition`](IndexScope::Partition) scope.
    pub fn is_partition(self) -> bool {
        matches!(self, Self::Partition)
    }

    /// Returns `true` if this is the [`Local`](IndexScope::Local) scope.
    pub fn is_local(self) -> bool {
        matches!(self, Self::Local)
    }
}

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

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

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

impl<'a> IndicesDiff<'a> {
    /// Computes the diff between two index slices.
    ///
    /// Uses [`DiffContext`] to resolve rename hints for both indices and columns.
    /// Indices matched by name (or by rename hint) are compared; unmatched
    /// indices in `previous` become drops, and unmatched indices in `next`
    /// become creates.
    pub fn from(cx: &DiffContext<'a>, previous: &'a [Index], next: &'a [Index]) -> Self {
        fn has_diff(cx: &DiffContext<'_>, previous: &Index, next: &Index) -> bool {
            // Check basic properties
            if previous.name != next.name
                || previous.columns.len() != next.columns.len()
                || previous.unique != next.unique
                || previous.primary_key != next.primary_key
            {
                return true;
            }

            // Check if index columns have changed
            for (previous_col, next_col) in previous.columns.iter().zip(next.columns.iter()) {
                // Check if op or scope changed
                if previous_col.op != next_col.op || previous_col.scope != next_col.scope {
                    return true;
                }

                // Check if the column changed (accounting for renames)
                let columns_match =
                    if let Some(renamed_to) = cx.rename_hints().get_column(previous_col.column) {
                        // Column was renamed - check if it matches the target column
                        renamed_to == next_col.column
                    } else {
                        // No rename hint - check if columns match by name
                        let previous_column = cx.previous().column(previous_col.column);
                        let next_column = cx.next().column(next_col.column);
                        previous_column.name == next_column.name
                    };

                if !columns_match {
                    return true;
                }
            }

            false
        }

        let mut items = vec![];
        let mut create_ids: HashSet<_> = next.iter().map(|to| to.id).collect();

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

        for previous in previous {
            let next = if let Some(next_id) = cx.rename_hints().get_index(previous.id) {
                cx.next().index(next_id)
            } else if let Some(next) = next_map.get(previous.name.as_str()) {
                next
            } else {
                items.push(IndicesDiffItem::DropIndex(previous));
                continue;
            };

            create_ids.remove(&next.id);

            if has_diff(cx, previous, next) {
                items.push(IndicesDiffItem::AlterIndex { previous, next });
            }
        }

        for index_id in create_ids {
            items.push(IndicesDiffItem::CreateIndex(cx.next().index(index_id)));
        }

        Self { items }
    }

    /// Returns `true` if there are no index changes.
    pub const fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

impl<'a> Deref for IndicesDiff<'a> {
    type Target = Vec<IndicesDiffItem<'a>>;

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

/// A single change detected between two index lists.
pub enum IndicesDiffItem<'a> {
    /// A new index was created.
    CreateIndex(&'a Index),
    /// An existing index was dropped.
    DropIndex(&'a Index),
    /// An index was modified (name, columns, uniqueness, or other property changed).
    AlterIndex {
        /// The index definition before the change.
        previous: &'a Index,
        /// The index definition after the change.
        next: &'a Index,
    },
}

#[cfg(test)]
mod tests {
    use crate::schema::db::{
        Column, ColumnId, DiffContext, Index, IndexColumn, IndexId, IndexOp, IndexScope,
        IndicesDiff, IndicesDiffItem, PrimaryKey, RenameHints, Schema, Table, TableId, Type,
    };
    use crate::stmt;

    fn make_column(table_id: usize, index: usize, name: &str) -> Column {
        Column {
            id: ColumnId {
                table: TableId(table_id),
                index,
            },
            name: name.to_string(),
            ty: stmt::Type::String,
            storage_ty: Type::Text,
            nullable: false,
            primary_key: false,
            auto_increment: false,
        }
    }

    fn make_index(
        table_id: usize,
        index: usize,
        name: &str,
        columns: Vec<(usize, IndexOp, IndexScope)>,
        unique: bool,
    ) -> Index {
        Index {
            id: IndexId {
                table: TableId(table_id),
                index,
            },
            name: name.to_string(),
            on: TableId(table_id),
            columns: columns
                .into_iter()
                .map(|(col_idx, op, scope)| IndexColumn {
                    column: ColumnId {
                        table: TableId(table_id),
                        index: col_idx,
                    },
                    op,
                    scope,
                })
                .collect(),
            unique,
            primary_key: false,
        }
    }

    fn make_schema_with_indices(
        table_id: usize,
        columns: Vec<Column>,
        indices: Vec<Index>,
    ) -> Schema {
        let mut schema = Schema::default();
        schema.tables.push(Table {
            id: TableId(table_id),
            name: "test_table".to_string(),
            columns,
            primary_key: PrimaryKey {
                columns: vec![],
                index: IndexId {
                    table: TableId(table_id),
                    index: 0,
                },
            },
            indices,
        });
        schema
    }

    #[test]
    fn test_no_diff_same_indices() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert!(diff.is_empty());
    }

    #[test]
    fn test_create_index() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::CreateIndex(_)));
        if let IndicesDiffItem::CreateIndex(idx) = diff.items[0] {
            assert_eq!(idx.name, "idx_name");
        }
    }

    #[test]
    fn test_drop_index() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::DropIndex(_)));
        if let IndicesDiffItem::DropIndex(idx) = diff.items[0] {
            assert_eq!(idx.name, "idx_name");
        }
    }

    #[test]
    fn test_alter_index_unique() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            true, // changed to unique
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::AlterIndex { .. }));
    }

    #[test]
    fn test_alter_index_columns() {
        let columns = vec![
            make_column(0, 0, "id"),
            make_column(0, 1, "name"),
            make_column(0, 2, "email"),
        ];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![
                (1, IndexOp::Eq, IndexScope::Local),
                (2, IndexOp::Eq, IndexScope::Local),
            ],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::AlterIndex { .. }));
    }

    #[test]
    fn test_alter_index_op() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Sort(stmt::Direction::Asc), IndexScope::Local)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::AlterIndex { .. }));
    }

    #[test]
    fn test_alter_index_scope() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Partition)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::AlterIndex { .. }));
    }

    #[test]
    fn test_rename_index_with_hint() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "old_idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "new_idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());

        let mut hints = RenameHints::new();
        hints.add_index_hint(
            IndexId {
                table: TableId(0),
                index: 0,
            },
            IndexId {
                table: TableId(0),
                index: 0,
            },
        );
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(diff.items[0], IndicesDiffItem::AlterIndex { .. }));
        if let IndicesDiffItem::AlterIndex { previous, next } = diff.items[0] {
            assert_eq!(previous.name, "old_idx_name");
            assert_eq!(next.name, "new_idx_name");
        }
    }

    #[test]
    fn test_rename_index_without_hint_is_drop_and_create() {
        let columns = vec![make_column(0, 0, "id"), make_column(0, 1, "name")];

        let from_indices = vec![make_index(
            0,
            0,
            "old_idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "new_idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());
        let hints = RenameHints::new();
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        assert_eq!(diff.items.len(), 2);

        let has_drop = diff
            .items
            .iter()
            .any(|item| matches!(item, IndicesDiffItem::DropIndex(_)));
        let has_create = diff
            .items
            .iter()
            .any(|item| matches!(item, IndicesDiffItem::CreateIndex(_)));
        assert!(has_drop);
        assert!(has_create);
    }

    #[test]
    fn test_index_with_renamed_column() {
        let from_columns = vec![make_column(0, 0, "id"), make_column(0, 1, "old_name")];
        let to_columns = vec![make_column(0, 0, "id"), make_column(0, 1, "new_name")];

        let from_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];
        let to_indices = vec![make_index(
            0,
            0,
            "idx_name",
            vec![(1, IndexOp::Eq, IndexScope::Local)],
            false,
        )];

        let from_schema = make_schema_with_indices(0, from_columns, from_indices.clone());
        let to_schema = make_schema_with_indices(0, to_columns, to_indices.clone());

        let mut hints = RenameHints::new();
        hints.add_column_hint(
            ColumnId {
                table: TableId(0),
                index: 1,
            },
            ColumnId {
                table: TableId(0),
                index: 1,
            },
        );
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        // Index should remain unchanged when column is renamed with hint
        assert!(diff.is_empty());
    }

    #[cfg(feature = "serde")]
    mod serde_tests {
        use crate::schema::db::{
            ColumnId, Index, IndexColumn, IndexId, IndexOp, IndexScope, TableId,
        };

        fn base_index() -> Index {
            Index {
                id: IndexId {
                    table: TableId(0),
                    index: 0,
                },
                name: "idx".to_string(),
                on: TableId(0),
                columns: vec![IndexColumn {
                    column: ColumnId {
                        table: TableId(0),
                        index: 0,
                    },
                    op: IndexOp::Eq,
                    scope: IndexScope::Local,
                }],
                unique: false,
                primary_key: false,
            }
        }

        #[test]
        fn false_booleans_are_omitted() {
            let toml = toml::to_string(&base_index()).unwrap();
            assert!(!toml.contains("unique"), "toml: {toml}");
            assert!(!toml.contains("primary_key"), "toml: {toml}");
        }

        #[test]
        fn unique_true_is_included() {
            let idx = Index {
                unique: true,
                ..base_index()
            };
            let toml = toml::to_string(&idx).unwrap();
            assert!(toml.contains("unique = true"), "toml: {toml}");
        }

        #[test]
        fn primary_key_true_is_included() {
            let idx = Index {
                primary_key: true,
                ..base_index()
            };
            let toml = toml::to_string(&idx).unwrap();
            assert!(toml.contains("primary_key = true"), "toml: {toml}");
        }

        #[test]
        fn missing_bool_fields_deserialize_as_false() {
            let toml = "name = \"idx\"\non = 0\n\n[id]\ntable = 0\nindex = 0\n\n[[columns]]\nop = \"Eq\"\nscope = \"Local\"\n\n[columns.column]\ntable = 0\nindex = 0\n";
            let idx: Index = toml::from_str(toml).unwrap();
            assert!(!idx.unique);
            assert!(!idx.primary_key);
        }

        #[test]
        fn round_trip_all_true() {
            let original = Index {
                unique: true,
                primary_key: true,
                ..base_index()
            };
            let decoded: Index = toml::from_str(&toml::to_string(&original).unwrap()).unwrap();
            assert_eq!(decoded.unique, original.unique);
            assert_eq!(decoded.primary_key, original.primary_key);
            assert_eq!(decoded.name, original.name);
        }
    }

    #[test]
    fn test_multiple_operations() {
        let columns = vec![
            make_column(0, 0, "id"),
            make_column(0, 1, "name"),
            make_column(0, 2, "email"),
        ];

        let from_indices = vec![
            make_index(
                0,
                0,
                "idx_name",
                vec![(1, IndexOp::Eq, IndexScope::Local)],
                false,
            ),
            make_index(
                0,
                1,
                "old_idx",
                vec![(2, IndexOp::Eq, IndexScope::Local)],
                false,
            ),
            make_index(
                0,
                2,
                "idx_to_drop",
                vec![(0, IndexOp::Eq, IndexScope::Local)],
                false,
            ),
        ];
        let to_indices = vec![
            make_index(
                0,
                0,
                "idx_name",
                vec![(1, IndexOp::Eq, IndexScope::Local)],
                true, // changed to unique
            ),
            make_index(
                0,
                1,
                "new_idx",
                vec![(2, IndexOp::Eq, IndexScope::Local)],
                false,
            ),
            make_index(
                0,
                2,
                "idx_added",
                vec![(1, IndexOp::Sort(stmt::Direction::Asc), IndexScope::Local)],
                false,
            ),
        ];

        let from_schema = make_schema_with_indices(0, columns.clone(), from_indices.clone());
        let to_schema = make_schema_with_indices(0, columns, to_indices.clone());

        let mut hints = RenameHints::new();
        hints.add_index_hint(
            IndexId {
                table: TableId(0),
                index: 1,
            },
            IndexId {
                table: TableId(0),
                index: 1,
            },
        );
        let cx = DiffContext::new(&from_schema, &to_schema, &hints);

        let diff = IndicesDiff::from(&cx, &from_indices, &to_indices);
        // Should have: 1 alter (idx_name unique changed), 1 alter (renamed), 1 drop (idx_to_drop), 1 create (idx_added)
        assert_eq!(diff.items.len(), 4);
    }
}