sqlite-diff-rs 0.10.0

Build SQLite changeset and patchset binary formats programmatically, without SQLite
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
//! Tests for `maxwell` wire event digestion via `DiffSetBuilder::digest`.
//!
//! Exercises the `Digestable` impls on `Message` for both
//! `ChangesetFormat` and `PatchsetFormat`, covering every operation kind,
//! and error paths.

#![cfg(feature = "maxwell")]

extern crate alloc;

use alloc::vec::Vec;

use sqlite_diff_rs::maxwell::{
    ColumnDefinition, ControlMessage, ConversionError, DatabaseChange, DatabaseDefinition,
    DatabaseDropChange, DdlMetadata, Maxwell, Message, OpType, RowChange, TableAlterChange,
    TableCreateChange, TableDefinition, TableDropChange,
};
use sqlite_diff_rs::{
    ChangeSet, ChangesetOp, DecodeError, DynTable, ParsedDiffSet, PatchSet, PatchsetOp, TypeMap,
    Value,
};

mod common;
use common::{TestUsersTable, test_schema};

fn default_adapter() -> TypeMap<Maxwell, String, Vec<u8>> {
    TypeMap::defaults()
}

fn data_map(id: i64, name: &str, active: bool) -> serde_json::Map<String, serde_json::Value> {
    let mut map = serde_json::Map::new();
    map.insert(
        "id".to_string(),
        serde_json::Value::Number(serde_json::Number::from(id)),
    );
    map.insert(
        "name".to_string(),
        serde_json::Value::String(name.to_string()),
    );
    map.insert("active".to_string(), serde_json::Value::Bool(active));
    map
}

fn row_change(
    table: &str,
    data: serde_json::Map<String, serde_json::Value>,
    old: Option<serde_json::Map<String, serde_json::Value>>,
) -> RowChange {
    RowChange {
        database: "testdb".to_string(),
        table: table.to_string(),
        data,
        old,
        ..Default::default()
    }
}

fn message(
    op_type: OpType,
    data: serde_json::Map<String, serde_json::Value>,
    old: Option<serde_json::Map<String, serde_json::Value>>,
) -> Message {
    let row = row_change("users", data, old);
    match op_type {
        OpType::Insert => Message::Insert(row),
        OpType::Update => Message::Update(row),
        OpType::Delete => Message::Delete(row),
        OpType::BootstrapInsert => Message::BootstrapInsert(row),
        other => panic!("unhandled op type in test helper: {other:?}"),
    }
}

fn minimal_ddl_metadata() -> DdlMetadata {
    DdlMetadata {
        ts: 0,
        sql: String::new(),
        position: None,
        gtid: None,
        schema_id: None,
    }
}

fn minimal_table_definition(database: &str, table: &str) -> TableDefinition {
    TableDefinition {
        database: database.to_string(),
        table: table.to_string(),
        charset: None,
        primary_key: alloc::vec!["id".to_string()],
        columns: alloc::vec![ColumnDefinition {
            name: "id".to_string(),
            column_type: "int".to_string(),
            charset: None,
            signed: None,
            enum_values: None,
            column_length: None,
        }],
    }
}

// -- ChangesetFormat: Insert, Update, Delete --------------------------------

#[test]
fn maxwell_changeset_insert() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(1, "Alice", true);
    let msg = message(OpType::Insert, data, None);

    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = cs.iter().collect();
    assert_eq!(ops.len(), 1, "one operation expected");
    match &ops[0] {
        ChangesetOp::Insert { table, values, .. } => {
            assert_eq!(table.name(), "users");
            assert_eq!(values.len(), 3, "three columns");
            assert_eq!(values[0], Value::Integer(1), "id");
            assert_eq!(values[1], Value::Text("Alice".to_string()), "name");
            assert_eq!(values[2], Value::Integer(1), "active=true encodes as 1");
        }
        other => panic!("expected Insert, got {other:?}"),
    }
    let bytes: Vec<u8> = cs.build();
    // Parse the encoded bytes back to catch op-code, value-type, and column-count bugs.
    let parsed = ParsedDiffSet::parse(&bytes).expect("bytes must re-parse");
    let ParsedDiffSet::Changeset(parsed_cs) = parsed else {
        panic!("expected changeset marker in encoded bytes");
    };
    let parsed_ops: Vec<_> = parsed_cs.iter().collect();
    assert_eq!(parsed_ops.len(), 1);
    match &parsed_ops[0] {
        ChangesetOp::Insert { values, .. } => {
            assert_eq!(values.len(), 3, "column count in encoded bytes");
            assert_eq!(values[0], Value::Integer(1));
            assert_eq!(values[1], Value::Text("Alice".to_string()));
            assert_eq!(values[2], Value::Integer(1));
        }
        other => panic!("expected Insert in parsed bytes, got {other:?}"),
    }
    // Oracle: our bytes must be bit-for-bit identical to what SQLite emits.
    #[cfg(feature = "testing")]
    {
        let (oracle, _) = sqlite_diff_rs::testing::session_changeset_and_patchset(&[
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, active INTEGER)",
            "INSERT INTO users (id, name, active) VALUES (1, 'Alice', 1)",
        ]);
        assert_eq!(bytes, oracle, "changeset bytes must match SQLite");
    }
}

#[test]
fn maxwell_changeset_update() {
    let schema = test_schema();
    let adapter = default_adapter();
    let new_data = data_map(1, "Alicia", true);
    let old_data = data_map(1, "Alice", true);
    let msg = message(OpType::Update, new_data, Some(old_data));

    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = cs.iter().collect();
    assert_eq!(ops.len(), 1, "one operation expected");
    match &ops[0] {
        ChangesetOp::Update { table, values, .. } => {
            assert_eq!(table.name(), "users");
            assert_eq!(values.len(), 3, "three columns");
            assert_eq!(values[0].0, Some(Value::Integer(1)), "old id");
            assert_eq!(values[0].1, Some(Value::Integer(1)), "new id (unchanged)");
            assert_eq!(
                values[1].0,
                Some(Value::Text("Alice".to_string())),
                "old name"
            );
            assert_eq!(
                values[1].1,
                Some(Value::Text("Alicia".to_string())),
                "new name"
            );
        }
        other => panic!("expected Update, got {other:?}"),
    }
    let bytes: Vec<u8> = cs.build();
    let parsed = ParsedDiffSet::parse(&bytes).expect("bytes must re-parse");
    let ParsedDiffSet::Changeset(parsed_cs) = parsed else {
        panic!("expected changeset marker");
    };
    let parsed_ops: Vec<_> = parsed_cs.iter().collect();
    assert_eq!(parsed_ops.len(), 1);
    match &parsed_ops[0] {
        ChangesetOp::Update { values, .. } => {
            assert_eq!(values.len(), 3, "column count in encoded bytes");
            assert_eq!(values[1].0, Some(Value::Text("Alice".to_string())));
            assert_eq!(values[1].1, Some(Value::Text("Alicia".to_string())));
        }
        other => panic!("expected Update in parsed bytes, got {other:?}"),
    }
}

#[test]
fn maxwell_changeset_delete() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(1, "Alice", true);
    let msg = message(OpType::Delete, data, None);

    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = cs.iter().collect();
    assert_eq!(ops.len(), 1, "one operation expected");
    match &ops[0] {
        ChangesetOp::Delete {
            table, old_values, ..
        } => {
            assert_eq!(table.name(), "users");
            assert_eq!(old_values.len(), 3, "three columns");
            assert_eq!(old_values[0], Value::Integer(1), "id");
            assert_eq!(old_values[1], Value::Text("Alice".to_string()), "name");
            assert_eq!(old_values[2], Value::Integer(1), "active=true encodes as 1");
        }
        other => panic!("expected Delete, got {other:?}"),
    }
    let bytes: Vec<u8> = cs.build();
    let parsed = ParsedDiffSet::parse(&bytes).expect("bytes must re-parse");
    let ParsedDiffSet::Changeset(parsed_cs) = parsed else {
        panic!("expected changeset marker");
    };
    let parsed_ops: Vec<_> = parsed_cs.iter().collect();
    assert_eq!(parsed_ops.len(), 1);
    match &parsed_ops[0] {
        ChangesetOp::Delete { old_values, .. } => {
            assert_eq!(old_values.len(), 3, "column count in encoded bytes");
            assert_eq!(old_values[0], Value::Integer(1));
            assert_eq!(old_values[1], Value::Text("Alice".to_string()));
            assert_eq!(old_values[2], Value::Integer(1));
        }
        other => panic!("expected Delete in parsed bytes, got {other:?}"),
    }
}

// -- PatchsetFormat: Insert, Update, Delete ---------------------------------

#[test]
fn maxwell_patchset_insert() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(1, "Alice", true);
    let msg = message(OpType::Insert, data, None);

    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = ps.iter().collect();
    assert_eq!(ops.len(), 1, "one operation expected");
    match &ops[0] {
        PatchsetOp::Insert { table, values, .. } => {
            assert_eq!(table.name(), "users");
            assert_eq!(values.len(), 3, "three columns");
            assert_eq!(values[0], Value::Integer(1), "id");
            assert_eq!(values[1], Value::Text("Alice".to_string()), "name");
            assert_eq!(values[2], Value::Integer(1), "active=true encodes as 1");
        }
        other => panic!("expected Insert, got {other:?}"),
    }
    let bytes: Vec<u8> = ps.build();
    let parsed = ParsedDiffSet::parse(&bytes).expect("bytes must re-parse");
    let ParsedDiffSet::Patchset(parsed_ps) = parsed else {
        panic!("expected patchset marker in encoded bytes");
    };
    let parsed_ops: Vec<_> = parsed_ps.iter().collect();
    assert_eq!(parsed_ops.len(), 1);
    match &parsed_ops[0] {
        PatchsetOp::Insert { values, .. } => {
            assert_eq!(values.len(), 3, "column count in encoded bytes");
            assert_eq!(values[0], Value::Integer(1));
            assert_eq!(values[1], Value::Text("Alice".to_string()));
            assert_eq!(values[2], Value::Integer(1));
        }
        other => panic!("expected Insert in parsed bytes, got {other:?}"),
    }
    // Oracle: our bytes must be bit-for-bit identical to what SQLite emits.
    #[cfg(feature = "testing")]
    {
        let (_, oracle) = sqlite_diff_rs::testing::session_changeset_and_patchset(&[
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, active INTEGER)",
            "INSERT INTO users (id, name, active) VALUES (1, 'Alice', 1)",
        ]);
        assert_eq!(bytes, oracle, "patchset bytes must match SQLite");
    }
}

#[test]
fn maxwell_patchset_update() {
    let schema = test_schema();
    let adapter = default_adapter();
    let new_data = data_map(1, "Alicia", true);
    let msg = message(OpType::Update, new_data, None);

    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = ps.iter().collect();
    assert_eq!(ops.len(), 1, "one operation expected");
    match &ops[0] {
        PatchsetOp::Update {
            table, pk, entries, ..
        } => {
            assert_eq!(table.name(), "users");
            assert_eq!(pk, &[Value::Integer(1)], "primary key");
            assert_eq!(entries.len(), 3, "three column entries");
            assert_eq!(
                entries[1].1,
                Some(Value::Text("Alicia".to_string())),
                "new name"
            );
            assert_eq!(entries[2].1, Some(Value::Integer(1)), "new active");
        }
        other => panic!("expected Update, got {other:?}"),
    }
    let bytes: Vec<u8> = ps.build();
    let parsed = ParsedDiffSet::parse(&bytes).expect("bytes must re-parse");
    let ParsedDiffSet::Patchset(parsed_ps) = parsed else {
        panic!("expected patchset marker");
    };
    let parsed_ops: Vec<_> = parsed_ps.iter().collect();
    assert_eq!(parsed_ops.len(), 1);
    match &parsed_ops[0] {
        PatchsetOp::Update { pk, entries, .. } => {
            assert_eq!(pk, &[Value::Integer(1)]);
            assert_eq!(entries.len(), 3, "column count in encoded bytes");
            assert_eq!(entries[1].1, Some(Value::Text("Alicia".to_string())));
        }
        other => panic!("expected Update in parsed bytes, got {other:?}"),
    }
}

#[test]
fn maxwell_patchset_delete() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(1, "Alice", true);
    let msg = message(OpType::Delete, data, None);

    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = ps.iter().collect();
    assert_eq!(ops.len(), 1, "one operation expected");
    match &ops[0] {
        PatchsetOp::Delete { table, pk, .. } => {
            assert_eq!(table.name(), "users");
            assert_eq!(pk, &[Value::Integer(1)], "primary key of deleted row");
        }
        other => panic!("expected Delete, got {other:?}"),
    }
    let bytes: Vec<u8> = ps.build();
    let parsed = ParsedDiffSet::parse(&bytes).expect("bytes must re-parse");
    let ParsedDiffSet::Patchset(parsed_ps) = parsed else {
        panic!("expected patchset marker");
    };
    let parsed_ops: Vec<_> = parsed_ps.iter().collect();
    assert_eq!(parsed_ops.len(), 1);
    match &parsed_ops[0] {
        PatchsetOp::Delete { pk, .. } => {
            assert_eq!(pk, &[Value::Integer(1)], "primary key in encoded bytes");
        }
        other => panic!("expected Delete in parsed bytes, got {other:?}"),
    }
}

// -- Error paths -----------------------------------------------------------

#[test]
fn maxwell_table_not_found_is_error() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(1, "Alice", true);

    let msg = Message::Insert(row_change("nonexistent", data, None));

    let result: Result<ChangeSet<TestUsersTable, String, Vec<u8>>, ConversionError> =
        ChangeSet::new().digest(&msg, &schema, &adapter);
    match result {
        Err(ConversionError::TableNotFound(n)) => assert_eq!(n, "nonexistent"),
        Err(other) => panic!("expected TableNotFound, got {other:?}"),
        Ok(_) => panic!("expected error"),
    }
}

#[test]
fn maxwell_column_not_found_is_error() {
    let schema = test_schema();
    let adapter = default_adapter();

    let mut data = serde_json::Map::new();
    data.insert(
        "missing_col".to_string(),
        serde_json::Value::Number(serde_json::Number::from(1_i64)),
    );
    let msg = message(OpType::Insert, data, None);

    let result: Result<ChangeSet<TestUsersTable, String, Vec<u8>>, ConversionError> =
        ChangeSet::new().digest(&msg, &schema, &adapter);
    match result {
        Err(ConversionError::ColumnNotFound(n)) => assert!(n.contains("missing_col")),
        Err(other) => panic!("expected ColumnNotFound, got {other:?}"),
        Ok(_) => panic!("expected error"),
    }
}

#[test]
fn maxwell_decode_error_is_propagated() {
    let adapter: TypeMap<Maxwell, String, Vec<u8>> = TypeMap::new();
    let schema = test_schema();
    let data = data_map(1, "Alice", true);
    let msg = message(OpType::Insert, data, None);

    let result: Result<ChangeSet<TestUsersTable, String, Vec<u8>>, ConversionError> =
        ChangeSet::new().digest(&msg, &schema, &adapter);
    match result {
        Err(ConversionError::Decode(DecodeError::NoDecoderForType { column })) => {
            assert_ne!(column, "");
        }
        Err(other) => panic!("expected Decode(NoDecoderForType), got {other:?}"),
        Ok(_) => panic!("expected error"),
    }
}

#[test]
fn maxwell_changeset_update_without_old_is_ok() {
    // Maxwell updates carry `old` as optional. When it is absent, every column
    // is treated as unchanged (old equals new), since Maxwell lists changed
    // columns in `old`.
    let schema = test_schema();
    let adapter = default_adapter();
    let new_data = data_map(1, "Alice", true);
    let msg = message(OpType::Update, new_data, None);

    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    let bytes: Vec<u8> = cs.build();
    assert!(
        !bytes.is_empty(),
        "changeset must produce output without old data"
    );
}

// -- Changeset UPDATE captures the old primary key -------------------------
//
// Maxwell's `old` carries only the columns that changed, so the unchanged
// primary key of a non-key update is absent from it. The digest must still
// capture the old key (equal to the new key, since it did not change) so a
// changeset apply can build a WHERE clause.

#[test]
fn maxwell_changeset_update_captures_old_pk_when_old_omits_it() {
    let schema = test_schema();
    let adapter = default_adapter();
    let new_data = data_map(1, "Alicia", true);
    // Only the changed column is present in `old`, as Maxwell emits it.
    let mut old = serde_json::Map::new();
    old.insert(
        "name".to_string(),
        serde_json::Value::String("Alice".to_string()),
    );
    let msg = message(OpType::Update, new_data, Some(old));

    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = cs.iter().collect();
    assert_eq!(ops.len(), 1);
    match &ops[0] {
        ChangesetOp::Update { values, .. } => {
            assert_eq!(
                values[0].0,
                Some(Value::Integer(1)),
                "old primary key must be captured even when absent from `old`"
            );
            assert_eq!(
                values[1].0,
                Some(Value::Text("Alice".to_string())),
                "old name"
            );
            assert_eq!(
                values[1].1,
                Some(Value::Text("Alicia".to_string())),
                "new name"
            );
            // An unchanged column absent from `old` is captured as old == new.
            assert_eq!(
                values[2].0, values[2].1,
                "unchanged column captured as old == new"
            );
        }
        other => panic!("expected update, got {other:?}"),
    }
}

#[test]
fn maxwell_changeset_update_captures_changed_pk() {
    // A primary-key change: Maxwell includes the changed key in `old`.
    let schema = test_schema();
    let adapter = default_adapter();
    let new_data = data_map(2, "Alice", true);
    let mut old = serde_json::Map::new();
    old.insert(
        "id".to_string(),
        serde_json::Value::Number(serde_json::Number::from(1_i64)),
    );
    let msg = message(OpType::Update, new_data, Some(old));

    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    let ops: Vec<_> = cs.iter().collect();
    match &ops[0] {
        ChangesetOp::Update { values, .. } => {
            assert_eq!(values[0].0, Some(Value::Integer(1)), "old key");
            assert_eq!(values[0].1, Some(Value::Integer(2)), "new key");
        }
        other => panic!("expected update, got {other:?}"),
    }
}

// -- Contract: BootstrapInsert digests as Insert ---------------------------

#[test]
fn bootstrap_insert_changeset_matches_insert() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(42, "Eve", false);

    let insert_msg = message(OpType::Insert, data.clone(), None);
    let bootstrap_msg = message(OpType::BootstrapInsert, data, None);

    let insert_bytes: Vec<u8> = ChangeSet::new()
        .digest(&insert_msg, &schema, &adapter)
        .unwrap()
        .build();
    let bootstrap_bytes: Vec<u8> = ChangeSet::new()
        .digest(&bootstrap_msg, &schema, &adapter)
        .unwrap()
        .build();

    assert_eq!(
        insert_bytes, bootstrap_bytes,
        "BootstrapInsert changeset must be identical to Insert on the same row"
    );
}

#[test]
fn bootstrap_insert_patchset_matches_insert() {
    let schema = test_schema();
    let adapter = default_adapter();
    let data = data_map(42, "Eve", false);

    let insert_msg = message(OpType::Insert, data.clone(), None);
    let bootstrap_msg = message(OpType::BootstrapInsert, data, None);

    let insert_bytes: Vec<u8> = PatchSet::new()
        .digest(&insert_msg, &schema, &adapter)
        .unwrap()
        .build();
    let bootstrap_bytes: Vec<u8> = PatchSet::new()
        .digest(&bootstrap_msg, &schema, &adapter)
        .unwrap()
        .build();

    assert_eq!(
        insert_bytes, bootstrap_bytes,
        "BootstrapInsert patchset must be identical to Insert on the same row"
    );
}

// -- Contract: non-row variants return the builder unchanged ---------------

#[test]
fn bootstrap_start_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::BootstrapStart(ControlMessage {
        database: "testdb".to_string(),
        table: "users".to_string(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "BootstrapStart must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "BootstrapStart must not add any ops");
}

#[test]
fn bootstrap_complete_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::BootstrapComplete(ControlMessage {
        database: "testdb".to_string(),
        table: "users".to_string(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(
        cs.iter().count(),
        0,
        "BootstrapComplete must not add any ops"
    );
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(
        ps.iter().count(),
        0,
        "BootstrapComplete must not add any ops"
    );
}

#[test]
fn table_create_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::TableCreate(TableCreateChange {
        database: "testdb".to_string(),
        table: "users".to_string(),
        definition: minimal_table_definition("testdb", "users"),
        metadata: minimal_ddl_metadata(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "TableCreate must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "TableCreate must not add any ops");
}

#[test]
fn table_alter_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::TableAlter(TableAlterChange {
        database: "testdb".to_string(),
        table: "users".to_string(),
        old_definition: minimal_table_definition("testdb", "users"),
        definition: minimal_table_definition("testdb", "users"),
        metadata: minimal_ddl_metadata(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "TableAlter must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "TableAlter must not add any ops");
}

#[test]
fn table_drop_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::TableDrop(TableDropChange {
        database: "testdb".to_string(),
        table: "users".to_string(),
        metadata: minimal_ddl_metadata(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "TableDrop must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "TableDrop must not add any ops");
}

#[test]
fn database_create_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::DatabaseCreate(DatabaseChange {
        definition: DatabaseDefinition {
            database: "testdb".to_string(),
            charset: None,
        },
        metadata: minimal_ddl_metadata(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "DatabaseCreate must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "DatabaseCreate must not add any ops");
}

#[test]
fn database_alter_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::DatabaseAlter(DatabaseChange {
        definition: DatabaseDefinition {
            database: "testdb".to_string(),
            charset: None,
        },
        metadata: minimal_ddl_metadata(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "DatabaseAlter must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "DatabaseAlter must not add any ops");
}

#[test]
fn database_drop_leaves_builder_unchanged() {
    let schema = test_schema();
    let adapter = default_adapter();
    let msg = Message::DatabaseDrop(DatabaseDropChange {
        database: "testdb".to_string(),
        metadata: minimal_ddl_metadata(),
        ..Default::default()
    });
    let cs: ChangeSet<TestUsersTable, String, Vec<u8>> =
        ChangeSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(cs.iter().count(), 0, "DatabaseDrop must not add any ops");
    let ps: PatchSet<TestUsersTable, String, Vec<u8>> =
        PatchSet::new().digest(&msg, &schema, &adapter).unwrap();
    assert_eq!(ps.iter().count(), 0, "DatabaseDrop must not add any ops");
}