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