Skip to main content

datafusion_common/
diagnostic.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::Span;
6
7/// Additional contextual information intended for end users, to help them
8/// understand what went wrong by providing human-readable messages, and
9/// locations in the source query that relate to the error in some way.
10///
11/// You can think of a single [`Diagnostic`] as a single "block" of output from
12/// rustc. i.e. either an error or a warning, optionally with some notes and
13/// help messages.
14///
15/// Example:
16///
17/// ```rust
18/// # use datafusion_common::{Location, Span, Diagnostic};
19/// let span = Some(Span {
20///     start: Location { line: 2, column: 1 },
21///     end: Location {
22///         line: 4,
23///         column: 15,
24///     },
25/// });
26/// let diagnostic = Diagnostic::new_error("Something went wrong", span)
27///     .with_help("Have you tried turning it on and off again?", None);
28/// ```
29#[derive(Debug, Clone)]
30pub struct Diagnostic {
31    pub kind: DiagnosticKind,
32    pub message: String,
33    pub span: Option<Span>,
34    pub notes: Vec<DiagnosticNote>,
35    pub helps: Vec<DiagnosticHelp>,
36}
37
38/// A note enriches a [`Diagnostic`] with extra information, possibly referring
39/// to different locations in the original SQL query, that helps contextualize
40/// the error and helps the end user understand why it occurred.
41///
42/// Example:
43/// SELECT id, name FROM users GROUP BY id
44/// Note:      ^^^^ 'name' is not in the GROUP BY clause
45#[derive(Debug, Clone)]
46pub struct DiagnosticNote {
47    pub message: String,
48    pub span: Option<Span>,
49}
50
51/// A "help" enriches a [`Diagnostic`] with extra information, possibly
52/// referring to different locations in the original SQL query, that helps the
53/// user understand how they might fix the error or warning.
54///
55/// Example:
56/// SELECT id, name FROM users GROUP BY id
57/// Help: Add 'name' here                 ^^^^
58#[derive(Debug, Clone)]
59pub struct DiagnosticHelp {
60    pub message: String,
61    pub span: Option<Span>,
62}
63
64/// A [`Diagnostic`] can either be a hard error that prevents the query from
65/// being planned and executed, or a warning that indicates potential issues,
66/// performance problems, or causes for unexpected results, but is non-fatal.
67/// This enum expresses these two possibilities.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum DiagnosticKind {
70    Error,
71    Warning,
72}
73
74impl Diagnostic {
75    /// Creates a new [`Diagnostic`] for a fatal error that prevents the SQL
76    /// query from being planned and executed. Optionally takes in a [`Span`] to
77    /// describe the location in the source code that caused the error, should
78    /// be provided when available.
79    pub fn new_error(message: impl Into<String>, span: Option<Span>) -> Self {
80        Self {
81            kind: DiagnosticKind::Error,
82            message: message.into(),
83            span,
84            notes: Vec::new(),
85            helps: Vec::new(),
86        }
87    }
88
89    /// Creates a new [`Diagnostic`] for a NON-fatal warning, such as a
90    /// performance problem, or possible cause for undesired results. Optionally
91    /// takes in a [`Span`] to describe the location in the source code that
92    /// caused the error, should be provided when available.
93    pub fn new_warning(message: impl Into<String>, span: Option<Span>) -> Self {
94        Self {
95            kind: DiagnosticKind::Warning,
96            message: message.into(),
97            span,
98            notes: Vec::new(),
99            helps: Vec::new(),
100        }
101    }
102
103    /// Adds a "note" to the [`Diagnostic`], which can have zero or many. A "note"
104    /// helps contextualize the error and helps the end user understand why it
105    /// occurred. It can refer to an arbitrary location in the SQL query, or to
106    /// no location.
107    pub fn add_note(&mut self, message: impl Into<String>, span: Option<Span>) {
108        self.notes.push(DiagnosticNote {
109            message: message.into(),
110            span,
111        });
112    }
113
114    /// Adds a "help" to the [`Diagnostic`], which can have zero or many. A
115    /// "help" helps the user understand how they might fix the error or
116    /// warning. It can refer to an arbitrary location in the SQL query, or to
117    /// no location.
118    pub fn add_help(&mut self, message: impl Into<String>, span: Option<Span>) {
119        self.helps.push(DiagnosticHelp {
120            message: message.into(),
121            span,
122        });
123    }
124
125    /// Like [`Diagnostic::add_note`], but returns `self` to allow chaining.
126    pub fn with_note(mut self, message: impl Into<String>, span: Option<Span>) -> Self {
127        self.add_note(message.into(), span);
128        self
129    }
130
131    /// Like [`Diagnostic::add_help`], but returns `self` to allow chaining.
132    pub fn with_help(mut self, message: impl Into<String>, span: Option<Span>) -> Self {
133        self.add_help(message.into(), span);
134        self
135    }
136}