mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
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
//! Producing a copy that can re-create the same state elsewhere.
//!
//! # Why the copy is taken inside a transaction
//!
//! A copy of ten tables read one after another is ten copies taken at ten
//! different moments. Restore it and the order lines refer to orders that did
//! not exist yet. The tables must agree with one another, and that agreement
//! is what a consistent read inside a transaction gives.
//!
//! The alternative is to lock every table for the duration, which produces the
//! same agreement by stopping everybody else. That is never what happens
//! unless somebody asked for it: by default this layer opens a transaction
//! with a consistent read and copies inside it, so no reader and no writer is
//! blocked for a single moment.
//!
//! An engine without a consistent read cannot take part in that agreement.
//! Those tables are still copied, because a copy of them is better than no
//! copy, and the shortfall is declared alongside the result rather than
//! quietly passed off as a snapshot.
//!
//! A caller who cannot live with that shortfall sets `data.export_lock` to
//! hold the tables, which buys one instant covering every engine and pays for
//! it with every writer on the destination. The price is why it is asked for
//! and never assumed.

use super::AtomicWriter;
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::checksum::Signature;
use crate::output::envelope::{Gap, Row};
use crate::sql::ident;
use mysql_async::prelude::Queryable;
use mysql_async::{Conn, Value as Wire};
use tokio_util::sync::CancellationToken;

/// What the copy holds still while it is taken.
///
/// Holding nothing still is the default because holding the tables blocks every
/// writer on this destination for as long as the copy runs, and the people
/// blocked never asked for the copy. The price of that default is that a table
/// on an engine with no versions to read from is copied at its own moment
/// rather than at the copy's, and that shortfall is declared rather than
/// passed off as a snapshot.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ExportLock {
    /// Nothing is held still; agreement comes from versions where they exist.
    #[default]
    None,
    /// Every table in the copy is held still, so all of them share one instant.
    Tables,
}

impl ExportLock {
    /// Reads what to hold from the word stored under `data.export_lock`.
    ///
    /// There is no fallback branch on purpose. The registry is the one place
    /// the default of that key lives, and a fallback here would be a second
    /// one, silently winning wherever the two disagreed.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the word is outside the domain the
    /// registry publishes for that key.
    pub fn parse(word: &str) -> Result<Self> {
        match word {
            "none" => Ok(Self::None),
            "tables" => Ok(Self::Tables),
            other => Err(Failure::config(
                "config.unknown_export_lock",
                format!("`{other}` is not something a copy can hold still"),
            )
            .with_detail("detail", other)
            .with_hint("set data.export_lock to none or to tables")),
        }
    }

    /// Whether every writer is stopped for the duration of the copy.
    #[must_use]
    pub const fn holds_the_tables(self) -> bool {
        matches!(self, Self::Tables)
    }
}

/// The statement that holds every table of the copy still.
///
/// One statement names them all, because naming them one at a time would
/// release each previous table as the next is taken, which is the opposite of
/// what is wanted. An empty list produces nothing to send.
///
/// # Errors
///
/// Returns a validation failure when a table name cannot be written into a
/// statement safely.
pub fn hold_statement(tables: &[String]) -> Result<Option<String>> {
    if tables.is_empty() {
        return Ok(None);
    }
    let mut named = Vec::with_capacity(tables.len());
    for table in tables {
        named.push(format!("{} READ", ident::quote(table)?));
    }
    Ok(Some(format!("LOCK TABLES {}", named.join(", "))))
}

/// What the caller asked to be copied, and where.
#[derive(Debug, Clone)]
pub struct ExportRequest {
    /// The database to copy from; absent means the one the session is on.
    pub database: Option<String>,
    /// The tables to copy; empty means every base table of the database.
    pub tables: Vec<String>,
    /// Whether to copy the structure and leave the rows behind.
    pub structure_only: bool,
    /// Where the copy is written.
    pub output: std::path::PathBuf,
    /// The largest the copy may become before it is refused.
    pub ceiling: Option<usize>,
    /// How many rows one statement in the copy carries.
    pub rows_per_statement: usize,
    /// What is held still while the copy is taken.
    pub lock: ExportLock,
}

/// What the copy turned out to be.
#[derive(Debug, Clone)]
pub struct ExportReport {
    /// Where the copy was placed.
    pub path: std::path::PathBuf,
    /// How many objects it describes.
    pub objects: usize,
    /// How many rows it carries.
    pub rows: u64,
    /// How many bytes it weighs.
    pub bytes: usize,
    /// The signature of the rows, comparable with a signature of a read.
    pub content_checksum: String,
    /// Whether the tables in it agree with one another.
    pub consistent: bool,
    /// Tables that could not take part in the agreement, and why.
    pub gaps: Vec<Gap>,
}

/// Engines that can give a consistent read.
///
/// The list is small and closed because the property is a fact about the
/// engine, not a setting: an engine outside it holds no versions to read from.
const SNAPSHOT_ENGINES: [&str; 2] = ["innodb", "xtradb"];

/// Whether an engine can take part in a consistent read.
#[must_use]
pub fn keeps_a_snapshot(engine: &str) -> bool {
    SNAPSHOT_ENGINES.contains(&engine.trim().to_ascii_lowercase().as_str())
}

/// One table, as the copy needs to know it.
#[derive(Debug, Clone, PartialEq, Eq)]
struct TableFacts {
    name: String,
    engine: String,
}

/// Runs the copy from start to finish.
///
/// # Errors
///
/// Returns a limit failure when the copy goes past its volume ceiling, in
/// which case nothing is left at the destination. Returns an interrupted
/// failure when the invocation is told to stop, and the mapped server failure
/// when a statement is refused.
pub async fn run(
    connection: &mut Conn,
    request: &ExportRequest,
    token: &CancellationToken,
) -> Result<ExportReport> {
    let tables = list_tables(connection, request).await?;
    crate::i18n::report::copy_started(tables.len(), &request.output.display().to_string());
    let mut writer = AtomicWriter::create(&request.output, request.ceiling)?;
    writer.write(&header())?;

    // Holding the tables gives every one of them the same instant whatever
    // engine they are on, so nothing is left out of the agreement and there is
    // no shortfall to declare. It is paid for by every writer on this
    // destination, which is why it is never the default.
    let held = request.lock.holds_the_tables();
    let outside: Vec<&TableFacts> = if held {
        Vec::new()
    } else {
        tables
            .iter()
            .filter(|table| !keeps_a_snapshot(&table.engine))
            .collect()
    };
    for table in &outside {
        crate::i18n::report::copy_snapshot_unavailable(&table.name);
    }
    let gaps = outside.iter().map(|table| snapshot_gap(table)).collect();
    let consistent = outside.is_empty();

    if held {
        hold_tables(connection, &tables).await?;
    }
    begin_snapshot(connection).await?;
    let outcome = copy_all(connection, request, &tables, &mut writer, token).await;
    let finished = finish_snapshot(connection).await;
    let released = if held {
        release_tables(connection).await
    } else {
        Ok(())
    };

    // The transaction is closed and the tables are released either way, and the
    // failure of the copy wins over the failure of doing either, because the
    // first one is what the caller has to act on.
    let rows = outcome?;
    finished?;
    released?;

    writer.write("COMMIT;\n")?;
    let written = writer.commit()?;
    crate::i18n::report::copy_finished(rows.count, written.bytes as u64);

    Ok(ExportReport {
        path: written.path,
        objects: tables.len(),
        rows: rows.count,
        bytes: written.bytes,
        content_checksum: rows.checksum,
        consistent,
        gaps,
    })
}

/// The shortfall a table on an engine without versions produces.
fn snapshot_gap(table: &TableFacts) -> Gap {
    Gap::new(
        table.name.clone(),
        "no_consistent_snapshot",
        format!(
            "`{}` is on the `{}` engine, which keeps no versions to read from, so this table is not part of the agreement between the others",
            table.name, table.engine
        ),
    )
}

/// What the rows of the whole copy came to.
struct RowTotals {
    count: u64,
    checksum: String,
}

/// Writes every table, structure first and then rows.
async fn copy_all(
    connection: &mut Conn,
    request: &ExportRequest,
    tables: &[TableFacts],
    writer: &mut AtomicWriter,
    token: &CancellationToken,
) -> Result<RowTotals> {
    let mut signature = Signature::new();
    let mut count = 0;

    for table in tables {
        if token.is_cancelled() {
            return Err(Failure::interrupted(
                "interrupted.during_copy",
                "the invocation was stopped while the copy was being written",
            ));
        }

        crate::i18n::report::copy_table(&table.name);
        writer.write(&format!("\n-- table {}\n", table.name))?;
        writer.write(&structure_of(connection, &table.name).await?)?;

        if !request.structure_only {
            count += copy_rows(
                connection,
                request,
                &table.name,
                writer,
                &mut signature,
                token,
            )
            .await?;
        }
    }

    Ok(RowTotals {
        count,
        checksum: signature.finish(),
    })
}

/// The lines every copy opens with.
///
/// The session settings are written into the copy rather than assumed, because
/// a copy restored on a server configured differently must still read the same
/// way it was written.
///
/// # Why the backslash mode is named here
///
/// It is not a preference: it is the other half of how a value is written.
/// [`super::literal::literal`] renders text through the driver's escaping with
/// the no-backslash rule ON, which doubles a quote and leaves a backslash
/// exactly as it stood. That is only correct on a server reading under the same
/// rule. Without it, a restore takes the backslash as an escape introducer and
/// the value silently changes: `C:\novo` comes back as `C:` followed by a line
/// break and `ovo`, and a value ending in a backslash escapes the closing quote
/// so the statement runs on into whatever follows it.
///
/// The two have to be named in one place or agree by luck, and they were
/// disagreeing: the mode was written without this and the values were written
/// as if it were there.
pub(super) fn header() -> String {
    concat!(
        "-- logical copy produced by ",
        env!("CARGO_PKG_NAME"),
        "\n",
        "SET @saved_sql_mode = @@SQL_MODE;\n",
        "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO,NO_BACKSLASH_ESCAPES';\n",
        "SET @saved_foreign_key_checks = @@FOREIGN_KEY_CHECKS;\n",
        "SET FOREIGN_KEY_CHECKS = 0;\n",
        "START TRANSACTION;\n",
    )
    .to_owned()
}

/// Opens the transaction the whole copy is read inside.
async fn begin_snapshot(connection: &mut Conn) -> Result<()> {
    connection
        .query_drop("START TRANSACTION WITH CONSISTENT SNAPSHOT")
        .await
        .or_failure()
}

/// Holds every table of the copy still, so all of them share one instant.
///
/// # Errors
///
/// Returns a validation failure when a table name cannot be written into a
/// statement safely, and the mapped server failure when the hold is refused.
async fn hold_tables(connection: &mut Conn, tables: &[TableFacts]) -> Result<()> {
    let names: Vec<String> = tables.iter().map(|table| table.name.clone()).collect();
    let Some(statement) = hold_statement(&names)? else {
        return Ok(());
    };
    connection.query_drop(statement).await.or_failure()
}

/// Lets every writer this copy stopped carry on.
///
/// # Errors
///
/// Returns the mapped server failure when the release is refused.
async fn release_tables(connection: &mut Conn) -> Result<()> {
    connection.query_drop("UNLOCK TABLES").await.or_failure()
}

/// Closes the transaction the copy was read inside.
async fn finish_snapshot(connection: &mut Conn) -> Result<()> {
    connection.query_drop("COMMIT").await.or_failure()
}

/// The tables this copy covers.
async fn list_tables(connection: &mut Conn, request: &ExportRequest) -> Result<Vec<TableFacts>> {
    let statement = "SELECT TABLE_NAME, IFNULL(ENGINE, '') \
         FROM information_schema.TABLES \
         WHERE TABLE_SCHEMA = IFNULL(?, DATABASE()) AND TABLE_TYPE = 'BASE TABLE' \
         ORDER BY TABLE_NAME";

    let found: Vec<(String, String)> = connection
        .exec(statement, (request.database.clone(),))
        .await
        .or_failure()?;

    let mut facts: Vec<TableFacts> = found
        .into_iter()
        .map(|(name, engine)| TableFacts { name, engine })
        .collect();

    if !request.tables.is_empty() {
        facts.retain(|table| request.tables.contains(&table.name));
        for wanted in &request.tables {
            if !facts.iter().any(|table| table.name == *wanted) {
                return Err(Failure::absence(
                    "datamove.table_absent",
                    format!("`{wanted}` is not a table of this database"),
                )
                .with_detail("detail", wanted.clone())
                .with_hint("run `schema tables` to see what is there"));
            }
        }
    }

    Ok(facts)
}

/// The statement that re-creates one table.
async fn structure_of(connection: &mut Conn, table: &str) -> Result<String> {
    let quoted = ident::quote(table)?;
    let created: Option<(String, String)> = connection
        .query_first(format!("SHOW CREATE TABLE {quoted}"))
        .await
        .or_failure()?;

    let (_, definition) = created.ok_or_else(|| {
        Failure::absence(
            "datamove.structure_absent",
            format!("the server described no structure for `{table}`"),
        )
        .with_detail("detail", table)
    })?;

    Ok(format!("DROP TABLE IF EXISTS {quoted};\n{definition};\n"))
}

/// Writes the rows of one table, in statements of the configured size.
///
/// # Why the stop signal is read here and not only between tables
///
/// The caller already asks before each table, which answers for a copy of many
/// small ones and answers for nothing at all when a copy is one large table.
/// That is the ordinary shape: the table worth copying is the big one. Without
/// this, an interrupted copy of a single hundred-million-row table went on
/// reading and writing to the end, and the only thing the signal did was make
/// the caller wait longer for a file it had already asked to abandon.
async fn copy_rows(
    connection: &mut Conn,
    request: &ExportRequest,
    table: &str,
    writer: &mut AtomicWriter,
    signature: &mut Signature,
    token: &CancellationToken,
) -> Result<u64> {
    let quoted = ident::quote(table)?;
    let mut result = connection
        .query_iter(format!("SELECT * FROM {quoted}"))
        .await
        .or_failure()?;

    let columns = result.columns_ref().to_vec();
    let mut batcher = Batcher::new(writer, quoted, request.rows_per_statement);

    // Pulled one row at a time rather than through the driver's `for_each`,
    // which has no way to stop early. Nothing else about the reading changes:
    // one row is held at a time either way, and the batch is still what decides
    // when anything is written.
    while let Some(row) = result.next().await.or_failure()? {
        if token.is_cancelled() {
            return Err(Failure::interrupted(
                "interrupted.during_copy",
                format!("the copy of `{table}` was stopped while its rows were still arriving"),
            ));
        }
        batcher.push(&row, &columns, signature);
    }

    batcher.finish()
}

/// Gathers rows and writes them out in statements of a fixed size.
///
/// The reader this feeds may not fail, so a failure is held here instead and
/// every later row is skipped. Draining the rest is deliberate: leaving a
/// result set half-read on the connection makes the next statement fail for a
/// reason that has nothing to do with the real problem.
struct Batcher<'a> {
    writer: &'a mut AtomicWriter,
    quoted: String,
    per_statement: usize,
    pending: Vec<String>,
    count: u64,
    held: Option<Failure>,
}

impl<'a> Batcher<'a> {
    /// Starts gathering into the given writer.
    fn new(writer: &'a mut AtomicWriter, quoted: String, per_statement: usize) -> Self {
        let per_statement = per_statement.max(1);
        Self {
            writer,
            quoted,
            per_statement,
            pending: Vec::with_capacity(per_statement),
            count: 0,
            held: None,
        }
    }

    /// Takes one row, holding the first failure rather than reporting it.
    fn push(
        &mut self,
        row: &mysql_async::Row,
        columns: &[mysql_async::Column],
        signature: &mut Signature,
    ) {
        if self.held.is_some() {
            return;
        }
        if let Err(failure) = self.take(row, columns, signature) {
            self.held = Some(failure);
        }
    }

    /// Folds one row into the signature and writes a statement when full.
    fn take(
        &mut self,
        row: &mysql_async::Row,
        columns: &[mysql_async::Column],
        signature: &mut Signature,
    ) -> Result<()> {
        self.pending.push(render_row(row, columns, signature)?);
        self.count += 1;
        if self.pending.len() >= self.per_statement {
            self.flush()?;
        }
        Ok(())
    }

    /// Writes the rows held so far as one statement and starts a new one.
    fn flush(&mut self) -> Result<()> {
        if self.pending.is_empty() {
            return Ok(());
        }
        let statement = format!(
            "INSERT INTO {} VALUES {};\n",
            self.quoted,
            self.pending.join(", ")
        );
        self.pending.clear();
        self.writer.write(&statement)
    }

    /// Writes whatever is left and reports how many rows went out.
    ///
    /// # Errors
    ///
    /// Returns the failure held during the walk, or the one writing the last
    /// statement.
    fn finish(mut self) -> Result<u64> {
        if let Some(failure) = self.held.take() {
            return Err(failure);
        }
        self.flush()?;
        Ok(self.count)
    }
}

/// One row, both as a statement fragment and as a contribution to the signature.
///
/// Rows are rendered one at a time, in the order the server sent them, and that
/// is a requirement rather than a stage nobody got around to widening. The
/// signature is a running digest, so it reads the rows in order or it means
/// nothing; and the copy holds its memory flat however long the table is, which
/// spreading the work would undo by keeping finished rows around waiting for
/// their turn to be folded in. Both guarantees are published, and both would go
/// at once.
///
/// The value is borrowed rather than taken. A row arrives owning its cells, and
/// every one of them is only read here, so copying each cell to look at it
/// duplicated every large value in the table for the length of one iteration.
fn render_row(
    row: &mysql_async::Row,
    columns: &[mysql_async::Column],
    signature: &mut Signature,
) -> Result<String> {
    /// The value a column carries when the row holds nothing at that position.
    const ABSENT: Wire = Wire::NULL;

    let mut rendered = Row::new();
    let mut literals = Vec::with_capacity(columns.len());

    for (index, column) in columns.iter().enumerate() {
        let wire = row.as_ref(index).unwrap_or(&ABSENT);
        literals.push(super::literal::literal(wire, column));
        rendered.insert(
            column.name_str().into_owned(),
            signature_value(wire, column)?,
        );
    }

    signature.absorb(&rendered);
    Ok(format!("({})", literals.join(", ")))
}

/// The shape one value contributes to the signature of a copy.
///
/// It is a REQUIREMENT that no published display setting reaches here, not an
/// observation that none happens to. The signature identifies the rows that
/// were copied; if it moved because somebody changed how they like byte values
/// shown, then two copies of identical rows would carry different signatures
/// and nothing in the answer would say why. The whole point of a signature is
/// that it does not move when the thing it signs has not.
///
/// The copy itself is unaffected either way: the statement text comes from
/// [`literal`], which reads the wire value directly. This function feeds the
/// signature alone, which is precisely why the coupling is easy to miss and
/// worth naming.
fn signature_value(wire: &Wire, column: &mysql_async::Column) -> Result<serde_json::Value> {
    crate::types::convert(wire, column, &crate::types::Conversion::stable())
}

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

    /// The shaping the registry publishes, with one key stored.
    fn published_with(binary: &str) -> crate::types::Conversion {
        let scratch = tempfile::tempdir().expect("a scratch directory");
        let file =
            crate::config::paths::config_file(Some(scratch.path())).expect("a settings location");
        crate::config::store::store(&file, "output.binary", binary).expect("legal");
        let config = crate::config::Config::load(Some(scratch.path())).expect("the location loads");
        crate::settings::conversion(&config).expect("resolves")
    }

    /// A byte column, declared the way the server declares one.
    fn byte_column() -> mysql_async::Column {
        mysql_async::Column::new(mysql_async::consts::ColumnType::MYSQL_TYPE_BLOB)
            .with_character_set(crate::types::BINARY_CHARSET)
    }

    /// Changing how byte values are displayed must not change the signature of
    /// a copy, or two copies of identical rows would be signed differently and
    /// nothing in the answer would say why.
    ///
    /// The first half proves the risk is real rather than theoretical: the
    /// published shaping genuinely does move with the setting. The second half
    /// proves the signature path is out of its reach.
    #[test]
    fn the_signature_of_identical_rows_never_moves_with_a_display_setting() {
        let column = byte_column();
        let bytes = vec![7u8; 64];

        let described = crate::types::convert(
            &Wire::Bytes(bytes.clone()),
            &column,
            &published_with("summary"),
        )
        .expect("converts");
        let whole = crate::types::convert(
            &Wire::Bytes(bytes.clone()),
            &column,
            &published_with("full"),
        )
        .expect("converts");
        assert_ne!(
            described, whole,
            "the setting has to move the shaping, or this test proves nothing"
        );

        let signed_once = signature_value(&Wire::Bytes(bytes.clone()), &column).expect("converts");
        let signed_again = signature_value(&Wire::Bytes(bytes), &column).expect("converts");
        assert_eq!(signed_once, signed_again);
        assert_ne!(
            signed_once, whole,
            "the signature must not follow the setting into the whole form"
        );

        // And the digest itself, which is what a caller compares.
        let digest = |value: &serde_json::Value| {
            let mut row = Row::new();
            row.insert("payload".to_owned(), value.clone());
            let mut signature = Signature::new();
            signature.absorb(&row);
            signature.finish()
        };
        assert_eq!(
            digest(&signed_once),
            digest(&signed_again),
            "identical rows must sign identically whatever the setting says"
        );
    }

    /// A signature that does not move with the content is not a signature.
    ///
    /// The proof above holds one half of the promise, that the signature stays
    /// put when the rows have not changed. Held alone it is satisfied by the
    /// worst possible implementation: a signature that never moves at all would
    /// pass it every time. This is the other half, and the two are only worth
    /// anything together.
    ///
    /// The families here are the ones whose values reach the signature as a
    /// description rather than as themselves, which is where a constant can
    /// hide. A family whose description omits the content — carrying only the
    /// name of the declaration, say — signs every value of that column
    /// identically, and a copy that lost those values would be signed exactly
    /// like the copy that kept them. That is worse than the loss, because the
    /// signature is the one thing a caller has to notice it with.
    #[test]
    fn a_signature_moves_when_the_content_it_signs_moves() {
        use mysql_async::consts::ColumnType;

        let digest = |wire: &Wire, column: &mysql_async::Column| {
            let mut row = Row::new();
            row.insert(
                "payload".to_owned(),
                signature_value(wire, column).expect("converts"),
            );
            let mut signature = Signature::new();
            signature.absorb(&row);
            signature.finish()
        };

        let one = Wire::Bytes(vec![0x11u8; 64]);
        let other = Wire::Bytes(vec![0x22u8; 64]);

        for column in [
            byte_column(),
            mysql_async::Column::new(ColumnType::MYSQL_TYPE_VECTOR),
            mysql_async::Column::new(ColumnType::MYSQL_TYPE_GEOMETRY),
        ] {
            assert_ne!(
                digest(&one, &column),
                digest(&other, &column),
                "two different values signed the same, so the signature is blind to {:?}",
                column.column_type()
            );
        }
    }

    #[test]
    fn only_an_engine_that_keeps_versions_joins_the_agreement() {
        assert!(keeps_a_snapshot("InnoDB"));
        assert!(keeps_a_snapshot("innodb"));
        assert!(keeps_a_snapshot(" XtraDB "));
        assert!(!keeps_a_snapshot("MyISAM"));
        assert!(!keeps_a_snapshot("MEMORY"));
        assert!(!keeps_a_snapshot("ARCHIVE"));
        assert!(!keeps_a_snapshot(""));
    }

    #[test]
    fn a_table_outside_the_agreement_is_declared_rather_than_hidden() {
        let gap = snapshot_gap(&TableFacts {
            name: "sessions".to_owned(),
            engine: "MEMORY".to_owned(),
        });
        assert_eq!(gap.object, "sessions");
        assert_eq!(gap.cause, "no_consistent_snapshot");
        assert!(gap.detail.contains("MEMORY"));
    }

    #[test]
    fn the_header_puts_the_reader_in_a_known_state() {
        let opened = header();
        assert!(opened.contains("SET SQL_MODE"));
        assert!(opened.contains("FOREIGN_KEY_CHECKS = 0"));
        assert!(opened.contains("START TRANSACTION;"));
    }
}