Skip to main content

query/promql/
error.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::any::Any;
16use std::time::SystemTime;
17
18use common_error::ext::ErrorExt;
19use common_error::status_code::StatusCode;
20use common_macro::stack_trace_debug;
21use common_time::timestamp::TimeUnit;
22use datafusion::error::DataFusionError;
23use promql::error::Error as PromqlError;
24use promql_parser::parser::token::TokenType;
25use promql_parser::parser::{Expr as PromExpr, VectorMatchCardinality};
26use snafu::{Location, Snafu};
27
28#[derive(Snafu)]
29#[snafu(visibility(pub))]
30#[stack_trace_debug]
31pub enum Error {
32    #[snafu(display("Unsupported expr type: {}", name))]
33    UnsupportedExpr {
34        name: String,
35        #[snafu(implicit)]
36        location: Location,
37    },
38
39    #[snafu(display("Unsupported vector matches: {:?}", name))]
40    UnsupportedVectorMatch {
41        name: VectorMatchCardinality,
42        #[snafu(implicit)]
43        location: Location,
44    },
45
46    #[snafu(display("Unexpected token: {:?}", token))]
47    UnexpectedToken {
48        token: TokenType,
49        #[snafu(implicit)]
50        location: Location,
51    },
52
53    #[snafu(display("Internal error during building DataFusion plan"))]
54    DataFusionPlanning {
55        #[snafu(source)]
56        error: datafusion::error::DataFusionError,
57        #[snafu(implicit)]
58        location: Location,
59    },
60
61    #[snafu(display(
62        "duplicate native PromQL output column name(s): {names}; time index, value and tag columns must have distinct names"
63    ))]
64    DuplicateOutputColumns {
65        names: String,
66        #[snafu(implicit)]
67        location: Location,
68    },
69
70    #[snafu(display("Unexpected plan or expression: {}", desc))]
71    UnexpectedPlanExpr {
72        desc: String,
73        #[snafu(implicit)]
74        location: Location,
75    },
76
77    #[snafu(display("Unknown table type, downcast failed"))]
78    UnknownTable {
79        #[snafu(implicit)]
80        location: Location,
81    },
82
83    #[snafu(display("Cannot find time index column in table {}", table))]
84    TimeIndexNotFound {
85        table: String,
86        #[snafu(implicit)]
87        location: Location,
88    },
89
90    #[snafu(display("Cannot find value columns in table {}", table))]
91    ValueNotFound {
92        table: String,
93        #[snafu(implicit)]
94        location: Location,
95    },
96
97    #[snafu(display("Failed to create PromQL plan node"))]
98    PromqlPlanNode {
99        #[snafu(source)]
100        source: PromqlError,
101        #[snafu(implicit)]
102        location: Location,
103    },
104
105    #[snafu(display(
106        "Cannot accept multiple vector as function input, PromQL expr: {:?}",
107        expr,
108    ))]
109    MultipleVector {
110        expr: PromExpr,
111        #[snafu(implicit)]
112        location: Location,
113    },
114
115    #[snafu(display(
116        "Table (metric) name not found, this indicates a procedure error in PromQL planner"
117    ))]
118    TableNameNotFound {
119        #[snafu(implicit)]
120        location: Location,
121    },
122
123    #[snafu(display("General catalog error: "))]
124    Catalog {
125        #[snafu(implicit)]
126        location: Location,
127        source: catalog::error::Error,
128    },
129
130    #[snafu(display("Expect a range selector, but not found"))]
131    ExpectRangeSelector {
132        #[snafu(implicit)]
133        location: Location,
134    },
135
136    #[snafu(display("Zero range in range selector"))]
137    ZeroRangeSelector {
138        #[snafu(implicit)]
139        location: Location,
140    },
141
142    #[snafu(display("Subquery step must be positive"))]
143    ZeroSubqueryStep {
144        #[snafu(implicit)]
145        location: Location,
146    },
147
148    #[snafu(display(
149        "invalid expression type \"range vector\" for range query, must be Scalar or instant Vector"
150    ))]
151    RangeVectorInRangeQuery {
152        #[snafu(implicit)]
153        location: Location,
154    },
155
156    #[snafu(display(
157        "The end time must be greater than start time, start: {:?}, end: {:?}",
158        start,
159        end
160    ))]
161    InvalidTimeRange {
162        start: i64,
163        end: i64,
164        #[snafu(implicit)]
165        location: Location,
166    },
167
168    #[snafu(display(
169        "The subquery child window is outside the representable millisecond range: {}",
170        timestamp
171    ))]
172    SubqueryTimestampOutOfRange {
173        timestamp: String,
174        #[snafu(implicit)]
175        location: Location,
176    },
177
178    #[snafu(display("Cannot find column {col}"))]
179    ColumnNotFound {
180        col: String,
181        #[snafu(implicit)]
182        location: Location,
183    },
184
185    #[snafu(display("Found multiple metric matchers in selector"))]
186    MultipleMetricMatchers {
187        #[snafu(implicit)]
188        location: Location,
189    },
190
191    #[snafu(display("Expect a metric matcher, but not found"))]
192    NoMetricMatcher {
193        #[snafu(implicit)]
194        location: Location,
195    },
196
197    #[snafu(display("Invalid function argument for {}", fn_name))]
198    FunctionInvalidArgument {
199        fn_name: String,
200        #[snafu(implicit)]
201        location: Location,
202    },
203
204    #[snafu(display(
205        "Attempt to combine two tables with different column sets, left: {:?}, right: {:?}",
206        left,
207        right
208    ))]
209    CombineTableColumnMismatch {
210        left: Vec<String>,
211        right: Vec<String>,
212        #[snafu(implicit)]
213        location: Location,
214    },
215
216    #[snafu(display("Multi fields calculation is not supported in {}", operator))]
217    MultiFieldsNotSupported {
218        operator: String,
219        #[snafu(implicit)]
220        location: Location,
221    },
222
223    #[snafu(display("Matcher operator {matcher_op} is not supported for {matcher}"))]
224    UnsupportedMatcherOp {
225        matcher_op: String,
226        matcher: String,
227        #[snafu(implicit)]
228        location: Location,
229    },
230
231    #[snafu(display("Timestamp out of range for the `@` modifier: {}", timestamp))]
232    AtModifierTimestampOutOfRange {
233        timestamp: String,
234        #[snafu(implicit)]
235        location: Location,
236    },
237
238    #[snafu(display("Timestamp out of range: {} of {:?}", timestamp, unit))]
239    TimestampOutOfRange {
240        timestamp: i64,
241        unit: TimeUnit,
242        #[snafu(implicit)]
243        location: Location,
244    },
245
246    #[snafu(display("Time out of the representable millisecond range: {:?}", time))]
247    SystemTimeOutOfRange {
248        time: SystemTime,
249        #[snafu(implicit)]
250        location: Location,
251    },
252
253    #[snafu(display("Invalid regular expression in label_replace(): {}", regex))]
254    InvalidRegularExpression {
255        regex: String,
256        #[snafu(implicit)]
257        location: Location,
258    },
259
260    #[snafu(display("Invalid destination label name in label_replace(): {}", label_name))]
261    InvalidDestinationLabelName {
262        label_name: String,
263        #[snafu(implicit)]
264        location: Location,
265    },
266}
267
268impl ErrorExt for Error {
269    fn status_code(&self) -> StatusCode {
270        use Error::*;
271        match self {
272            TimeIndexNotFound { .. }
273            | ValueNotFound { .. }
274            | UnsupportedExpr { .. }
275            | UnexpectedToken { .. }
276            | MultipleVector { .. }
277            | ExpectRangeSelector { .. }
278            | ZeroRangeSelector { .. }
279            | RangeVectorInRangeQuery { .. }
280            | ZeroSubqueryStep { .. }
281            | InvalidTimeRange { .. }
282            | SubqueryTimestampOutOfRange { .. }
283            | ColumnNotFound { .. }
284            | FunctionInvalidArgument { .. }
285            | UnsupportedVectorMatch { .. }
286            | CombineTableColumnMismatch { .. }
287            | UnexpectedPlanExpr { .. }
288            | UnsupportedMatcherOp { .. }
289            | TimestampOutOfRange { .. }
290            | SystemTimeOutOfRange { .. }
291            | AtModifierTimestampOutOfRange { .. }
292            | InvalidRegularExpression { .. }
293            | InvalidDestinationLabelName { .. }
294            | DuplicateOutputColumns { .. } => StatusCode::InvalidArguments,
295
296            UnknownTable { .. } => StatusCode::Internal,
297
298            PromqlPlanNode { source, .. } => source.status_code(),
299
300            DataFusionPlanning { .. } => StatusCode::PlanQuery,
301
302            TableNameNotFound { .. } => StatusCode::TableNotFound,
303
304            MultipleMetricMatchers { .. } | NoMetricMatcher { .. } => StatusCode::InvalidSyntax,
305
306            MultiFieldsNotSupported { .. } => StatusCode::Unsupported,
307            Catalog { source, .. } => source.status_code(),
308        }
309    }
310
311    fn as_any(&self) -> &dyn Any {
312        self
313    }
314}
315
316pub type Result<T> = std::result::Result<T, Error>;
317
318impl From<Error> for DataFusionError {
319    fn from(err: Error) -> Self {
320        DataFusionError::External(Box::new(err))
321    }
322}