Skip to main content

operator/
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::sync::Arc;
17
18use common_datasource::file_format::Format;
19use common_error::define_into_tonic_status;
20use common_error::ext::{BoxedError, ErrorExt, RetryHint};
21use common_error::status_code::StatusCode;
22use common_macro::stack_trace_debug;
23use common_query::error::Error as QueryResult;
24use datafusion::parquet;
25use datafusion_common::DataFusionError;
26use datatypes::arrow::error::ArrowError;
27use object_store::error::retry_hint_from_opendal_error;
28use snafu::{Location, Snafu};
29use table::metadata::TableType;
30
31#[derive(Snafu)]
32#[snafu(visibility(pub))]
33#[stack_trace_debug]
34pub enum Error {
35    #[snafu(display("Table already exists: `{}`", table))]
36    TableAlreadyExists {
37        table: String,
38        #[snafu(implicit)]
39        location: Location,
40    },
41
42    #[snafu(display("Failed to cast result: `{}`", source))]
43    Cast {
44        #[snafu(source)]
45        source: QueryResult,
46        #[snafu(implicit)]
47        location: Location,
48    },
49
50    #[snafu(display("View already exists: `{name}`"))]
51    ViewAlreadyExists {
52        name: String,
53        #[snafu(implicit)]
54        location: Location,
55    },
56
57    #[snafu(display("Failed to build admin function args: {msg}"))]
58    BuildAdminFunctionArgs { msg: String },
59
60    #[snafu(display("Failed to execute admin function {msg}"))]
61    ExecuteAdminFunction {
62        msg: String,
63        #[snafu(source)]
64        error: DataFusionError,
65        #[snafu(implicit)]
66        location: Location,
67    },
68
69    #[snafu(display("Admin function execution was cancelled"))]
70    AdminFunctionCancelled,
71
72    #[snafu(display("Expected {expected} args, but actual {actual}"))]
73    FunctionArityMismatch { expected: usize, actual: usize },
74
75    #[snafu(display("Failed to invalidate table cache"))]
76    InvalidateTableCache {
77        #[snafu(implicit)]
78        location: Location,
79        source: common_meta::error::Error,
80    },
81
82    #[snafu(display("Failed to execute ddl"))]
83    ExecuteDdl {
84        #[snafu(implicit)]
85        location: Location,
86        source: common_meta::error::Error,
87    },
88
89    #[snafu(display("Invalid database export: {reason}"))]
90    InvalidDatabaseExport { reason: String },
91
92    #[snafu(display("Database export cancelled"))]
93    DatabaseExportCancelled {},
94
95    #[snafu(display("Invalid logical table export: {reason}"))]
96    InvalidLogicalTableExport { reason: String },
97
98    #[snafu(display("Logical table export resource limit exceeded: {reason}"))]
99    LogicalTableExportResource { reason: String },
100
101    #[snafu(display("Logical table export cancelled"))]
102    LogicalTableExportCancelled {},
103
104    #[snafu(display("Unexpected, violated: {}", violated))]
105    Unexpected {
106        violated: String,
107        #[snafu(implicit)]
108        location: Location,
109    },
110
111    #[snafu(display("Failed to flush pending batch: {source}"))]
112    BatchFlush {
113        source: Arc<Error>,
114        #[snafu(implicit)]
115        location: Location,
116    },
117
118    #[snafu(display("external error"))]
119    External {
120        #[snafu(implicit)]
121        location: Location,
122        source: BoxedError,
123    },
124
125    #[snafu(display("Failed to insert data"))]
126    RequestInserts {
127        #[snafu(implicit)]
128        location: Location,
129        source: common_meta::error::Error,
130    },
131
132    #[snafu(display("Failed to delete data"))]
133    RequestDeletes {
134        #[snafu(implicit)]
135        location: Location,
136        source: common_meta::error::Error,
137    },
138
139    #[snafu(display("Failed to send request to region"))]
140    RequestRegion {
141        #[snafu(implicit)]
142        location: Location,
143        source: common_meta::error::Error,
144    },
145
146    #[snafu(display("Unsupported region request"))]
147    UnsupportedRegionRequest {
148        #[snafu(implicit)]
149        location: Location,
150    },
151
152    #[snafu(display("Failed to parse SQL"))]
153    ParseSql {
154        #[snafu(implicit)]
155        location: Location,
156        source: sql::error::Error,
157    },
158
159    #[snafu(display("Failed to convert identifier: {}", ident))]
160    ConvertIdentifier {
161        ident: String,
162        #[snafu(implicit)]
163        location: Location,
164        #[snafu(source)]
165        error: datafusion::error::DataFusionError,
166    },
167
168    #[snafu(display("Failed to extract table names"))]
169    ExtractTableNames {
170        #[snafu(implicit)]
171        location: Location,
172        source: query::error::Error,
173    },
174
175    #[snafu(display("Column datatype error"))]
176    ColumnDataType {
177        #[snafu(implicit)]
178        location: Location,
179        source: api::error::Error,
180    },
181
182    #[snafu(display("Invalid column proto definition, column: {}", column))]
183    InvalidColumnDef {
184        column: String,
185        #[snafu(implicit)]
186        location: Location,
187        source: api::error::Error,
188    },
189
190    #[snafu(display("Invalid statement to create view"))]
191    InvalidViewStmt {
192        #[snafu(implicit)]
193        location: Location,
194    },
195
196    #[snafu(display("Expect {expected} columns for view {view_name}, but found {actual}"))]
197    ViewColumnsMismatch {
198        view_name: String,
199        expected: usize,
200        actual: usize,
201    },
202
203    #[snafu(display("Invalid view \"{view_name}\": {msg}"))]
204    InvalidView {
205        msg: String,
206        view_name: String,
207        #[snafu(implicit)]
208        location: Location,
209    },
210
211    #[snafu(display("Failed to convert column default constraint, column: {}", column_name))]
212    ConvertColumnDefaultConstraint {
213        column_name: String,
214        #[snafu(implicit)]
215        location: Location,
216        source: datatypes::error::Error,
217    },
218
219    #[snafu(display("Failed to convert datafusion schema"))]
220    ConvertSchema {
221        source: datatypes::error::Error,
222        #[snafu(implicit)]
223        location: Location,
224    },
225
226    #[snafu(display("Failed to convert expr to struct"))]
227    InvalidExpr {
228        #[snafu(implicit)]
229        location: Location,
230        source: common_meta::error::Error,
231    },
232
233    #[snafu(display("Invalid partition"))]
234    InvalidPartition {
235        #[snafu(implicit)]
236        location: Location,
237        source: partition::error::Error,
238    },
239
240    #[snafu(display("Invalid SQL, error: {}", err_msg))]
241    InvalidSql {
242        err_msg: String,
243        #[snafu(implicit)]
244        location: Location,
245    },
246
247    #[snafu(display("Invalid InsertRequest, reason: {}", reason))]
248    InvalidInsertRequest {
249        reason: String,
250        #[snafu(implicit)]
251        location: Location,
252    },
253
254    #[snafu(display("Invalid DeleteRequest, reason: {}", reason))]
255    InvalidDeleteRequest {
256        reason: String,
257        #[snafu(implicit)]
258        location: Location,
259    },
260
261    #[snafu(display("Table not found: {}", table_name))]
262    TableNotFound { table_name: String },
263
264    #[snafu(display("Admin function not found: {}", name))]
265    AdminFunctionNotFound { name: String },
266
267    #[snafu(display("Flow not found: {}", flow_name))]
268    FlowNotFound { flow_name: String },
269
270    #[snafu(display("Failed to join task"))]
271    JoinTask {
272        #[snafu(source)]
273        error: common_runtime::JoinError,
274        #[snafu(implicit)]
275        location: Location,
276    },
277
278    #[snafu(display("General catalog error"))]
279    Catalog {
280        #[snafu(implicit)]
281        location: Location,
282        source: catalog::error::Error,
283    },
284
285    #[snafu(display("Failed to find view info for: {}", view_name))]
286    FindViewInfo {
287        view_name: String,
288        #[snafu(implicit)]
289        location: Location,
290        source: common_meta::error::Error,
291    },
292
293    #[snafu(display("View info not found: {}", view_name))]
294    ViewInfoNotFound {
295        view_name: String,
296        #[snafu(implicit)]
297        location: Location,
298    },
299
300    #[snafu(display("View not found: {}", view_name))]
301    ViewNotFound {
302        view_name: String,
303        #[snafu(implicit)]
304        location: Location,
305    },
306
307    #[snafu(display("Failed to find table partition rule for table {}", table_name))]
308    FindTablePartitionRule {
309        table_name: String,
310        #[snafu(implicit)]
311        location: Location,
312        source: partition::error::Error,
313    },
314
315    #[snafu(display("Failed to split insert request"))]
316    SplitInsert {
317        source: partition::error::Error,
318        #[snafu(implicit)]
319        location: Location,
320    },
321
322    #[snafu(display("Failed to split delete request"))]
323    SplitDelete {
324        source: partition::error::Error,
325        #[snafu(implicit)]
326        location: Location,
327    },
328
329    #[snafu(display("Failed to find leader for region"))]
330    FindRegionLeader {
331        source: partition::error::Error,
332        #[snafu(implicit)]
333        location: Location,
334    },
335
336    #[snafu(display("Failed to build CreateExpr on insertion"))]
337    BuildCreateExprOnInsertion {
338        #[snafu(implicit)]
339        location: Location,
340        source: common_grpc_expr::error::Error,
341    },
342
343    #[snafu(display("Failed to find schema, schema info: {}", schema_info))]
344    SchemaNotFound {
345        schema_info: String,
346        #[snafu(implicit)]
347        location: Location,
348    },
349
350    #[snafu(display("Schema {} already exists", name))]
351    SchemaExists {
352        name: String,
353        #[snafu(implicit)]
354        location: Location,
355    },
356
357    #[snafu(display("Schema `{name}` is in use"))]
358    SchemaInUse {
359        name: String,
360        #[snafu(implicit)]
361        location: Location,
362    },
363
364    #[snafu(display("Schema `{name}` is read-only"))]
365    SchemaReadOnly {
366        name: String,
367        #[snafu(implicit)]
368        location: Location,
369    },
370
371    #[snafu(display("Table `{name}` is read-only"))]
372    TableReadOnly {
373        name: String,
374        #[snafu(implicit)]
375        location: Location,
376    },
377
378    #[snafu(display(
379        "The definition of table `{name}` is managed by GreptimeDB; it cannot be created or altered (DROP recreates it on the next write)"
380    ))]
381    TableDdlReserved {
382        name: String,
383        #[snafu(implicit)]
384        location: Location,
385    },
386
387    #[snafu(display("Table occurs error"))]
388    Table {
389        #[snafu(implicit)]
390        location: Location,
391        source: table::error::Error,
392    },
393
394    #[snafu(display("Cannot find column by name: {}", msg))]
395    ColumnNotFound {
396        msg: String,
397        #[snafu(implicit)]
398        location: Location,
399    },
400
401    #[snafu(display("Failed to execute statement"))]
402    ExecuteStatement {
403        #[snafu(implicit)]
404        location: Location,
405        source: query::error::Error,
406    },
407
408    #[snafu(display("Failed to plan statement"))]
409    PlanStatement {
410        #[snafu(implicit)]
411        location: Location,
412        source: query::error::Error,
413    },
414
415    #[snafu(display("Failed to parse query"))]
416    ParseQuery {
417        #[snafu(implicit)]
418        location: Location,
419        source: query::error::Error,
420    },
421
422    #[snafu(display("Failed to execute logical plan"))]
423    ExecLogicalPlan {
424        #[snafu(implicit)]
425        location: Location,
426        source: query::error::Error,
427    },
428
429    #[snafu(display("Failed to build DataFusion logical plan"))]
430    BuildDfLogicalPlan {
431        #[snafu(source)]
432        error: datafusion_common::DataFusionError,
433        #[snafu(implicit)]
434        location: Location,
435    },
436
437    #[snafu(display("Failed to convert AlterExpr to AlterRequest"))]
438    AlterExprToRequest {
439        #[snafu(implicit)]
440        location: Location,
441        source: common_grpc_expr::error::Error,
442    },
443
444    #[snafu(display("Failed to build table meta for table: {}", table_name))]
445    BuildTableMeta {
446        table_name: String,
447        #[snafu(source)]
448        error: table::metadata::TableMetaBuilderError,
449        #[snafu(implicit)]
450        location: Location,
451    },
452
453    #[snafu(display("Not supported: {}", feat))]
454    NotSupported { feat: String },
455
456    #[snafu(display("Failed to find new columns on insertion"))]
457    FindNewColumnsOnInsertion {
458        #[snafu(implicit)]
459        location: Location,
460        source: common_grpc_expr::error::Error,
461    },
462
463    #[snafu(display("Failed to convert into vectors"))]
464    IntoVectors {
465        #[snafu(implicit)]
466        location: Location,
467        source: datatypes::error::Error,
468    },
469
470    #[snafu(display("Failed to describe schema for given statement"))]
471    DescribeStatement {
472        #[snafu(implicit)]
473        location: Location,
474        source: query::error::Error,
475    },
476
477    #[snafu(display("Illegal primary keys definition: {}", msg))]
478    IllegalPrimaryKeysDef {
479        msg: String,
480        #[snafu(implicit)]
481        location: Location,
482    },
483
484    #[snafu(display("Unrecognized table option"))]
485    UnrecognizedTableOption {
486        #[snafu(implicit)]
487        location: Location,
488        source: table::error::Error,
489    },
490
491    #[snafu(display("Missing time index column"))]
492    MissingTimeIndexColumn {
493        #[snafu(implicit)]
494        location: Location,
495        source: table::error::Error,
496    },
497
498    #[snafu(display("Failed to build regex"))]
499    BuildRegex {
500        #[snafu(implicit)]
501        location: Location,
502        #[snafu(source)]
503        error: regex::Error,
504    },
505
506    #[snafu(display("Failed to insert value into table: {}", table_name))]
507    Insert {
508        table_name: String,
509        #[snafu(implicit)]
510        location: Location,
511        source: table::error::Error,
512    },
513
514    #[snafu(display("Unsupported format: {:?}", format))]
515    UnsupportedFormat {
516        #[snafu(implicit)]
517        location: Location,
518        format: Format,
519    },
520
521    #[snafu(display("Failed to parse file format"))]
522    ParseFileFormat {
523        #[snafu(implicit)]
524        location: Location,
525        source: common_datasource::error::Error,
526    },
527
528    #[snafu(display("Failed to build data source backend"))]
529    BuildBackend {
530        #[snafu(implicit)]
531        location: Location,
532        source: common_datasource::error::Error,
533    },
534
535    #[snafu(display("Failed to list objects"))]
536    ListObjects {
537        #[snafu(implicit)]
538        location: Location,
539        source: common_datasource::error::Error,
540    },
541
542    #[snafu(display("Failed to infer schema from path: {}", path))]
543    InferSchema {
544        path: String,
545        #[snafu(implicit)]
546        location: Location,
547        source: common_datasource::error::Error,
548    },
549
550    #[snafu(display("Failed to write stream to path: {}", path))]
551    WriteStreamToFile {
552        path: String,
553        #[snafu(implicit)]
554        location: Location,
555        source: common_datasource::error::Error,
556    },
557
558    #[snafu(display("Failed to read object in path: {}", path))]
559    ReadObject {
560        path: String,
561        #[snafu(implicit)]
562        location: Location,
563        #[snafu(source)]
564        error: object_store::Error,
565    },
566
567    #[snafu(display("Failed to read record batch"))]
568    ReadDfRecordBatch {
569        #[snafu(source)]
570        error: datafusion::error::DataFusionError,
571        #[snafu(implicit)]
572        location: Location,
573    },
574
575    #[snafu(display("Failed to read parquet file metadata"))]
576    ReadParquetMetadata {
577        #[snafu(source)]
578        error: parquet::errors::ParquetError,
579        #[snafu(implicit)]
580        location: Location,
581    },
582
583    #[snafu(display("Failed to build record batch"))]
584    BuildRecordBatch {
585        #[snafu(implicit)]
586        location: Location,
587        source: common_recordbatch::error::Error,
588    },
589
590    #[snafu(display("Failed to read orc schema"))]
591    ReadOrc {
592        source: common_datasource::error::Error,
593        #[snafu(implicit)]
594        location: Location,
595    },
596
597    #[snafu(display("Failed to build parquet record batch stream"))]
598    BuildParquetRecordBatchStream {
599        #[snafu(implicit)]
600        location: Location,
601        #[snafu(source)]
602        error: parquet::errors::ParquetError,
603    },
604
605    #[snafu(display("Failed to build file stream"))]
606    BuildFileStream {
607        #[snafu(implicit)]
608        location: Location,
609        #[snafu(source)]
610        error: common_datasource::error::Error,
611    },
612
613    #[snafu(display(
614        "Schema datatypes not match at index {}, expected table schema: {}, actual file schema: {}",
615        index,
616        table_schema,
617        file_schema
618    ))]
619    InvalidSchema {
620        index: usize,
621        table_schema: String,
622        file_schema: String,
623        #[snafu(implicit)]
624        location: Location,
625    },
626
627    #[snafu(display(
628        "CSV header mismatch in path: {}, unknown columns: {:?}, missing columns: {:?}, duplicate columns: {:?}",
629        path,
630        unknown_columns,
631        missing_columns,
632        duplicate_columns
633    ))]
634    CsvHeaderMismatch {
635        path: String,
636        unknown_columns: Vec<String>,
637        missing_columns: Vec<String>,
638        duplicate_columns: Vec<String>,
639        #[snafu(implicit)]
640        location: Location,
641    },
642
643    #[snafu(display("Failed to project schema"))]
644    ProjectSchema {
645        #[snafu(source)]
646        error: ArrowError,
647        #[snafu(implicit)]
648        location: Location,
649    },
650
651    #[snafu(display("Failed to encode object into json"))]
652    EncodeJson {
653        #[snafu(source)]
654        error: serde_json::error::Error,
655        #[snafu(implicit)]
656        location: Location,
657    },
658
659    #[snafu(display("Invalid COPY parameter, key: {}, value: {}", key, value))]
660    InvalidCopyParameter {
661        key: String,
662        value: String,
663        #[snafu(implicit)]
664        location: Location,
665    },
666
667    #[snafu(display("Invalid COPY DATABASE location, must end with '/': {}", value))]
668    InvalidCopyDatabasePath {
669        value: String,
670        #[snafu(implicit)]
671        location: Location,
672    },
673
674    #[snafu(display("Table metadata manager error"))]
675    TableMetadataManager {
676        source: common_meta::error::Error,
677        #[snafu(implicit)]
678        location: Location,
679    },
680
681    #[snafu(display("Missing insert body"))]
682    MissingInsertBody {
683        source: sql::error::Error,
684        #[snafu(implicit)]
685        location: Location,
686    },
687
688    #[snafu(display("Failed to parse sql value"))]
689    ParseSqlValue {
690        source: sql::error::Error,
691        #[snafu(implicit)]
692        location: Location,
693    },
694
695    #[snafu(display("Failed to build default value, column: {}", column))]
696    ColumnDefaultValue {
697        column: String,
698        #[snafu(implicit)]
699        location: Location,
700        source: datatypes::error::Error,
701    },
702
703    #[snafu(display(
704        "No valid default value can be built automatically, column: {}",
705        column,
706    ))]
707    ColumnNoneDefaultValue {
708        column: String,
709        #[snafu(implicit)]
710        location: Location,
711    },
712
713    #[snafu(display("Failed to prepare file table"))]
714    PrepareFileTable {
715        #[snafu(implicit)]
716        location: Location,
717        source: query::error::Error,
718    },
719
720    #[snafu(display("Failed to infer file table schema"))]
721    InferFileTableSchema {
722        #[snafu(implicit)]
723        location: Location,
724        source: query::error::Error,
725    },
726
727    #[snafu(display("The schema of the file table is incompatible with the table schema"))]
728    SchemaIncompatible {
729        #[snafu(implicit)]
730        location: Location,
731        source: query::error::Error,
732    },
733
734    #[snafu(display("Invalid table name: {}", table_name))]
735    InvalidTableName {
736        table_name: String,
737        #[snafu(implicit)]
738        location: Location,
739    },
740
741    #[snafu(display("Invalid view name: {name}"))]
742    InvalidViewName {
743        name: String,
744        #[snafu(implicit)]
745        location: Location,
746    },
747
748    #[snafu(display("Invalid flow name: {name}"))]
749    InvalidFlowName {
750        name: String,
751        #[snafu(implicit)]
752        location: Location,
753    },
754
755    #[cfg(feature = "enterprise")]
756    #[snafu(display("Invalid trigger name: {name}"))]
757    InvalidTriggerName {
758        name: String,
759        #[snafu(implicit)]
760        location: Location,
761    },
762
763    #[snafu(display("Empty {} expr", name))]
764    EmptyDdlExpr {
765        name: String,
766        #[snafu(implicit)]
767        location: Location,
768    },
769
770    #[snafu(display("Failed to create logical tables: {}", reason))]
771    CreateLogicalTables {
772        reason: String,
773        #[snafu(implicit)]
774        location: Location,
775    },
776
777    #[snafu(display("Invalid partition rule: {}", reason))]
778    InvalidPartitionRule {
779        reason: String,
780        #[snafu(implicit)]
781        location: Location,
782    },
783
784    #[snafu(display("Failed to serialize partition expression"))]
785    SerializePartitionExpr {
786        #[snafu(implicit)]
787        location: Location,
788        source: partition::error::Error,
789    },
790
791    #[snafu(display("Failed to deserialize partition expression"))]
792    DeserializePartitionExpr {
793        #[snafu(source)]
794        source: partition::error::Error,
795        #[snafu(implicit)]
796        location: Location,
797    },
798
799    #[snafu(display("Invalid configuration value."))]
800    InvalidConfigValue {
801        source: session::session_config::Error,
802        #[snafu(implicit)]
803        location: Location,
804    },
805
806    #[snafu(display("Invalid timestamp range, start: `{}`, end: `{}`", start, end))]
807    InvalidTimestampRange {
808        start: String,
809        end: String,
810        #[snafu(implicit)]
811        location: Location,
812    },
813
814    #[snafu(display("Failed to convert between logical plan and substrait plan"))]
815    SubstraitCodec {
816        #[snafu(implicit)]
817        location: Location,
818        source: substrait::error::Error,
819    },
820
821    #[snafu(display(
822        "Show create table only for base table. {} is {}",
823        table_name,
824        table_type
825    ))]
826    ShowCreateTableBaseOnly {
827        table_name: String,
828        table_type: TableType,
829        #[snafu(implicit)]
830        location: Location,
831    },
832    #[snafu(display("Create physical expr error"))]
833    PhysicalExpr {
834        #[snafu(source)]
835        error: common_recordbatch::error::Error,
836        #[snafu(implicit)]
837        location: Location,
838    },
839
840    #[snafu(display("Failed to upgrade catalog manager reference"))]
841    UpgradeCatalogManagerRef {
842        #[snafu(implicit)]
843        location: Location,
844    },
845
846    #[snafu(display("Invalid json text: {}", json))]
847    InvalidJsonFormat {
848        #[snafu(implicit)]
849        location: Location,
850        json: String,
851    },
852
853    #[snafu(display("Cursor {name} is not found"))]
854    CursorNotFound { name: String },
855
856    #[snafu(display("A cursor named {name} already exists"))]
857    CursorExists { name: String },
858
859    #[snafu(display("Column options error"))]
860    ColumnOptions {
861        #[snafu(source)]
862        source: api::error::Error,
863        #[snafu(implicit)]
864        location: Location,
865    },
866
867    #[snafu(display("Failed to create partition rules"))]
868    CreatePartitionRules {
869        #[snafu(source)]
870        source: sql::error::Error,
871        #[snafu(implicit)]
872        location: Location,
873    },
874
875    #[snafu(display("Failed to decode arrow flight data"))]
876    DecodeFlightData {
877        source: common_grpc::error::Error,
878        #[snafu(implicit)]
879        location: Location,
880    },
881
882    #[snafu(display("Failed to perform arrow compute"))]
883    ComputeArrow {
884        #[snafu(source)]
885        error: ArrowError,
886        #[snafu(implicit)]
887        location: Location,
888    },
889
890    #[snafu(display("Invalid time index type: {}", ty))]
891    InvalidTimeIndexType {
892        ty: arrow::datatypes::DataType,
893        #[snafu(implicit)]
894        location: Location,
895    },
896
897    #[snafu(display("Invalid timezone: {}", timezone))]
898    InvalidTimezone {
899        timezone: String,
900        #[snafu(source)]
901        source: common_time::error::Error,
902        #[snafu(implicit)]
903        location: Location,
904    },
905
906    #[snafu(display("Invalid process id: {}", id))]
907    InvalidProcessId { id: String },
908
909    #[snafu(display("ProcessManager is not present, this can be caused by misconfiguration."))]
910    ProcessManagerMissing {
911        #[snafu(implicit)]
912        location: Location,
913    },
914
915    #[snafu(display("Sql common error"))]
916    SqlCommon {
917        source: common_sql::error::Error,
918        #[snafu(implicit)]
919        location: Location,
920    },
921
922    #[snafu(display("Failed to convert partition expression to protobuf"))]
923    PartitionExprToPb {
924        source: partition::error::Error,
925        #[snafu(implicit)]
926        location: Location,
927    },
928
929    #[snafu(display(
930        "{} not supported when transforming to {} format type",
931        format,
932        file_format
933    ))]
934    TimestampFormatNotSupported {
935        file_format: String,
936        format: String,
937        #[snafu(implicit)]
938        location: Location,
939    },
940
941    #[cfg(feature = "enterprise")]
942    #[snafu(display("Too large duration"))]
943    TooLargeDuration {
944        #[snafu(source)]
945        error: prost_types::DurationError,
946        #[snafu(implicit)]
947        location: Location,
948    },
949
950    #[cfg(feature = "enterprise")]
951    #[snafu(display("Not trigger querier is specified"))]
952    MissingTriggerQuerier {
953        #[snafu(implicit)]
954        location: Location,
955    },
956
957    #[cfg(feature = "enterprise")]
958    #[snafu(display("Trigger querier error"))]
959    TriggerQuerier {
960        source: BoxedError,
961        #[snafu(implicit)]
962        location: Location,
963    },
964}
965
966pub type Result<T> = std::result::Result<T, Error>;
967
968impl ErrorExt for Error {
969    fn status_code(&self) -> StatusCode {
970        match self {
971            Error::Cast { source, .. } => source.status_code(),
972            Error::InvalidSql { .. }
973            | Error::InvalidConfigValue { .. }
974            | Error::InvalidInsertRequest { .. }
975            | Error::InvalidDeleteRequest { .. }
976            | Error::IllegalPrimaryKeysDef { .. }
977            | Error::SchemaNotFound { .. }
978            | Error::SchemaExists { .. }
979            | Error::SchemaInUse { .. }
980            | Error::ColumnNotFound { .. }
981            | Error::BuildRegex { .. }
982            | Error::InvalidSchema { .. }
983            | Error::CsvHeaderMismatch { .. }
984            | Error::ProjectSchema { .. }
985            | Error::UnsupportedFormat { .. }
986            | Error::ColumnNoneDefaultValue { .. }
987            | Error::PrepareFileTable { .. }
988            | Error::InferFileTableSchema { .. }
989            | Error::SchemaIncompatible { .. }
990            | Error::ConvertSchema { .. }
991            | Error::UnsupportedRegionRequest { .. }
992            | Error::InvalidTableName { .. }
993            | Error::InvalidViewName { .. }
994            | Error::InvalidFlowName { .. }
995            | Error::InvalidView { .. }
996            | Error::InvalidExpr { .. }
997            | Error::AdminFunctionNotFound { .. }
998            | Error::ViewColumnsMismatch { .. }
999            | Error::InvalidViewStmt { .. }
1000            | Error::ConvertIdentifier { .. }
1001            | Error::BuildAdminFunctionArgs { .. }
1002            | Error::FunctionArityMismatch { .. }
1003            | Error::InvalidPartition { .. }
1004            | Error::PhysicalExpr { .. }
1005            | Error::InvalidJsonFormat { .. }
1006            | Error::PartitionExprToPb { .. }
1007            | Error::CursorNotFound { .. }
1008            | Error::CursorExists { .. }
1009            | Error::CreatePartitionRules { .. } => StatusCode::InvalidArguments,
1010            Error::TableAlreadyExists { .. } | Error::ViewAlreadyExists { .. } => {
1011                StatusCode::TableAlreadyExists
1012            }
1013            Error::NotSupported { .. }
1014            | Error::ShowCreateTableBaseOnly { .. }
1015            | Error::SchemaReadOnly { .. }
1016            | Error::TableReadOnly { .. }
1017            | Error::TableDdlReserved { .. } => StatusCode::Unsupported,
1018            Error::TableMetadataManager { source, .. } => source.status_code(),
1019            Error::ParseSql { source, .. } => source.status_code(),
1020            Error::InvalidateTableCache { source, .. } => source.status_code(),
1021            Error::ParseFileFormat { source, .. } | Error::InferSchema { source, .. } => {
1022                source.status_code()
1023            }
1024            Error::Table { source, .. } | Error::Insert { source, .. } => source.status_code(),
1025            Error::ConvertColumnDefaultConstraint { source, .. }
1026            | Error::IntoVectors { source, .. } => source.status_code(),
1027            Error::RequestInserts { source, .. } | Error::FindViewInfo { source, .. } => {
1028                source.status_code()
1029            }
1030            Error::RequestRegion { source, .. } => source.status_code(),
1031            Error::RequestDeletes { source, .. } => source.status_code(),
1032            Error::SubstraitCodec { source, .. } => source.status_code(),
1033            Error::ColumnDataType { source, .. } | Error::InvalidColumnDef { source, .. } => {
1034                source.status_code()
1035            }
1036            Error::MissingTimeIndexColumn { source, .. } => source.status_code(),
1037            Error::BuildDfLogicalPlan { .. }
1038            | Error::BuildTableMeta { .. }
1039            | Error::MissingInsertBody { .. } => StatusCode::Internal,
1040            Error::ExecuteAdminFunction { error, .. } => admin_external_error(error)
1041                .map(ErrorExt::status_code)
1042                .unwrap_or(StatusCode::Unexpected),
1043            Error::EncodeJson { .. }
1044            | Error::DeserializePartitionExpr { .. }
1045            | Error::SerializePartitionExpr { .. } => StatusCode::Unexpected,
1046            Error::AdminFunctionCancelled => StatusCode::Cancelled,
1047            Error::ViewNotFound { .. }
1048            | Error::ViewInfoNotFound { .. }
1049            | Error::TableNotFound { .. } => StatusCode::TableNotFound,
1050            Error::FlowNotFound { .. } => StatusCode::FlowNotFound,
1051            Error::JoinTask { .. } => StatusCode::Internal,
1052            Error::BuildParquetRecordBatchStream { .. }
1053            | Error::BuildFileStream { .. }
1054            | Error::WriteStreamToFile { .. }
1055            | Error::ReadDfRecordBatch { .. }
1056            | Error::Unexpected { .. } => StatusCode::Unexpected,
1057            Error::Catalog { source, .. } => source.status_code(),
1058            Error::BuildCreateExprOnInsertion { source, .. }
1059            | Error::FindNewColumnsOnInsertion { source, .. } => source.status_code(),
1060            Error::ExecuteStatement { source, .. }
1061            | Error::ExtractTableNames { source, .. }
1062            | Error::PlanStatement { source, .. }
1063            | Error::ParseQuery { source, .. }
1064            | Error::ExecLogicalPlan { source, .. }
1065            | Error::DescribeStatement { source, .. } => source.status_code(),
1066            Error::AlterExprToRequest { source, .. } => source.status_code(),
1067            Error::External { source, .. } => source.status_code(),
1068            Error::BatchFlush { source, .. } => source.status_code(),
1069            Error::FindTablePartitionRule { source, .. }
1070            | Error::SplitInsert { source, .. }
1071            | Error::SplitDelete { source, .. }
1072            | Error::FindRegionLeader { source, .. } => source.status_code(),
1073            Error::UnrecognizedTableOption { .. } => StatusCode::InvalidArguments,
1074            Error::ReadObject { .. }
1075            | Error::ReadParquetMetadata { .. }
1076            | Error::ReadOrc { .. } => StatusCode::StorageUnavailable,
1077            Error::ListObjects { source, .. } | Error::BuildBackend { source, .. } => {
1078                source.status_code()
1079            }
1080            Error::ExecuteDdl { source, .. } => source.status_code(),
1081            Error::InvalidCopyParameter { .. } | Error::InvalidCopyDatabasePath { .. } => {
1082                StatusCode::InvalidArguments
1083            }
1084            Error::ColumnDefaultValue { source, .. } => source.status_code(),
1085            Error::EmptyDdlExpr { .. }
1086            | Error::InvalidPartitionRule { .. }
1087            | Error::ParseSqlValue { .. }
1088            | Error::InvalidTimestampRange { .. } => StatusCode::InvalidArguments,
1089            Error::CreateLogicalTables { .. } => StatusCode::Unexpected,
1090            Error::BuildRecordBatch { source, .. } => source.status_code(),
1091            Error::UpgradeCatalogManagerRef { .. } => StatusCode::Internal,
1092            Error::ColumnOptions { source, .. } => source.status_code(),
1093            Error::DecodeFlightData { source, .. } => source.status_code(),
1094            Error::ComputeArrow { .. } => StatusCode::Internal,
1095            Error::InvalidTimeIndexType { .. } | Error::InvalidTimezone { .. } => {
1096                StatusCode::InvalidArguments
1097            }
1098            Error::InvalidDatabaseExport { .. } => StatusCode::InvalidArguments,
1099            Error::DatabaseExportCancelled { .. } => StatusCode::Cancelled,
1100            Error::InvalidLogicalTableExport { .. } => StatusCode::InvalidArguments,
1101            Error::LogicalTableExportResource { .. } => StatusCode::Suspended,
1102            Error::LogicalTableExportCancelled { .. } => StatusCode::Cancelled,
1103            Error::InvalidProcessId { .. } => StatusCode::InvalidArguments,
1104            Error::ProcessManagerMissing { .. } => StatusCode::Unexpected,
1105            Error::TimestampFormatNotSupported { .. } => StatusCode::InvalidArguments,
1106            Error::SqlCommon { source, .. } => source.status_code(),
1107            #[cfg(feature = "enterprise")]
1108            Error::InvalidTriggerName { .. } => StatusCode::InvalidArguments,
1109            #[cfg(feature = "enterprise")]
1110            Error::TooLargeDuration { .. } => StatusCode::InvalidArguments,
1111            #[cfg(feature = "enterprise")]
1112            Error::MissingTriggerQuerier { .. } => StatusCode::Internal,
1113            #[cfg(feature = "enterprise")]
1114            Error::TriggerQuerier { source, .. } => source.status_code(),
1115        }
1116    }
1117
1118    fn as_any(&self) -> &dyn Any {
1119        self
1120    }
1121
1122    fn retry_hint(&self) -> RetryHint {
1123        match self {
1124            Error::ReadObject { error, .. } => retry_hint_from_opendal_error(error),
1125            Error::ReadParquetMetadata { .. } => RetryHint::Retryable,
1126            Error::InvalidateTableCache { source, .. }
1127            | Error::ExecuteDdl { source, .. }
1128            | Error::RequestInserts { source, .. }
1129            | Error::RequestDeletes { source, .. }
1130            | Error::RequestRegion { source, .. }
1131            | Error::FindViewInfo { source, .. }
1132            | Error::TableMetadataManager { source, .. } => source.retry_hint(),
1133
1134            Error::ParseFileFormat { source, .. }
1135            | Error::InferSchema { source, .. }
1136            | Error::ListObjects { source, .. }
1137            | Error::BuildBackend { source, .. }
1138            | Error::ReadOrc { source, .. } => source.retry_hint(),
1139
1140            Error::ExtractTableNames { source, .. }
1141            | Error::ExecuteStatement { source, .. }
1142            | Error::PlanStatement { source, .. }
1143            | Error::ParseQuery { source, .. }
1144            | Error::ExecLogicalPlan { source, .. }
1145            | Error::DescribeStatement { source, .. } => source.retry_hint(),
1146
1147            Error::FindTablePartitionRule { source, .. }
1148            | Error::SplitInsert { source, .. }
1149            | Error::SplitDelete { source, .. }
1150            | Error::FindRegionLeader { source, .. } => source.retry_hint(),
1151
1152            Error::BuildCreateExprOnInsertion { source, .. }
1153            | Error::FindNewColumnsOnInsertion { source, .. }
1154            | Error::AlterExprToRequest { source, .. } => source.retry_hint(),
1155
1156            Error::ConvertColumnDefaultConstraint { source, .. }
1157            | Error::IntoVectors { source, .. }
1158            | Error::ColumnDefaultValue { source, .. } => source.retry_hint(),
1159
1160            Error::ColumnDataType { source, .. }
1161            | Error::InvalidColumnDef { source, .. }
1162            | Error::ColumnOptions { source, .. } => source.retry_hint(),
1163
1164            Error::Table { source, .. }
1165            | Error::Insert { source, .. }
1166            | Error::MissingTimeIndexColumn { source, .. } => source.retry_hint(),
1167
1168            Error::Cast { source, .. } => source.retry_hint(),
1169            Error::ExecuteAdminFunction { error, .. } => admin_external_error(error)
1170                .map(ErrorExt::retry_hint)
1171                .unwrap_or(RetryHint::NonRetryable),
1172            Error::ParseSql { source, .. } => source.retry_hint(),
1173            Error::Catalog { source, .. } => source.retry_hint(),
1174            Error::SubstraitCodec { source, .. } => source.retry_hint(),
1175            Error::External { source, .. } => source.retry_hint(),
1176            Error::BatchFlush { source, .. } => source.retry_hint(),
1177            Error::BuildRecordBatch { source, .. } => source.retry_hint(),
1178            Error::DecodeFlightData { source, .. } => source.retry_hint(),
1179            Error::SqlCommon { source, .. } => source.retry_hint(),
1180            Error::ConvertSchema { source, .. } => source.retry_hint(),
1181            Error::WriteStreamToFile { source, .. } => source.retry_hint(),
1182            Error::PrepareFileTable { source, .. } | Error::InferFileTableSchema { source, .. } => {
1183                source.retry_hint()
1184            }
1185            #[cfg(feature = "enterprise")]
1186            Error::TriggerQuerier { source, .. } => source.retry_hint(),
1187            _ => RetryHint::NonRetryable,
1188        }
1189    }
1190}
1191
1192fn admin_external_error(error: &DataFusionError) -> Option<&BoxedError> {
1193    match error {
1194        DataFusionError::External(error) => error.downcast_ref::<BoxedError>(),
1195        DataFusionError::Diagnostic(_, error) => admin_external_error(error),
1196        _ => None,
1197    }
1198}
1199
1200define_into_tonic_status!(Error);
1201
1202#[cfg(test)]
1203mod tests {
1204    use crate::error::*;
1205
1206    #[test]
1207    fn admin_function_preserves_external_error_metadata() {
1208        let external = BoxedError::new(meta_client::error::Error::MetaServer {
1209            code: StatusCode::TableUnavailable,
1210            msg: "leader changed".to_string(),
1211            tonic_code: tonic::Code::Unavailable,
1212            retry_hint: RetryHint::Retryable,
1213            location: snafu::location!(),
1214        });
1215        let error = Error::ExecuteAdminFunction {
1216            msg: "test_admin".to_string(),
1217            error: DataFusionError::External(Box::new(external)),
1218            location: snafu::location!(),
1219        };
1220
1221        assert_eq!(StatusCode::TableUnavailable, error.status_code());
1222        assert_eq!(RetryHint::Retryable, error.retry_hint());
1223    }
1224}