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
//! Calling a stored routine.
//!
//! # The name is quoted and the values are bound
//!
//! A routine name is not a value and cannot travel as a bound parameter, so it
//! is pasted into the call. It goes through [`crate::sql::ident::quote`], the
//! one sanctioned way to do that, which refuses a name it cannot quote instead
//! of producing text that would change what the call means. Every argument
//! travels bound, so an argument can never become part of the call.
//!
//! # Why every result set is kept apart
//!
//! A routine may answer with several result sets, and folding them into one
//! loses which row came from which. Each set is therefore returned with its own
//! position and its own columns.
//!
//! On the prepared protocol this server also returns the final values of the
//! routine's output parameters, and it returns them as a result set of their
//! own after the last one the routine produced. They are labelled as such, so a
//! routine that answers only through its parameters still answers.

use super::prepare::Gated;
use super::read;
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::Row;
use crate::sql::ident;
use mysql_async::prelude::Queryable;
use mysql_async::prelude::*;
use mysql_async::Conn;
use serde_json::{json, Value};

/// One result set a routine produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResultSet {
    /// Its position among the sets, counted from one.
    pub index: usize,
    /// The columns the server declared for it, in order.
    pub columns: Vec<String>,
    /// Its rows, in the order the server sent them.
    pub rows: Vec<Row>,
}

impl ResultSet {
    /// The answer this set carries.
    #[must_use]
    pub fn as_value(&self) -> Value {
        json!({
            "set": self.index,
            "columns": self.columns,
            "rows": self.rows,
        })
    }
}

/// Builds the call to one routine.
///
/// # Errors
///
/// Returns a validation failure when the routine name, or the database holding
/// it, cannot be quoted safely.
pub fn build(routine: &str, database: Option<&str>, arguments: usize) -> Result<String> {
    let name = match database {
        Some(database) => ident::quote_qualified(&[database, routine])?,
        None => ident::quote(routine)?,
    };
    let markers = vec!["?"; arguments].join(", ");
    Ok(format!("CALL {name}({markers})"))
}

/// Runs a call and keeps every result set it produced apart from the others.
///
/// # Errors
///
/// Returns the mapped driver failure when the routine does not exist, when the
/// number of arguments does not match its signature, or when the channel is
/// lost.
pub async fn execute(
    conn: &mut Conn,
    gated: &Gated,
    conversion: &crate::types::Conversion,
) -> Result<Vec<ResultSet>> {
    let mut result = conn
        .exec_iter(gated.sql(), gated.params())
        .await
        .or_failure()?;

    let mut sets = Vec::new();
    while !result.is_empty() {
        let columns = result.columns_ref().to_vec();
        // One list for the whole set, used both by the rows and by the header
        // reported beside them, so the two can never disagree.
        let labels = read::column_names(&columns);
        let mut rows = Vec::new();
        while let Some(row) = result.next().await.or_failure()? {
            rows.push(read::convert_row(row, &columns, &labels, conversion)?);
        }
        // A set with no columns at all is the server acknowledging the call and
        // carries nothing for the caller, so it is not reported as an answer.
        if !columns.is_empty() {
            sets.push(ResultSet {
                index: sets.len() + 1,
                columns: labels,
                rows,
            });
        }
    }
    Ok(sets)
}

/// Refuses a text asked to be a routine name that is not one.
///
/// A caller who writes a whole statement where a name belongs would otherwise
/// have it quoted as a single strange name and rejected by the server with a
/// message about an object that does not exist, which hides the real mistake.
///
/// # Errors
///
/// Returns a usage failure naming what was expected.
pub fn refuse_statement_as_name(routine: &str) -> Result<()> {
    if !routine.contains(char::is_whitespace) && !routine.contains('(') {
        return Ok(());
    }
    Err(Failure::usage(
        "usage.not_a_routine_name",
        format!("`{routine}` is a statement, and this command takes the name of a routine"),
    )
    .with_detail("detail", routine)
    .with_hint("give the routine name alone, and its arguments with --param"))
}

/// The routine's own parameters, as the catalogue declares them.
const SIGNATURE: &str = "SELECT ORDINAL_POSITION, PARAMETER_NAME, PARAMETER_MODE \
     FROM information_schema.PARAMETERS \
     WHERE SPECIFIC_SCHEMA = COALESCE(:database, DATABASE()) \
       AND SPECIFIC_NAME = :routine AND ORDINAL_POSITION > 0 \
     ORDER BY ORDINAL_POSITION";

/// One declared parameter, with where it sits and which way it carries.
#[derive(Debug, Clone)]
pub struct Parameter {
    /// Its place in the call, counted from one.
    pub position: usize,
    /// The name the routine declares it under.
    pub name: String,
    /// Whether it carries in, out, or both.
    pub mode: String,
}

impl Parameter {
    /// Whether the routine writes a value back through this parameter.
    #[must_use]
    pub fn carries_out(&self) -> bool {
        let mode = self.mode.to_uppercase();
        mode == "OUT" || mode == "INOUT"
    }
}

/// Reads the parameters a routine declares.
///
/// Position zero is skipped: a function keeps its return value there, and a
/// return value is not a parameter anybody can name.
///
/// # Errors
///
/// Returns the mapped driver failure when the catalogue cannot be read.
pub async fn signature(
    conn: &mut Conn,
    database: Option<&str>,
    routine: &str,
) -> Result<Vec<Parameter>> {
    let rows: Vec<(u32, Option<String>, Option<String>)> = conn
        .exec(
            SIGNATURE,
            mysql_async::params! {
                "database" => database,
                "routine" => routine,
            },
        )
        .await
        .or_failure()?;

    Ok(rows
        .into_iter()
        .map(|(position, name, mode)| Parameter {
            position: position as usize,
            name: name.unwrap_or_default(),
            mode: mode.unwrap_or_default(),
        })
        .collect())
}

/// The call to build once the caller has named some parameters as output.
#[derive(Debug, Clone)]
pub struct Planned {
    /// The statement, with a session variable where each output sits.
    pub sql: String,
    /// The values still bound, in the order their markers appear.
    pub bound: Vec<String>,
    /// Each output, as the variable holding it and the name it answers under.
    pub outputs: Vec<(String, String)>,
}

/// Places a session variable at each named output and a marker at the rest.
///
/// # Why the caller's values fill only the other positions
///
/// An output parameter carries nothing in, so a value written for it would have
/// nowhere to go. The values therefore fill the positions that are not outputs,
/// in the order they were written, and the manual says so.
///
/// # Why the variable is numbered and not named
///
/// The name comes from the caller and a name pasted into a statement is the one
/// thing this module refuses to do. The position is the product's own number,
/// so the variable cannot be steered from outside.
///
/// # Errors
///
/// Returns a validation failure naming a parameter the routine does not declare
/// as an output, raised before anything is sent.
pub fn plan(
    routine: &str,
    database: Option<&str>,
    declared: &[Parameter],
    asked: &[String],
    values: &[String],
) -> Result<Planned> {
    let mut wanted = Vec::new();
    for name in asked {
        let found = declared
            .iter()
            .find(|parameter| parameter.name.eq_ignore_ascii_case(name) && parameter.carries_out());
        let Some(parameter) = found else {
            return Err(Failure::validation(
                "sql.unknown_out_parameter",
                format!("`{name}` is not an output parameter of this routine"),
            )
            .with_detail("detail", name.clone())
            .with_hint(
                "read the signature with `schema routines` and mark a parameter                  the routine declares as OUT or INOUT",
            ));
        };
        wanted.push(parameter.clone());
    }

    let name = match database {
        Some(database) => ident::quote_qualified(&[database, routine])?,
        None => ident::quote(routine)?,
    };
    let mut pieces = Vec::new();
    let mut outputs = Vec::new();
    for parameter in declared {
        match wanted.iter().find(|out| out.position == parameter.position) {
            Some(out) => {
                let variable = format!("@mariadb_cli_out_{}", out.position);
                pieces.push(variable.clone());
                outputs.push((variable, out.name.clone()));
            }
            None => pieces.push("?".to_owned()),
        }
    }

    Ok(Planned {
        sql: format!("CALL {name}({})", pieces.join(", ")),
        bound: values.to_vec(),
        outputs,
    })
}

/// Reads the values the routine wrote into the session variables.
///
/// Read in the same invocation because the variables live in the session, and
/// this product's session ends with the invocation.
///
/// # Errors
///
/// Returns the mapped driver failure when the reading cannot be made.
async fn collected(
    conn: &mut Conn,
    outputs: &[(String, String)],
    conversion: &crate::types::Conversion,
) -> Result<Row> {
    if outputs.is_empty() {
        return Ok(Row::new());
    }
    let projection = outputs
        .iter()
        .map(|(variable, name)| ident::quote(name).map(|alias| format!("{variable} AS {alias}")))
        .collect::<Result<Vec<_>>>()?
        .join(", ");

    let mut result = conn
        .exec_iter(format!("SELECT {projection}"), mysql_async::Params::Empty)
        .await
        .or_failure()?;
    let columns = result.columns_ref().to_vec();
    let Some(row) = result.next().await.or_failure()? else {
        return Ok(Row::new());
    };
    let labels = read::column_names(&columns);
    read::convert_row(row, &columns, &labels, conversion)
}

/// Which routine is being called, and with what.
///
/// The three parts of the call itself travel together rather than as three
/// parameters beside the four that describe the invocation it runs under. They
/// are one thing — the call — and separating them made the signature read as a
/// list rather than as two ideas.
#[derive(Debug, Clone, Copy)]
pub struct Call<'a> {
    /// The routine's own name, never a statement.
    pub routine: &'a str,
    /// The database holding it, when the session is not already on it.
    pub database: Option<&'a str>,
    /// The values bound to its parameters, in order.
    pub values: &'a [String],
    /// The parameters the caller wants the final value of.
    pub outputs: &'a [String],
}

/// Calls one routine, through the guards a call has to pass.
///
/// A routine may change data, and nothing outside it can say whether it does,
/// so a call is admitted as a change rather than assumed harmless.
///
/// # Errors
///
/// Returns a usage failure when a statement was given where a name belongs, the
/// refusal a change earns when it is not admitted, and the mapped driver
/// failure when the routine does not exist or its signature does not match.
pub async fn serve(
    call: Call<'_>,
    conn: &mut Conn,
    policy: &super::Policy,
    write_state: &mut super::WriteState,
    server_read_only: bool,
    conversion: &crate::types::Conversion,
) -> Result<Value> {
    refuse_statement_as_name(call.routine)?;
    policy.admit_change("query call")?;
    // A routine cannot be called halfway, so there is nothing to preview.
    policy.admit_simulation("query call")?;
    write_state.admit(server_read_only)?;

    if call.outputs.is_empty() {
        let request = build(call.routine, call.database, call.values.len())?;
        let gated = super::prepare::gate(&request, call.values, policy)?;
        let sets = execute(conn, &gated, conversion).await?;
        return Ok(as_value(call.routine, call.database, &sets, &Row::new()));
    }

    // The signature is read, and the naming refused, before anything is sent,
    // because a routine that ran and then had its output rejected has already
    // done whatever it does.
    let declared = signature(conn, call.database, call.routine).await?;
    let planned = plan(
        call.routine,
        call.database,
        &declared,
        call.outputs,
        call.values,
    )?;
    let gated = super::prepare::gate(&planned.sql, &planned.bound, policy)?;
    let sets = execute(conn, &gated, conversion).await?;
    let returned = collected(conn, &planned.outputs, conversion).await?;
    Ok(as_value(call.routine, call.database, &sets, &returned))
}

/// The answer a call carries.
#[must_use]
pub fn as_value(
    routine: &str,
    database: Option<&str>,
    sets: &[ResultSet],
    returned: &Row,
) -> Value {
    json!({
        // The database is declared because the routine name may carry one of
        // its own, and then it is not the database the session sits on. An
        // answer naming only the routine would leave the caller to assume the
        // database they named, which is the one that did not apply.
        "database": database,
        "routine": routine,
        "sets": sets.iter().map(ResultSet::as_value).collect::<Vec<_>>(),
        "set_count": sets.len(),
        "output_parameters": returned,
    })
}

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

    #[test]
    fn a_call_binds_one_marker_for_every_argument() {
        assert_eq!(
            build("recalcular", None, 0).expect("builds"),
            "CALL `recalcular`()"
        );
        assert_eq!(
            build("recalcular", None, 1).expect("builds"),
            "CALL `recalcular`(?)"
        );
        assert_eq!(
            build("recalcular", None, 3).expect("builds"),
            "CALL `recalcular`(?, ?, ?)"
        );
    }

    #[test]
    fn the_database_holding_the_routine_is_quoted_part_by_part() {
        assert_eq!(
            build("recalcular", Some("loja"), 1).expect("builds"),
            "CALL `loja`.`recalcular`(?)"
        );
    }

    /// A name cannot travel as a bound value, so the one thing that must hold
    /// is that it can never close its own quoting.
    #[test]
    fn a_routine_name_can_never_close_its_own_quoting() {
        let built = build("p`(); DROP TABLE users; -- ", None, 0).expect("quotes");
        assert_eq!(built, "CALL `p``(); DROP TABLE users; -- `()");
        assert_eq!(
            built.matches("``").count(),
            1,
            "the delimiter inside the name is doubled, not closed"
        );
    }

    #[test]
    fn a_name_that_cannot_be_quoted_is_refused_rather_than_pasted() {
        assert!(build("", None, 0).is_err());
        assert!(build("has\u{0}a control", None, 0).is_err());
    }

    #[test]
    fn a_whole_statement_where_a_name_belongs_is_refused_with_the_real_reason() {
        let failure = refuse_statement_as_name("CALL recalcular(1)").expect_err("must refuse");
        assert_eq!(failure.code(), "usage.not_a_routine_name");
        assert_eq!(failure.exit_number().code(), 2);
    }

    #[test]
    fn a_plain_routine_name_passes() {
        assert!(refuse_statement_as_name("recalcular").is_ok());
        assert!(refuse_statement_as_name("loja.recalcular").is_ok());
    }

    /// A routine answering with two sets must show two, or the caller cannot
    /// tell which row came from which.
    #[test]
    fn two_result_sets_reach_the_caller_as_two() {
        let sets = vec![
            ResultSet {
                index: 1,
                columns: vec!["a".to_owned()],
                rows: vec![Row::new()],
            },
            ResultSet {
                index: 2,
                columns: vec!["b".to_owned()],
                rows: Vec::new(),
            },
        ];
        let value = as_value("recalcular", Some("loja"), &sets, &Row::new());
        assert_eq!(
            value["database"], "loja",
            "the answer must say which database the routine ran in"
        );
        assert_eq!(value["set_count"], 2);
        assert_eq!(value["sets"][0]["set"], 1);
        assert_eq!(value["sets"][0]["columns"][0], "a");
        assert_eq!(value["sets"][1]["set"], 2);
        assert_eq!(value["sets"][1]["columns"][0], "b");
    }

    #[test]
    fn a_routine_that_answers_with_nothing_says_so_without_inventing_a_set() {
        let value = as_value("recalcular", None, &[], &Row::new());
        assert_eq!(value["set_count"], 0);
        assert_eq!(value["sets"].as_array().expect("array").len(), 0);
    }
}