mz_expr_parser/
command.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Handlers for testdriven test commands.
11
12use mz_repr::explain::ExplainConfig;
13
14use crate::{Def, TestCatalog, try_parse_def, try_parse_mir};
15
16pub fn handle_define(catalog: &mut TestCatalog, input: &str) -> String {
17    // Parse the relation, returning early on parse error.
18    let result = match try_parse_def(catalog, input) {
19        Ok(def) => match def {
20            Def::Source { name, cols, typ } => match catalog.insert(&name, cols, typ, true) {
21                Ok(id) => format!("Source defined as {id}"),
22                Err(err) => err,
23            },
24        },
25        Err(err) => err,
26    };
27    result + "\n"
28}
29
30pub fn handle_roundtrip(catalog: &TestCatalog, input: &str) -> String {
31    let output = match try_parse_mir(catalog, input) {
32        Ok(expr) => expr.explain(&ExplainConfig::default(), Some(catalog)),
33        Err(err) => return err,
34    };
35
36    if strip_comments(input).trim() == output.trim() {
37        "roundtrip OK\n".to_string()
38    } else {
39        format!(
40            "roundtrip produced a different output:\n~~~ expected:\n{}\n~~~ actual:\n{}\n~~~\n",
41            strip_comments(input),
42            output
43        )
44    }
45}
46
47fn strip_comments(s: &str) -> String {
48    let mut r = "".to_string();
49    for line in s.lines() {
50        let len = line.find("// {").unwrap_or(line.len());
51        r.push_str(line[0..len].trim_end());
52        r.push_str("\n");
53    }
54    r
55}