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
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
//! Statements that return rows.
//!
//! # A read never persists anything
//!
//! The session opens with automatic confirmation switched off, so anything a
//! read touched is discarded when the connection closes at the end of the
//! invocation. The guarantee therefore does not depend on the classification
//! being right: even a change that escaped the classifier and travelled here
//! would leave nothing behind. There is no flag that switches this off.
//!
//! # A row is never held longer than it takes to write it
//!
//! [`stream`] hands each row to the output flow and forgets it, so a million
//! rows cost the same memory as one and the caller sees the first row while the
//! server is still sending the last. The output operations run as stages of
//! that flow, so a ceiling, a filter, a projection or a deduplication no longer
//! costs the whole set being gathered first. The flow ends with the record that
//! declares it complete, and a connection that drops mid-way leaves the output
//! without that record, which is exactly how a cut set is told from a whole one.
//!
//! [`collect`] exists for the answer that travels inside a single envelope,
//! where the whole set is the payload by definition. It obeys the row ceiling,
//! and declares a gap when the ceiling cut the answer short.

use super::prepare::Gated;
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::envelope::Gap;
use crate::output::ops::Step;
use crate::output::stream::Stream;
use crate::output::Row;
use crate::sql::classify::Classification;
use crate::sql::{rewrite, ParseLimits};
use crate::types::{value::convert, Conversion};
use mysql_async::prelude::Queryable;
use mysql_async::{Column, Conn, Row as WireRow};
use std::io::Write;

/// The rows of one read, together with what the ceiling did to them.
#[derive(Debug, Default)]
pub struct ReadResult {
    /// The rows, in the order the server sent them.
    pub rows: Vec<Row>,
    /// The columns the server declared, in order.
    pub columns: Vec<String>,
    /// What the caller asked for and did not get, when the ceiling bit.
    pub gap: Option<Gap>,
}

/// Converts one wire row into the shape the output pipeline carries.
///
/// The column order the server declared is preserved, so two runs of the same
/// query produce the same bytes.
///
/// # Why the labels are handed in rather than worked out here
///
/// They are a function of the declared columns alone, so they are the same for
/// every row of one result. Working them out here read well and cost a `Vec`, a
/// `String` per column and two maps on every single row: a million rows of
/// twenty columns paid for twenty million strings to arrive at the same twenty
/// labels. The caller holds them across its loop instead, which is also what
/// the header is built from, so a row still cannot carry a key the announced
/// header does not name.
///
/// # Errors
///
/// Returns a limit failure when a byte value exceeds the ceiling for raw
/// content.
pub fn convert_row(
    row: WireRow,
    columns: &[Column],
    labels: &[String],
    conversion: &Conversion,
) -> Result<Row> {
    let mut converted = Row::with_capacity(columns.len());
    let mut wire = row;
    for ((index, column), label) in columns.iter().enumerate().zip(labels) {
        let value = wire.take(index).unwrap_or(mysql_async::Value::NULL);
        converted.insert(label.clone(), convert(&value, column, conversion)?);
    }
    Ok(converted)
}

/// The label a column with no declared name of its own falls back to.
///
/// A computed column written without a name still has to be addressable, and a
/// row keyed by the empty string is not.
const UNNAMED_COLUMN: &str = "column";

/// Separates a label from the position that was appended to keep it distinct.
const POSITION_MARK: char = '#';

/// The labels the declared columns are carried under, in order.
///
/// A row is an ordered map, so two columns sharing one label would collapse
/// into one and the second would be lost without a word. That is why a repeated
/// name is not carried as it arrived: it is qualified with the table the server
/// declared it under, which is the same convention the server uses to tell two
/// homonymous columns apart. A qualification that still repeats — the same table
/// joined to itself, or two unnamed computed columns — is settled by the
/// column's position, the one thing that is always distinct and always the same
/// between two runs of the same query.
///
/// Nothing outside the declared metadata is consulted, so the labels of a query
/// never change from one run to the next.
#[must_use]
pub fn column_names(columns: &[Column]) -> Vec<String> {
    let mut labels: Vec<String> = columns.iter().map(plain_label).collect();

    // Only the labels that actually clash are rewritten, so a query without
    // homonymous columns reads exactly as the server declared it.
    for index in repeated(&labels) {
        labels[index] = qualified_label(&columns[index]);
    }
    for index in repeated(&labels) {
        labels[index] = format!("{}{POSITION_MARK}{index}", labels[index]);
    }
    labels
}

/// The name the server declared, or the fallback when it declared none.
fn plain_label(column: &Column) -> String {
    let name = column.name_str();
    if name.is_empty() {
        return UNNAMED_COLUMN.to_owned();
    }
    name.into_owned()
}

/// The label qualified with the table, and the schema, the server declared.
///
/// Parts the server left empty are dropped rather than written as an empty
/// segment, because a leading dot would name a schema that does not exist.
fn qualified_label(column: &Column) -> String {
    let mut parts: Vec<String> = Vec::with_capacity(3);
    for part in [column.schema_str(), column.table_str()] {
        if !part.is_empty() {
            parts.push(part.into_owned());
        }
    }
    parts.push(plain_label(column));
    parts.join(".")
}

/// The positions of the labels that occur more than once.
fn repeated(labels: &[String]) -> Vec<usize> {
    let mut seen: std::collections::HashMap<&str, usize> =
        std::collections::HashMap::with_capacity(labels.len());
    for label in labels {
        *seen.entry(label.as_str()).or_insert(0) += 1;
    }
    labels
        .iter()
        .enumerate()
        .filter(|(_, label)| seen.get(label.as_str()).is_some_and(|count| *count > 1))
        .map(|(index, _)| index)
        .collect()
}

/// Imposes this tool's own row ceiling on a statement that returns rows.
///
/// A statement that is not a plain query carries no ceiling, because appending
/// one would change what it means. A query that already carries a ceiling of
/// its own is left as the caller wrote it.
///
/// The server is asked for one row more than the ceiling allows. That extra row
/// is never handed to the caller: it exists only so that a full answer can be
/// told apart from a cut one. Asking for exactly the ceiling would make every
/// cut answer indistinguishable from a complete one, and the answer would shrink
/// in silence.
///
/// # Errors
///
/// Returns a validation failure when the query ends in a clause a ceiling
/// cannot be appended after.
pub fn with_ceiling(gated: Gated, ceiling: usize, parse: ParseLimits) -> Result<Gated> {
    if gated.classification() != Classification::Read || gated.kind() != "select" {
        return Ok(gated);
    }
    let widened = rewrite::with_limit(gated.sql(), witness_limit(ceiling), None, parse)?;
    Ok(gated.with_sql(widened))
}

/// How many rows the server is asked for so that a cut answer announces itself.
///
/// The ceiling plus one, saturating, because a ceiling at the top of the range
/// must not wrap around into a tiny one.
fn witness_limit(ceiling: usize) -> usize {
    ceiling.saturating_add(1)
}

/// Runs a read and collects its rows, obeying the ceiling.
///
/// # Errors
///
/// Returns the mapped driver failure when the server refuses the statement or
/// the channel is lost, and a limit failure when a value exceeds its ceiling.
pub async fn collect(
    conn: &mut Conn,
    gated: &Gated,
    ceiling: usize,
    conversion: &Conversion,
) -> Result<ReadResult> {
    let mut result = conn
        .exec_iter(gated.sql(), gated.params())
        .await
        .or_failure()?;

    let columns = result.columns_ref().to_vec();
    // Worked out once for the whole result, because they depend on nothing the
    // rows carry. The header below is built from this same list.
    let labels = column_names(&columns);
    let mut under = UnderCeiling::new(ceiling);
    while let Some(row) = result.next().await.or_failure()? {
        under.take(|| convert_row(row, &columns, &labels, conversion))?;
    }

    Ok(ReadResult {
        columns: labels,
        gap: under.gap(),
        rows: under.rows,
    })
}

/// The rows a ceiling admits, and the memory that more had arrived.
#[derive(Debug)]
struct UnderCeiling {
    ceiling: usize,
    rows: Vec<Row>,
    overflowed: bool,
}

impl UnderCeiling {
    /// An empty answer that will admit at most `ceiling` rows.
    fn new(ceiling: usize) -> Self {
        Self {
            ceiling,
            rows: Vec::new(),
            overflowed: false,
        }
    }

    /// Offers one arriving row to the answer.
    ///
    /// A row past the ceiling is a witness and nothing else, so it is never
    /// produced: the caller's row is built only when there is room for it, which
    /// also keeps a discarded row from failing conversion.
    ///
    /// # Errors
    ///
    /// Returns whatever building the row failed with.
    fn take<F>(&mut self, produce: F) -> Result<()>
    where
        F: FnOnce() -> Result<Row>,
    {
        if self.rows.len() < self.ceiling {
            self.rows.push(produce()?);
        } else {
            self.overflowed = true;
        }
        Ok(())
    }

    /// The gap the ceiling left, when a witness proved it cut the answer.
    fn gap(&self) -> Option<Gap> {
        self.overflowed.then(|| ceiling_gap(self.ceiling))
    }
}

/// Refuses a projection that would keep no column of this answer.
///
/// # Errors
///
/// Returns a usage failure naming the fields asked for and the columns the
/// answer really carries, which is what a mistyped name needs to be corrected.
fn refuse_a_projection_that_keeps_nothing(
    pipeline: &crate::output::Pipeline,
    labels: &[String],
    shown: &[String],
) -> Result<()> {
    if pipeline.select.is_empty() || labels.is_empty() || !shown.is_empty() {
        return Ok(());
    }
    Err(Failure::usage(
        "usage.projection_kept_nothing",
        "no field named by the projection is carried by the answer",
    )
    .with_detail("asked", pipeline.select.join(","))
    .with_detail("available", labels.join(","))
    .with_hint("name a field the answer carries, or leave --select out"))
}

/// The gap a row ceiling leaves behind when it cuts an answer short.
///
/// A shrunken answer without a declared gap is a defect: the caller would read
/// a partial set as a whole one.
///
/// The witness row proves only that at least one row was left behind, so the
/// wording claims exactly that. Naming a count here would be inventing one.
fn ceiling_gap(ceiling: usize) -> Gap {
    Gap::new(
        "rows",
        "row_ceiling",
        format!(
            "the ceiling of {ceiling} rows was reached and at least one further row was not returned"
        ),
    )
}

/// Runs a read and writes each row straight onto the flow.
///
/// Nothing here holds a collection of rows: a row is shaped, written and
/// forgotten, so the memory cost does not grow with the size of the result set.
/// The output operations run as stages of that flow rather than over a gathered
/// payload, so asking for a ceiling, a filter or a projection costs no memory
/// either.
///
/// `sink` carries the channel, the shape and the tail the closing record
/// declares besides the count: the command that produced the set and the
/// destination it came from, which a flow has no envelope of its own to carry
/// (FR-143).
///
/// The closing record is written only when the flow reached its end with
/// everything it promised. A failure mid-way returns without it, and so does a
/// flow the volume ceiling cut short, which is how the caller tells a cut set
/// from a whole one.
///
/// # The row ceiling ends a flow without breaking it
///
/// `ceiling` is this tool's own ceiling on returned rows, and it is counted
/// over the rows ARRIVING from the server rather than over the rows leaving,
/// which is where the gathered path counts it too. Counting the ones leaving
/// would answer one request two different ways the moment a filter dropped
/// anything, because the gathered path cuts at the read and filters afterwards.
///
/// A flow the ceiling ended still closes with the record that declares it,
/// carrying the gap the ceiling left. The set ended because this tool decided
/// to end it, and a decision is not a loss: a flow cut by a dropped channel
/// still leaves the output with no closing record at all, and that difference
/// is the only thing a reader of the primary channel has to tell an interrupted
/// set from a complete one.
///
/// # Errors
///
/// Returns the mapped driver failure when the channel is lost, and a limit
/// failure when the reader closed the output channel.
pub async fn stream<W: Write>(
    conn: &mut Conn,
    gated: &Gated,
    sink: crate::output::stream::Sink<'_, W>,
    pipeline: &crate::output::Pipeline,
    conversion: &Conversion,
    ceiling: usize,
    token: &tokio_util::sync::CancellationToken,
) -> Result<u64> {
    let crate::output::stream::Sink {
        writer,
        formatter,
        tail,
    } = sink;
    let mut result = conn
        .exec_iter(gated.sql(), gated.params())
        .await
        .or_failure()?;

    let columns = result.columns_ref().to_vec();
    // The row labels and the header the reader sees are two different lists:
    // projection can drop a column from the header while the row still has to
    // be built whole before the pipeline decides. Both are worked out once
    // here, because a million rows would otherwise pay for the same answer a
    // million times.
    let labels = column_names(&columns);
    let shown = pipeline.columns_after_projection(&labels);
    // FR-034. Refused here, before a single row is pulled, because this is the
    // first place that knows both what was asked for and what the answer
    // carries.
    //
    // A field the answer does not carry is skipped rather than emitted as null,
    // and that is right for a caller naming five fields where four exist. When
    // NONE of them exist the same rule leaves one empty object per row, and
    // `row_count` still counts them — measured before this existed,
    // `--select naoexiste` over four rows answered
    // `{"columns":[],"rows":[{},{},{},{}],"row_count":4}` and ended in 0, so a
    // mistyped field name was handed back as a full result of nothing.
    refuse_a_projection_that_keeps_nothing(pipeline, &labels, &shown)?;
    // FR-039. The volume ceiling covers the frame this shape writes around the
    // rows, not the rows alone, so the frame is measured before the first row
    // is offered and charged against the ceiling here.
    let mut formatter = formatter;
    let mut stage = pipeline.flow_framed(
        &mut *formatter,
        tail,
        &shown,
        ceiling,
        &[ceiling_gap(ceiling)],
    )?;
    let mut flow = Stream::open(writer, formatter, tail, &shown)?;
    let mut arrived = 0usize;
    let mut cut = None;

    while let Some(row) = result.next().await.or_failure()? {
        // Asked once per row, which is the only place a flow can be stopped
        // from. This is the longest loop the product has and it used to be the
        // deafest: a million-row read carried on writing after the signal, all
        // the way to the last row, because nothing between the signal and here
        // ever looked. The check is a load of an atomic, which is nothing
        // beside converting and writing the row it guards.
        if token.is_cancelled() {
            return Err(crate::error::Failure::interrupted(
                "interrupted.during_flow",
                "the invocation was stopped while the rows were still arriving",
            ));
        }
        if arrived == ceiling {
            // This row is the witness the ceiling was widened by, and nothing
            // else. It is never converted and never written: it exists only so
            // that a cut answer can be told from one that ended on its own.
            cut = Some(ceiling_gap(ceiling));
            break;
        }
        arrived += 1;

        match stage.offer(convert_row(row, &columns, &labels, conversion)?) {
            Step::Emit(shaped) => flow.write(&shaped)?,
            Step::Skip => {}
            Step::Stop => {
                // Closed whether or not the set is whole. Leaving the channel
                // unterminated used to be how a cut set was marked, and the
                // mark is now the `output_truncated` field the `applied` block
                // already carries: the primary channel stays parseable, which
                // is the older and wider promise of the two.
                //
                // Closing here rather than gathering the rows first is what
                // keeps this a flow. Measured, on two hundred thousand rows
                // cut to two thousand bytes: flowing peaks at a quarter of
                // what gathering peaks at, and the answer is the same.
                return flow.finish(tail, &[], stage.applied().as_ref());
            }
        }
    }

    // Reaching this line is what makes the set whole, whether the server ran
    // out of rows or this tool's ceiling ended the pull, so this is the only
    // place the closing record is written.
    flow.finish(tail, cut.as_slice(), stage.applied().as_ref())
}

/// Runs a read under the ceiling and shapes the payload it answers with.
///
/// # Errors
///
/// Returns a validation failure when the ceiling cannot be imposed, and the
/// mapped driver failure when the server refuses the statement.
pub async fn serve(
    gated: Gated,
    conn: &mut Conn,
    parse: ParseLimits,
    ceiling: usize,
    conversion: &Conversion,
    passed_over: usize,
) -> Result<(serde_json::Value, Vec<Gap>)> {
    // The rows the resume mark passes over still have to arrive, because the
    // pipeline passes over them here rather than the server skipping them.
    // Without this a caller asking for the second page of ten would ask the
    // server for eleven rows and then discard all of them.
    let reach = ceiling.saturating_add(passed_over);

    // Both sides are given the same reach on purpose: the statement asks for
    // one row beyond it and the collection stops at it, so the extra row can
    // only ever be read as the witness that the answer was cut.
    let widened = with_ceiling(gated, reach, parse)?;
    let result = collect(conn, &widened, reach, conversion).await?;
    Ok((
        serde_json::json!({
            "columns": result.columns,
            "rows": result.rows,
            "row_count": result.rows.len(),
        }),
        result.gap.into_iter().collect(),
    ))
}

/// Builds the statement that returns the first rows of a table.
///
/// A table name is not a value and cannot be bound, so it goes through the one
/// sanctioned way of putting a name into a statement, which refuses a name it
/// cannot quote rather than producing text that means something else.
///
/// # Errors
///
/// Returns a limit failure when more rows are asked for than the ceiling
/// allows, and a validation failure when the name cannot be quoted.
pub fn sample_request(
    table: &str,
    database: Option<&str>,
    wanted: usize,
    ceiling: usize,
) -> Result<String> {
    if wanted > ceiling {
        return Err(Failure::limit(
            "limit.rows",
            format!("{wanted} rows were asked for and the ceiling is {ceiling}"),
        )
        .with_detail("detail", format!("{wanted} > {ceiling}"))
        .with_hint("ask for fewer rows, or raise output.max_rows"));
    }
    let name = match database {
        Some(database) => crate::sql::ident::quote_qualified(&[database, table])?,
        None => crate::sql::ident::quote(table)?,
    };
    Ok(format!("SELECT * FROM {name}"))
}

/// Refuses a statement asked to be read that does not read.
///
/// # Errors
///
/// Returns a validation failure naming what the statement actually does.
pub fn refuse_if_not_a_read(gated: &Gated) -> Result<()> {
    if gated.classification().is_read() {
        return Ok(());
    }
    Err(Failure::validation(
        "sql.not_a_read",
        format!(
            "this command only reads, and the statement is a {}",
            gated.classification().as_str()
        ),
    )
    .with_detail("detail", gated.classification().as_str())
    .with_hint("use `query run` for a statement that changes the server"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::globals::RowCountMode;
    use crate::exec::{prepare, Policy};
    use crate::output::format::ndjson::Ndjson;
    use crate::output::format::{END_OF_STREAM_KEY, ROW_COUNT_KEY};
    use serde_json::json;
    use std::time::Duration;

    /// The tail a flow closes with, carrying no destination.
    ///
    /// These proofs measure the closing record itself, so nothing about a
    /// destination is invented here.
    fn tail() -> crate::output::Envelope {
        crate::output::Envelope::new("query run", json!({}))
    }

    fn policy() -> Policy {
        Policy::new(
            ParseLimits::default(),
            100,
            50,
            RowCountMode::Changed,
            ";".to_owned(),
            Duration::from_secs(30),
        )
    }

    fn gated(sql: &str) -> Gated {
        prepare::gate(sql, &[], &policy()).expect("admitted")
    }

    fn row(index: u64) -> Row {
        let mut row = Row::new();
        row.insert("id".to_owned(), json!(index));
        row
    }

    /// Drives the ceiling exactly as [`collect`] does, with rows that need no
    /// server behind them.
    fn arriving(ceiling: usize, rows: u64) -> UnderCeiling {
        let mut under = UnderCeiling::new(ceiling);
        for index in 0..rows {
            under.take(|| Ok(row(index))).expect("a row is built");
        }
        under
    }

    /// The statement asks for one row more than the ceiling allows, because
    /// that extra row is the only thing that tells a full answer from a cut
    /// one. It is a witness, never a result: the caller still gets five.
    #[test]
    fn a_query_receives_this_tools_ceiling_plus_the_witness_row() {
        let widened = with_ceiling(gated("SELECT a FROM t"), 5, ParseLimits::default())
            .expect("a query accepts a ceiling");
        assert_eq!(widened.sql(), "SELECT a FROM t\nLIMIT 6");
    }

    /// A ceiling at the top of the range must not wrap around into a tiny one.
    #[test]
    fn a_ceiling_at_the_top_of_the_range_does_not_wrap_around() {
        assert_eq!(witness_limit(usize::MAX), usize::MAX);
    }

    /// An answer that ends exactly at the ceiling was not cut, so declaring a
    /// gap there would send the caller looking for rows that do not exist.
    #[test]
    fn an_answer_that_fills_the_ceiling_exactly_declares_no_gap() {
        let under = arriving(3, 3);
        assert_eq!(under.rows.len(), 3);
        assert!(under.gap().is_none());
    }

    #[test]
    fn the_witness_row_declares_the_gap_and_is_not_returned() {
        let under = arriving(3, 4);
        assert_eq!(under.rows.len(), 3, "the caller gets the ceiling, no more");
        let gap = under.gap().expect("a cut answer declares its gap");
        assert_eq!(gap.object, "rows");
        assert_eq!(gap.cause, "row_ceiling");
    }

    /// The witness must never reach the caller as data, or the ceiling would be
    /// exceeded by the very row that reports it.
    #[test]
    fn the_witness_row_never_appears_among_the_returned_rows() {
        let under = arriving(3, 4);
        let returned: Vec<_> = under.rows.iter().map(|row| row["id"].clone()).collect();
        assert_eq!(returned, vec![json!(0), json!(1), json!(2)]);
    }

    /// A statement that is not a plain query must not be rewritten, because a
    /// clause appended to it would change what it means.
    #[test]
    fn a_statement_that_is_not_a_query_is_left_exactly_as_written() {
        for sql in ["SHOW TABLES", "DESCRIBE t"] {
            let untouched =
                with_ceiling(gated(sql), 5, ParseLimits::default()).expect("left as written");
            assert_eq!(untouched.sql(), sql, "input {sql:?}");
        }
    }

    #[test]
    fn a_statement_that_changes_the_server_is_refused_by_a_read_command() {
        let failure = refuse_if_not_a_read(&gated("DELETE FROM t WHERE a = 1"))
            .expect_err("a change is not a read");
        assert_eq!(failure.code(), "sql.not_a_read");
        assert!(failure.message().contains("change"));
    }

    #[test]
    fn a_read_passes_the_read_only_refusal() {
        assert!(refuse_if_not_a_read(&gated("SELECT 1")).is_ok());
    }

    /// The witness proves only that something was left behind, so the wording
    /// must name the ceiling and stop there rather than invent a count.
    #[test]
    fn a_ceiling_that_cuts_the_answer_declares_the_gap_it_left() {
        let gap = ceiling_gap(10);
        assert_eq!(gap.object, "rows");
        assert_eq!(gap.cause, "row_ceiling");
        assert!(gap.detail.contains("10"), "the ceiling is named");
        assert!(
            gap.detail.contains("at least one"),
            "no count is invented: {}",
            gap.detail
        );
    }

    /// The closing record is the only mark that separates a whole set from a
    /// cut one, so a completed flow must always carry it.
    #[test]
    fn a_completed_flow_ends_with_the_record_that_declares_it_whole() {
        let mut out = Vec::new();
        let mut flow =
            Stream::open(&mut out, Box::new(Ndjson), &tail(), &["id".to_owned()]).expect("opens");
        for index in 0..3 {
            flow.write(&row(index)).expect("writes");
        }
        assert_eq!(flow.finish(&tail(), &[], None).expect("closes"), 3);

        let text = String::from_utf8(out).expect("utf8");
        let last = text.lines().next_back().expect("a last line");
        let parsed: serde_json::Value = serde_json::from_str(last).expect("parses");
        assert_eq!(parsed[END_OF_STREAM_KEY], true);
        assert_eq!(parsed[ROW_COUNT_KEY], 3);
    }

    /// A connection lost mid-flow leaves the output without the closing record,
    /// which is what the caller reads as "this set is not whole".
    #[test]
    fn a_flow_abandoned_mid_way_carries_no_closing_record() {
        let mut out = Vec::new();
        {
            let mut flow = Stream::open(&mut out, Box::new(Ndjson), &tail(), &["id".to_owned()])
                .expect("opens");
            flow.write(&row(0)).expect("writes");
            // The connection dropped here: `finish` is never reached.
        }
        let text = String::from_utf8(out).expect("utf8");
        assert!(
            !text.contains(END_OF_STREAM_KEY),
            "a cut set must never look whole: {text}"
        );
    }

    /// Builds one declared column the way the server would announce it.
    fn declared(schema: &str, table: &str, name: &str) -> Column {
        Column::new(mysql_async::consts::ColumnType::MYSQL_TYPE_LONG)
            .with_schema(schema.as_bytes())
            .with_table(table.as_bytes())
            .with_name(name.as_bytes())
    }

    /// FR-102: a join of two tables that both declare `id` must return both
    /// columns. Carrying them under one label would drop the second one, and
    /// losing a column without a word is exactly the defect the requirement
    /// forbids.
    #[test]
    fn fr_102_two_homonymous_columns_keep_two_distinct_labels() {
        let labels = column_names(&[
            declared("loja", "pedidos", "id"),
            declared("loja", "clientes", "id"),
        ]);
        assert_eq!(labels, vec!["loja.pedidos.id", "loja.clientes.id"]);
    }

    /// FR-102: a name that repeats nowhere is carried exactly as the server
    /// declared it, so qualifying only happens where it is needed.
    #[test]
    fn fr_102_a_name_that_repeats_nowhere_is_left_as_declared() {
        let labels = column_names(&[
            declared("loja", "pedidos", "total"),
            declared("loja", "clientes", "nome"),
        ]);
        assert_eq!(labels, vec!["total", "nome"]);
    }

    /// FR-102: the same table joined to itself declares the same schema, table
    /// and name twice, so qualification alone still collapses. The position is
    /// the only thing left that is both distinct and stable.
    #[test]
    fn fr_102_a_self_join_falls_back_to_the_declared_position() {
        let labels = column_names(&[
            declared("loja", "pedidos", "id"),
            declared("loja", "pedidos", "id"),
        ]);
        assert_eq!(labels, vec!["loja.pedidos.id#0", "loja.pedidos.id#1"]);
    }

    /// FR-102: a computed column written without a name declares no name at
    /// all, and a row keyed by the empty string cannot be addressed.
    #[test]
    fn fr_102_a_column_with_no_declared_name_still_gets_one() {
        let labels = column_names(&[declared("", "", ""), declared("", "", "")]);
        assert_eq!(labels, vec!["column#0", "column#1"]);
    }

    /// FR-102 with FR-064: the labels are read from the declared metadata and
    /// nothing else, so two runs of the same query agree.
    #[test]
    fn fr_102_the_labels_are_the_same_on_every_run() {
        let columns = [
            declared("loja", "pedidos", "id"),
            declared("loja", "clientes", "id"),
            declared("", "", ""),
        ];
        assert_eq!(column_names(&columns), column_names(&columns));
    }

    /// FR-102: a label produced by qualifying must not collide with a label
    /// another column already carried as declared, or the collapse would come
    /// back through the repair itself.
    #[test]
    fn fr_102_a_qualified_label_that_meets_a_plain_one_is_still_separated() {
        let labels = column_names(&[
            declared("", "pedidos", "id"),
            declared("", "clientes", "id"),
            declared("", "", "pedidos.id"),
        ]);
        assert_eq!(
            labels,
            vec!["pedidos.id#0", "clientes.id", "pedidos.id#2"],
            "no two columns may share a label"
        );
    }

    /// The flow must not grow its memory with the number of rows, or a large
    /// result set would cost as much as holding it all.
    #[test]
    fn a_long_flow_does_not_grow_its_buffer_row_by_row() {
        let mut out = Vec::new();
        let mut flow =
            Stream::open(&mut out, Box::new(Ndjson), &tail(), &["id".to_owned()]).expect("opens");
        let before = flow.buffer_capacity();
        for index in 0..20_000 {
            flow.write(&row(index)).expect("writes");
        }
        assert_eq!(flow.buffer_capacity(), before);
        assert_eq!(flow.finish(&tail(), &[], None).expect("closes"), 20_000);
    }
}