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
//! The single gateway every caller statement passes through.
//!
//! Nothing in this crate sends a caller's text to the server except through
//! this module, so the order of the defences exists in one place only and
//! cannot be reordered by accident at a call site.
//!
//! # The prepared protocol is the defence
//!
//! [`exec_rows`] and [`exec_drop`] call the driver's `exec_*` family, which
//! speaks the binary prepared protocol. The server manual requires the text of
//! a prepared statement to represent one single statement, so a text carrying
//! two commands is refused by the server itself. That refusal does not depend
//! on this tool reading the text correctly, which is what makes it the
//! structural defence rather than one more textual check.
//!
//! The driver's `query_*` family speaks the text protocol and hands the server
//! a text it is free to split. It is never used here. Swapping one for the
//! other would look like a harmless simplification and would remove the whole
//! defence, which is why the reason is written next to the code.
//!
//! # A value is never pasted into the text
//!
//! A caller value travels bound and never as text spliced into the statement.
//! Splicing is injection, whatever quoting is applied first. An object name
//! cannot travel as a parameter, and the one sanctioned way to put one into a
//! statement is [`crate::sql::ident::quote`].

use super::Policy;
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::Row;
use crate::sql::classify::Classification;
use crate::sql::guard::{admit, Admission};
use mysql_async::prelude::Queryable;
use mysql_async::{Conn, Params, Value as Wire};

/// The marker a bound value occupies in a statement.
const PARAMETER_MARKER: char = '?';

/// The kinds a declared parameter may be.
///
/// The list is closed: a kind absent from it does not exist, so a declaration
/// naming one is refused when it is written rather than when it is run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// Free text.
    Text,
    /// A whole number, which may be negative.
    Integer,
    /// A number with a fractional part.
    Decimal,
    /// A truth value.
    Boolean,
    /// A calendar date, written as year, month and day.
    Date,
}

impl Kind {
    /// The stable name a declaration writes.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Integer => "integer",
            Self::Decimal => "decimal",
            Self::Boolean => "boolean",
            Self::Date => "date",
        }
    }

    /// Reads a kind out of a declaration.
    ///
    /// # Errors
    ///
    /// Returns a usage failure naming every kind that exists.
    pub fn parse(text: &str) -> Result<Self> {
        match text.trim().to_ascii_lowercase().as_str() {
            "text" => Ok(Self::Text),
            "integer" => Ok(Self::Integer),
            "decimal" => Ok(Self::Decimal),
            "boolean" => Ok(Self::Boolean),
            "date" => Ok(Self::Date),
            other => Err(Failure::usage(
                "usage.unknown_parameter_kind",
                format!("`{other}` is not a kind a parameter may be"),
            )
            .with_detail("detail", other)
            .with_hint("one of: text, integer, decimal, boolean, date")),
        }
    }

    /// Whether one value belongs to this kind.
    #[must_use]
    pub fn accepts(self, value: &str) -> bool {
        match self {
            Self::Text => true,
            Self::Integer => value.parse::<i64>().is_ok(),
            Self::Decimal => value.parse::<f64>().is_ok(),
            Self::Boolean => matches!(
                value.to_ascii_lowercase().as_str(),
                "true" | "false" | "1" | "0"
            ),
            Self::Date => is_calendar_date(value),
        }
    }
}

/// Whether a text is a date written as year, month and day.
fn is_calendar_date(value: &str) -> bool {
    let parts: Vec<&str> = value.split('-').collect();
    let [year, month, day] = parts.as_slice() else {
        return false;
    };
    year.len() == 4
        && year.parse::<u16>().is_ok()
        && month.parse::<u8>().is_ok_and(|m| (1..=12).contains(&m))
        && day.parse::<u8>().is_ok_and(|d| (1..=31).contains(&d))
}

/// A statement that passed every defence and the values bound to it.
///
/// Holding the admission rather than only the classification keeps the syntax
/// tree available to the ceilings that need to read it, so nothing downstream
/// has to parse the text a second time.
#[derive(Debug)]
pub struct Gated {
    sql: String,
    admission: Admission,
    values: Vec<String>,
}

impl Gated {
    /// The exact text that will reach the server.
    #[must_use]
    pub fn sql(&self) -> &str {
        &self.sql
    }

    /// What the statement does.
    #[must_use]
    pub const fn classification(&self) -> Classification {
        self.admission.classification()
    }

    /// The recognised statement shape, such as `select` or `delete`.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        self.admission.analysis().kind()
    }

    /// The admission, with the syntax tree the defences were read from.
    #[must_use]
    pub const fn admission(&self) -> &Admission {
        &self.admission
    }

    /// The values bound to the markers, in the order they were given.
    #[must_use]
    pub fn values(&self) -> &[String] {
        &self.values
    }

    /// The bound values in the shape the driver sends them.
    #[must_use]
    pub fn params(&self) -> Params {
        bind(&self.values)
    }

    /// Replaces the text while keeping the admission that cleared it.
    ///
    /// Used where this tool appends its own row ceiling to a query it has
    /// already admitted. The appended clause is written by this tool and never
    /// by the caller, so re-admitting it would only re-prove what is known.
    #[must_use]
    pub fn with_sql(mut self, sql: String) -> Self {
        self.sql = sql;
        self
    }
}

/// Admits one caller statement, or says exactly why it is refused.
///
/// The order is the design and is fixed:
///
/// 1. The structural refusals run over the syntax tree and over the text with
///    comments and literals blanked, before anything is sent.
/// 2. The classification is read from that same tree. A shape the classifier
///    does not recognise is refused here and is never carried on as a read.
/// 3. The count of bound values is checked against the count of markers, so a
///    mismatch costs no connection.
///
/// The size of the send is measured before any of that, because it is the one
/// refusal whose absence is not a wrong answer but a lost connection: a command
/// past the destination's packet ceiling is not rejected by the server, it
/// makes the server close the channel, and the caller is then told the network
/// is unreachable about a command that never had a chance of arriving.
///
/// # Errors
///
/// Returns a limit failure when the send is larger than the destination
/// accepts. Returns a validation failure when the statement carries more than
/// one command, reaches the server's filesystem, or has an unrecognised shape.
/// Returns a usage failure when the number of values does not match the number
/// of markers.
pub fn gate(sql: &str, values: &[String], policy: &Policy) -> Result<Gated> {
    refuse_oversized_send(sql, values)?;

    let admission = admit(sql, policy.parse)?;
    // The classifier refuses an unrecognised shape inside `admit`, so reaching
    // this line already proves the statement was recognised. The assertion is
    // kept as an explicit statement of that dependency.
    debug_assert!(matches!(
        admission.classification(),
        Classification::Read
            | Classification::Change
            | Classification::Definition
            | Classification::Administration
    ));

    refuse_value_count_mismatch(admission.stripped().text(), values.len())?;

    Ok(Gated {
        sql: sql.to_owned(),
        admission,
        values: values.to_vec(),
    })
}

/// Refuses a send larger than the destination will accept in one piece.
///
/// The measurement is taken with the values counted in, because that is what
/// travels: the statement is one part of the send and every bound value is
/// another, and a caller writing many values at once reaches the ceiling with a
/// statement of two lines. Measuring the text alone would let exactly the send
/// this refusal exists for through.
///
/// A ceiling that was never settled means no server has been reached and no key
/// was written, so there is no send to measure and nothing is refused. Choosing
/// a number here instead would refuse a command no destination objected to.
///
/// # Errors
///
/// Returns a limit failure naming the size measured and the ceiling it passed.
fn refuse_oversized_send(sql: &str, values: &[String]) -> Result<()> {
    let Some(ceiling) = crate::conn::handshake::PacketCeiling::in_force() else {
        return Ok(());
    };
    let measured = measured_send(sql, values);
    if measured <= ceiling {
        return Ok(());
    }
    Err(Failure::limit(
        "limit.packet_size",
        format!("the command measures {measured} bytes and the destination accepts {ceiling}"),
    )
    .with_detail("detail", format!("{measured} > {ceiling}"))
    .with_hint("split the send into smaller commands, or raise conn.max_packet_bytes"))
}

/// The size of what this send puts on the channel, in bytes.
///
/// The statement and every value it carries are counted together, because the
/// ceiling applies to the send and not to either half of it.
fn measured_send(sql: &str, values: &[String]) -> usize {
    sql.len() + values.iter().map(String::len).sum::<usize>()
}

/// Refuses a statement whose markers and values do not match.
///
/// The markers are counted over the blanked text, so a marker that is really a
/// character inside a text literal is not counted and a legitimate statement is
/// not refused for it.
///
/// # Errors
///
/// Returns a usage failure naming both counts.
fn refuse_value_count_mismatch(stripped: &str, given: usize) -> Result<()> {
    let markers = stripped.chars().filter(|c| *c == PARAMETER_MARKER).count();
    if markers == given {
        return Ok(());
    }
    Err(Failure::usage(
        "usage.parameter_count",
        format!("the statement has {markers} value markers and {given} values were given"),
    )
    .with_detail("detail", format!("{markers} != {given}"))
    .with_hint("give exactly one --param for each marker, in order"))
}

/// Turns caller values into the shape the driver sends.
///
/// Every value is bound as text and the server converts it to the column's own
/// type. Deciding the type here would mean guessing, and a wrong guess changes
/// what the statement matches. Binding as text never changes the statement,
/// because a bound value is never part of the statement.
#[must_use]
pub fn bind(values: &[String]) -> Params {
    if values.is_empty() {
        return Params::Empty;
    }
    Params::Positional(
        values
            .iter()
            .map(|value| Wire::Bytes(value.clone().into_bytes()))
            .collect(),
    )
}

/// Writes the exact statement to the auxiliary channel, never the primary one.
///
/// The values are shown as markers rather than as themselves. A value may be a
/// credential, and a diagnostic that prints one has leaked it into every log
/// that captured the auxiliary channel.
pub fn echo(gated: &Gated) {
    tracing::debug!(
        statement = gated.sql(),
        values = gated.values().len(),
        classification = gated.classification().as_str(),
        "sending prepared statement; values are bound and never shown"
    );
}

/// Runs a prepared statement and collects the rows of its first result set.
///
/// # 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 exec_rows(
    conn: &mut Conn,
    sql: &str,
    params: Params,
    conversion: &crate::types::Conversion,
) -> Result<Vec<Row>> {
    // The prepared protocol: `exec_iter`, never `query_iter`. See the module
    // documentation for why this choice is the product's defence.
    let mut result = conn.exec_iter(sql, params).await.or_failure()?;

    let columns = result.columns_ref().to_vec();
    // Worked out once, outside the loop: they are the same for every row.
    let labels = crate::exec::read::column_names(&columns);
    let mut rows = Vec::new();
    while let Some(row) = result.next().await.or_failure()? {
        rows.push(crate::exec::read::convert_row(
            row, &columns, &labels, conversion,
        )?);
    }
    Ok(rows)
}

/// Runs a prepared statement that returns no rows.
///
/// # Errors
///
/// Returns the mapped driver failure when the server refuses the statement.
pub async fn exec_drop(conn: &mut Conn, sql: &str, params: Params) -> Result<()> {
    conn.exec_drop(sql, params).await.or_failure()
}

/// Reads one whole number out of a single-cell result.
///
/// # Errors
///
/// Returns the mapped driver failure, or a server failure when the answer did
/// not carry the single number it was asked for.
pub async fn exec_count(conn: &mut Conn, sql: &str, params: Params) -> Result<u64> {
    // Deliberately not routed through `exec_rows`. A count is a single number
    // and can never be a byte column, so it needs none of the shaping a row
    // does; asking for a conversion here would make every caller carry one for
    // a value it can have no effect on.
    let mut result = conn.exec_iter(sql, params).await.or_failure()?;
    let first = result.next().await.or_failure()?;
    // The rest of the answer is drained so the connection is left usable, which
    // matters because this runs before the work the caller actually asked for.
    result.drop_result().await.or_failure()?;

    first
        .and_then(|mut row| row.take::<Wire, _>(0))
        .and_then(|wire| counted(&wire))
        .ok_or_else(|| {
            Failure::server(
                "server.count_unreadable",
                "the derived count did not return a single number",
            )
        })
}

/// Reads a whole number out of a cell, whichever shape it arrived in.
///
/// Reads a count straight off the wire.
///
/// A count above the range a number can carry without losing a digit arrives as
/// text, by the published type map, so both shapes have to be accepted here.
fn counted(wire: &Wire) -> Option<u64> {
    match wire {
        Wire::UInt(number) => Some(*number),
        Wire::Int(number) => u64::try_from(*number).ok(),
        Wire::Bytes(bytes) => std::str::from_utf8(bytes).ok()?.trim().parse().ok(),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::globals::RowCountMode;
    use crate::sql::ParseLimits;
    use std::time::Duration;

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

    fn refusal(sql: &str, values: &[&str]) -> Failure {
        let owned: Vec<String> = values.iter().map(|v| (*v).to_owned()).collect();
        gate(sql, &owned, &policy()).expect_err("the statement must be refused")
    }

    fn admitted(sql: &str, values: &[&str]) -> Gated {
        let owned: Vec<String> = values.iter().map(|v| (*v).to_owned()).collect();
        gate(sql, &owned, &policy()).expect("the statement must be admitted")
    }

    /// A channel that keeps what was written to it, so a diagnostic can be read
    /// back by the test that provoked it.
    #[derive(Clone, Default)]
    struct Kept(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl Kept {
        /// Everything written so far, as text.
        fn text(&self) -> String {
            String::from_utf8(self.0.lock().expect("the channel is not poisoned").clone())
                .expect("the channel carries utf8")
        }
    }

    impl std::io::Write for Kept {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0
                .lock()
                .expect("the channel is not poisoned")
                .extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Kept {
        type Writer = Self;

        fn make_writer(&'a self) -> Self::Writer {
            self.clone()
        }
    }

    /// What the echo writes for one admitted statement.
    fn echoed(gated: &Gated) -> String {
        let kept = Kept::default();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(kept.clone())
            .with_max_level(tracing::Level::DEBUG)
            .with_ansi(false)
            .finish();
        tracing::subscriber::with_default(subscriber, || echo(gated));
        kept.text()
    }

    /// FR-098. The echo carries the exact text that reaches the server, and the
    /// values are named by their count alone.
    ///
    /// Both halves are one test because either one alone is worthless. An echo
    /// that named the values would leak whatever a caller bound — a password,
    /// a document number — into every log that captured the auxiliary channel,
    /// which is the leak FR-051 exists to forbid. An echo that hid the values
    /// but printed a statement other than the one that was sent would send
    /// whoever is investigating after the wrong text.
    ///
    /// The value below is one nothing else in the diagnostic could produce, so
    /// finding it anywhere in what was written is proof it travelled.
    #[test]
    fn the_echo_carries_the_exact_statement_and_never_a_value() {
        let secret = "senha-que-nunca-pode-aparecer";
        let gated = admitted("SELECT a FROM t WHERE b = ? AND c = ?", &[secret, "outro"]);

        let written = echoed(&gated);

        assert!(
            written.contains("SELECT a FROM t WHERE b = ? AND c = ?"),
            "the echo has to carry the statement that is sent: {written}"
        );
        assert_eq!(
            written.matches(secret).count(),
            0,
            "a bound value reached the auxiliary channel: {written}"
        );
        assert!(
            written.contains("values=2"),
            "the values are named by their count, and the count has to be right: {written}"
        );
        assert!(
            written.contains("classification=\"read\"") || written.contains("classification=read"),
            "the echo has to say what the statement does: {written}"
        );
    }

    /// The structural refusals run before anything else, so a text carrying two
    /// commands never reaches the count of markers, let alone the server.
    #[test]
    fn the_multiple_command_refusal_runs_before_every_other_layer() {
        let failure = refusal("SELECT ?; DELETE FROM users", &["a", "b"]);
        assert_eq!(failure.code(), "sql.multiple_statements");
    }

    #[test]
    fn a_reach_for_the_servers_filesystem_is_refused_before_the_marker_count() {
        let failure = refusal("SELECT LOAD_FILE('/etc/passwd')", &["extra"]);
        assert_eq!(failure.code(), "sql.server_file_read");
    }

    /// A shape the classifier does not recognise is refused, and is never let
    /// through as a read.
    #[test]
    fn an_unrecognised_shape_is_refused_and_never_treated_as_a_read() {
        let failure = refusal("SELECT FROM WHERE", &[]);
        assert!(
            matches!(failure.code(), "sql.unparsable" | "sql.unclassified"),
            "unexpected code {}",
            failure.code()
        );
        assert_eq!(failure.exit_number().code(), 3);
    }

    #[test]
    fn the_classification_travels_with_the_admitted_statement() {
        assert_eq!(
            admitted("SELECT a FROM t", &[]).classification(),
            Classification::Read
        );
        assert_eq!(
            admitted("DELETE FROM t WHERE a = ?", &["1"]).classification(),
            Classification::Change
        );
        assert_eq!(
            admitted("/* SELECT */ DELETE FROM users WHERE a = 1", &[]).classification(),
            Classification::Change,
            "a comment must not move the decision"
        );
    }

    #[test]
    fn too_few_values_are_refused_before_any_connection_is_opened() {
        let failure = refusal("SELECT a FROM t WHERE a = ? AND b = ?", &["one"]);
        assert_eq!(failure.code(), "usage.parameter_count");
        assert_eq!(failure.exit_number().code(), 2);
    }

    #[test]
    fn too_many_values_are_refused_as_well() {
        assert_eq!(
            refusal("SELECT a FROM t WHERE a = ?", &["one", "two"]).code(),
            "usage.parameter_count"
        );
    }

    /// A marker inside a text literal is not a marker, so counting it would
    /// refuse a legitimate statement.
    #[test]
    fn a_marker_inside_a_literal_is_not_counted() {
        assert_eq!(admitted("SELECT 'why?' AS note", &[]).values().len(), 0);
        assert_eq!(
            admitted("SELECT 'why?' FROM t WHERE a = ?", &["one"])
                .values()
                .len(),
            1
        );
    }

    /// The whole point of a bound value: whatever it contains, it stays a
    /// value and never becomes part of the statement.
    #[test]
    fn a_value_carrying_a_command_stays_a_value() {
        let gated = admitted(
            "SELECT * FROM clientes WHERE nome = ?",
            &["O'Brien'; DROP TABLE clientes; --"],
        );
        assert_eq!(
            gated.sql(),
            "SELECT * FROM clientes WHERE nome = ?",
            "the statement text is untouched by the value"
        );
        assert_eq!(gated.classification(), Classification::Read);
        match gated.params() {
            Params::Positional(values) => {
                assert_eq!(values.len(), 1);
                assert_eq!(
                    values[0],
                    Wire::Bytes(b"O'Brien'; DROP TABLE clientes; --".to_vec()),
                    "the value travels whole, as a value"
                );
            }
            other => panic!("values must be bound positionally, got {other:?}"),
        }
    }

    #[test]
    fn every_kind_accepts_what_it_names_and_refuses_what_it_does_not() {
        assert!(Kind::Integer.accepts("-42") && !Kind::Integer.accepts("4.2"));
        assert!(Kind::Decimal.accepts("4.2"));
        assert!(Kind::Boolean.accepts("TRUE") && Kind::Boolean.accepts("0"));
        assert!(!Kind::Boolean.accepts("maybe"));
        assert!(Kind::Date.accepts("2026-08-07"));
        assert!(
            !Kind::Date.accepts("2026-13-01"),
            "a thirteenth month is not one"
        );
        assert!(
            !Kind::Date.accepts("2026-01"),
            "an incomplete date is not one"
        );
        assert!(Kind::Text.accepts("anything at all; DROP TABLE t"));
    }

    /// FR-084. The size is measured with the values counted in, because that is
    /// what travels. Measuring the text alone would let a two-line statement
    /// carrying a hundred large values through, which is the send the ceiling
    /// exists for.
    #[test]
    fn the_send_is_measured_with_the_values_applied() {
        let statement = "INSERT INTO t (a, b) VALUES (?, ?)";
        let values = vec!["x".repeat(1000), "y".repeat(2000)];
        assert_eq!(
            measured_send(statement, &values),
            statement.len() + 3000,
            "the statement and every value it carries are one send"
        );
        assert_eq!(measured_send(statement, &[]), statement.len());
    }

    #[test]
    fn a_statement_without_values_binds_nothing() {
        assert_eq!(admitted("SELECT 1", &[]).params(), Params::Empty);
    }

    #[test]
    fn a_count_reads_a_number_in_either_published_shape() {
        assert_eq!(counted(&Wire::UInt(42)), Some(42));
        assert_eq!(counted(&Wire::Int(42)), Some(42));
        assert_eq!(
            counted(&Wire::Bytes(b"18446744073709551615".to_vec())),
            Some(u64::MAX),
            "a count above the safe range arrives as text"
        );
        assert_eq!(counted(&Wire::NULL), None);
        assert_eq!(counted(&Wire::Int(-1)), None, "a count is never negative");
    }

    #[test]
    fn appending_this_tools_own_clause_keeps_the_admission_that_cleared_it() {
        let gated = admitted("SELECT a FROM t", &[]);
        let widened = gated.with_sql("SELECT a FROM t\nLIMIT 10".to_owned());
        assert_eq!(widened.sql(), "SELECT a FROM t\nLIMIT 10");
        assert_eq!(widened.classification(), Classification::Read);
    }
}