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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! This module houses a pretty printer for the parts of a
//! [`DataflowDescription`] that are relevant to dataflow rendering.
//!
//! Format details:
//!
//!   * Sources that have [`LinearOperator`]s come first.
//!     The format is "Source <name> (<id>):" followed by the `predicates` of
//!     the [`LinearOperator`] and then the `projection`.
//!   * Intermediate views in the dataflow come next.
//!     The format is "View <name> (<id>):" followed by the output of
//!     [`expr::explain::ViewExplanation`].
//!   * Last is the view or query being explained. The format is "Query:"
//!     followed by the output of [`expr::explain::ViewExplanation`].
//!   * If there are no sources with some [`LinearOperator`] and no intermediate
//!     views, then the format is identical to the format of
//!     [`expr::explain::ViewExplanation`].
//!
//! It's important to avoid trailing whitespace everywhere, as plans may be
//! printed in contexts where trailing whitespace is unacceptable, like
//! sqllogictest files.

use std::fmt;

use crate::{DataflowDescription, LinearOperator};

use expr::explain::{Indices, ViewExplanation};
use expr::{ExprHumanizer, GlobalId, OptimizedMirRelationExpr, RowSetFinishing};
use ore::result::ResultExt;
use ore::str::{bracketed, separated};

pub trait ViewFormatter<ViewExpr> {
    fn fmt_source_body(&self, f: &mut fmt::Formatter, operator: &LinearOperator) -> fmt::Result;
    fn fmt_view(&self, f: &mut fmt::Formatter, view: &ViewExpr) -> fmt::Result;
}

/// An `Explanation` facilitates pretty-printing of the parts of a
/// [`DataflowDescription`] that are relevant to dataflow rendering.
///
/// By default, the [`fmt::Display`] implementation renders the expression as
/// described in the module docs. Additional information may be attached to the
/// explanation via the other public methods on the type.
#[derive(Debug)]
pub struct Explanation<'a, Formatter, ViewExpr>
where
    Formatter: ViewFormatter<ViewExpr>,
{
    /// Determines how sources and views are formatted
    formatter: &'a Formatter,
    expr_humanizer: &'a dyn ExprHumanizer,
    /// Each source that has some [`LinearOperator`].
    sources: Vec<(GlobalId, &'a LinearOperator)>,
    /// One `ViewExplanation` per view in the dataflow.
    views: Vec<(GlobalId, &'a ViewExpr)>,
    /// An optional `RowSetFinishing` to mention at the end.
    finishing: Option<RowSetFinishing>,
}

impl<'a, Formatter, ViewExpr> Explanation<'a, Formatter, ViewExpr>
where
    Formatter: ViewFormatter<ViewExpr>,
{
    pub fn new(
        expr: &'a ViewExpr,
        expr_humanizer: &'a dyn ExprHumanizer,
        formatter: &'a Formatter,
    ) -> Self {
        Self {
            formatter,
            expr_humanizer,
            sources: vec![],
            views: vec![(GlobalId::Explain, expr)],
            finishing: None,
        }
    }

    pub fn new_from_dataflow(
        dataflow: &'a DataflowDescription<ViewExpr>,
        expr_humanizer: &'a dyn ExprHumanizer,
        formatter: &'a Formatter,
    ) -> Self {
        let sources = dataflow
            .source_imports
            .iter()
            .filter_map(|(id, source)| {
                if let Some(operator) = &source.operators {
                    Some((*id, operator))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();
        let views = dataflow
            .objects_to_build
            .iter()
            .map(|build_desc| (build_desc.id, &build_desc.view))
            .collect::<Vec<_>>();
        Self {
            formatter,
            expr_humanizer,
            sources,
            views,
            finishing: None,
        }
    }

    /// Attach a `RowSetFinishing` to the explanation.
    pub fn explain_row_set_finishing(&mut self, finishing: RowSetFinishing) {
        self.finishing = Some(finishing);
    }
}

impl<'a, Formatter, ViewExpr> fmt::Display for Explanation<'a, Formatter, ViewExpr>
where
    Formatter: ViewFormatter<ViewExpr>,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (id, operator) in &self.sources {
            writeln!(
                f,
                "Source {} ({}):",
                self.expr_humanizer
                    .humanize_id(*id)
                    .unwrap_or_else(|| "?".to_owned()),
                id,
            )?;
            self.formatter.fmt_source_body(f, operator)?;
            writeln!(f)?;
        }
        for (view_num, (id, view)) in self.views.iter().enumerate() {
            if view_num > 0 {
                writeln!(f)?;
            }
            if self.sources.len() > 0 || self.views.len() > 1 {
                match id {
                    GlobalId::Explain => writeln!(f, "Query:")?,
                    _ => writeln!(
                        f,
                        "View {} ({}):",
                        self.expr_humanizer
                            .humanize_id(*id)
                            .unwrap_or_else(|| "?".to_owned()),
                        id
                    )?,
                }
            }
            self.formatter.fmt_view(f, view)?;
        }

        if let Some(finishing) = &self.finishing {
            writeln!(
                f,
                "\nFinish order_by={} limit={} offset={} project={}",
                bracketed("(", ")", separated(", ", &finishing.order_by)),
                match finishing.limit {
                    Some(limit) => limit.to_string(),
                    None => "none".to_owned(),
                },
                finishing.offset,
                bracketed("(", ")", Indices(&finishing.project))
            )?;
        }

        Ok(())
    }
}

pub struct JsonViewFormatter {}

impl<ViewExpr: serde::Serialize> ViewFormatter<ViewExpr> for JsonViewFormatter {
    fn fmt_source_body(&self, f: &mut fmt::Formatter, operator: &LinearOperator) -> fmt::Result {
        let operator_str = match serde_json::to_string_pretty(operator).map_err_to_string() {
            Ok(o) => o,
            Err(e) => e,
        };
        writeln!(f, "{}", operator_str)
    }

    fn fmt_view(&self, f: &mut fmt::Formatter, view: &ViewExpr) -> fmt::Result {
        let view_str = match serde_json::to_string_pretty(view).map_err_to_string() {
            Ok(o) => o,
            Err(e) => e,
        };
        writeln!(f, "{}", view_str)
    }
}

pub struct DataflowGraphFormatter<'a> {
    expr_humanizer: &'a dyn ExprHumanizer,
    typed: bool,
}

impl<'a> DataflowGraphFormatter<'a> {
    pub fn new(expr_humanizer: &'a dyn ExprHumanizer, typed: bool) -> Self {
        Self {
            expr_humanizer,
            typed,
        }
    }
}

impl<'a> ViewFormatter<OptimizedMirRelationExpr> for DataflowGraphFormatter<'a> {
    fn fmt_source_body(&self, f: &mut fmt::Formatter, operator: &LinearOperator) -> fmt::Result {
        if !operator.predicates.is_empty() {
            writeln!(
                f,
                "| Filter {}",
                separated(", ", operator.predicates.iter())
            )?;
        }
        writeln!(
            f,
            "| Project {}",
            bracketed("(", ")", Indices(&operator.projection))
        )
    }

    fn fmt_view(&self, f: &mut fmt::Formatter, view: &OptimizedMirRelationExpr) -> fmt::Result {
        let mut explain = ViewExplanation::new(view, self.expr_humanizer);
        if self.typed {
            explain.explain_types();
        }
        fmt::Display::fmt(&explain, f)
    }
}