-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathplanner.rs
2679 lines (2444 loc) · 94.3 KB
/
planner.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 The CeresDB Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Planner converts a SQL AST into logical plans
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap},
convert::TryFrom,
mem,
ops::ControlFlow,
sync::{atomic::AtomicBool, Arc},
};
use arrow::{
compute::can_cast_types,
datatypes::{DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema},
error::ArrowError,
};
use catalog::consts::{DEFAULT_CATALOG, DEFAULT_SCHEMA};
use ceresdbproto::storage::{value::Value as PbValue, WriteTableRequest};
use cluster::config::SchemaConfig;
use common_types::{
column_schema::{self, ColumnSchema},
datum::{Datum, DatumKind},
request_id::RequestId,
row::{RowBuilder, RowGroup},
schema::{self, Builder as SchemaBuilder, Schema, TSID_COLUMN},
};
use datafusion::{
common::{DFField, DFSchema},
error::DataFusionError,
optimizer::simplify_expressions::{ExprSimplifier, SimplifyContext},
physical_expr::{create_physical_expr, execution_props::ExecutionProps},
sql::{
planner::{ParserOptions, PlannerContext, SqlToRel},
ResolvedTableReference,
},
};
use generic_error::GenericError;
use influxql_parser::statement::Statement as InfluxqlStatement;
use logger::{debug, trace};
use macros::define_result;
use prom_remote_api::types::Query as PromRemoteQuery;
use snafu::{ensure, Backtrace, OptionExt, ResultExt, Snafu};
use sqlparser::ast::{
visit_statements_mut, ColumnDef, ColumnOption, Expr, Expr as SqlExpr, Ident, Query, SelectItem,
SetExpr, SqlOption, Statement as SqlStatement, TableConstraint, UnaryOperator, Value, Values,
};
use table_engine::table::TableRef;
use crate::{
ast::{
AlterAddColumn, AlterModifySetting, CreateTable, DescribeTable, DropTable, ExistsTable,
ShowCreate, ShowTables, Statement, TableName,
},
config::DynamicConfig,
container::TableReference,
frontend::parse_table_name_with_standard,
logical_optimizer::optimize_plan,
parser,
partition::PartitionParser,
plan::{
AlterTableOperation, AlterTablePlan, CreateTablePlan, DescribeTablePlan, DropTablePlan,
ExistsTablePlan, InsertPlan, Plan, QueryPlan, QueryType, ShowCreatePlan, ShowPlan,
ShowTablesPlan,
},
promql::{remote_query_to_plan, ColumnNames, Expr as PromExpr, RemoteQueryPlan},
provider::{ContextProviderAdapter, MetaProvider},
};
// We do not carry backtrace in sql error because it is mainly used in server
// handler and the error is usually caused by invalid/unsupported sql, which
// should be easy to find out the reason.
#[derive(Debug, Snafu)]
#[snafu(visibility = "pub")]
pub enum Error {
#[snafu(display("Failed to generate datafusion plan, err:{}", source))]
DatafusionPlan { source: DataFusionError },
#[snafu(display("Failed to create datafusion schema, err:{}", source))]
CreateDatafusionSchema { source: DataFusionError },
#[snafu(display("Failed to merge arrow schema, err:{}", source))]
MergeArrowSchema { source: ArrowError },
#[snafu(display("Failed to generate datafusion expr, err:{}", source))]
DatafusionExpr { source: DataFusionError },
#[snafu(display(
"Failed to get data type from datafusion physical expr, err:{}",
source
))]
DatafusionDataType { source: DataFusionError },
// Statement is too large and complicate to carry in Error, so we
// only return error here, so the caller should attach sql to its
// error context
#[snafu(display("Unsupported SQL statement"))]
UnsupportedStatement,
#[snafu(display("Create table name is empty"))]
CreateTableNameEmpty,
#[snafu(display("Only support non-column-input expr in default-value-option, column name:{} default value:{}", name, default_value))]
CreateWithComplexDefaultValue { name: String, default_value: Expr },
#[snafu(display("Table must contain timestamp constraint"))]
RequireTimestamp,
#[snafu(display(
"Table must contain only one timestamp key and it's data type must be TIMESTAMP"
))]
InvalidTimestampKey,
#[snafu(display("Invalid unsign type: {}.\nBacktrace:\n{}", kind, backtrace))]
InvalidUnsignType {
kind: DatumKind,
backtrace: Backtrace,
},
#[snafu(display(
"Undefined column is used in primary key, column name:{}.\nBacktrace:\n{}",
name,
backtrace
))]
UndefinedColumnInPrimaryKey { name: String, backtrace: Backtrace },
#[snafu(display("Primary key not found, column name:{}", name))]
PrimaryKeyNotFound { name: String },
#[snafu(display(
"Duplicate definitions of primary key are found, first:{:?}, second:{:?}.\nBacktrace:\n{:?}",
first,
second,
backtrace,
))]
DuplicatePrimaryKey {
first: Vec<Ident>,
second: Vec<Ident>,
backtrace: Backtrace,
},
#[snafu(display("Tag column not found, name:{}", name))]
TagColumnNotFound { name: String },
#[snafu(display(
"Timestamp key column can not be tag, name:{}.\nBacktrace:\n{:?}",
name,
backtrace
))]
TimestampKeyTag { name: String, backtrace: Backtrace },
#[snafu(display("Timestamp column not found, name:{}", name))]
TimestampColumnNotFound { name: String },
#[snafu(display("{} is a reserved column name", name))]
ColumnNameReserved { name: String },
#[snafu(display("Invalid create table name, err:{}", source))]
InvalidCreateTableName { source: DataFusionError },
#[snafu(display("Failed to build schema, err:{}", source))]
BuildTableSchema { source: common_types::schema::Error },
#[snafu(display("Unsupported SQL data type, err:{}", source))]
UnsupportedDataType { source: common_types::datum::Error },
#[snafu(display("Invalid column schema, column_name:{}, err:{}", column_name, source))]
InvalidColumnSchema {
column_name: String,
source: column_schema::Error,
},
#[snafu(display("Invalid table name, err:{}", source))]
InvalidTableName { source: DataFusionError },
#[snafu(display("Table not found, table:{}", name))]
TableNotFound { name: String },
#[snafu(display("Column is not null, table:{}, column:{}", table, column))]
InsertMissingColumn { table: String, column: String },
#[snafu(display("Column is reserved, table:{}, column:{}", table, column))]
InsertReservedColumn { table: String, column: String },
#[snafu(display("Unknown insert column, name:{}", name))]
UnknownInsertColumn { name: String },
#[snafu(display("Insert values not enough, len:{}, index:{}", len, index))]
InsertValuesNotEnough { len: usize, index: usize },
#[snafu(display("Invalid insert stmt, contains duplicate columns"))]
InsertDuplicateColumns,
#[snafu(display("Invalid insert stmt, source should be a set"))]
InsertSourceBodyNotSet,
#[snafu(display(
"Invalid insert stmt, source expr is not value, source_expr:{:?}.\nBacktrace:\n{}",
source_expr,
backtrace,
))]
InsertExprNotValue {
source_expr: Expr,
backtrace: Backtrace,
},
#[snafu(display(
"Invalid insert stmt, source expr has no valid negative value, source_expr:{:?}.\nBacktrace:\n{}",
source_expr,
backtrace,
))]
InsertExprNoNegativeValue {
source_expr: Expr,
backtrace: Backtrace,
},
#[snafu(display("Insert Failed to convert value, err:{}", source))]
InsertConvertValue { source: common_types::datum::Error },
#[snafu(display("Failed to build row, err:{}", source))]
BuildRow { source: common_types::row::Error },
#[snafu(display("MetaProvider Failed to find table, err:{}", source))]
MetaProviderFindTable { source: crate::provider::Error },
#[snafu(display("Failed to find meta during planning, err:{}", source))]
FindMeta { source: crate::provider::Error },
#[snafu(display("Invalid alter table operation, err:{}", source))]
InvalidAlterTableOperation { source: crate::plan::Error },
#[snafu(display("Unsupported sql option, value:{}", value))]
UnsupportedOption { value: String },
#[snafu(display("Failed to build plan from promql, error:{}", source))]
BuildPromPlanError { source: crate::promql::Error },
#[snafu(display(
"Failed to cast default value expr to column type, expr:{}, from:{}, to:{}",
expr,
from,
to
))]
InvalidDefaultValueCoercion {
expr: Expr,
from: ArrowDataType,
to: ArrowDataType,
},
#[snafu(display(
"Failed to parse partition statement to partition info, msg:{}, err:{}",
msg,
source,
))]
ParsePartitionWithCause { msg: String, source: GenericError },
#[snafu(display("Unsupported partition method, msg:{}", msg,))]
UnsupportedPartition { msg: String },
#[snafu(display("Failed to build plan, msg:{}", msg))]
InvalidWriteEntry { msg: String },
#[snafu(display("Failed to build influxql plan, err:{}", source))]
BuildInfluxqlPlan {
source: crate::influxql::error::Error,
},
}
define_result!(Error);
const DEFAULT_QUOTE_CHAR: char = '`';
const DEFAULT_PARSER_OPTS: ParserOptions = ParserOptions {
parse_float_as_decimal: false,
enable_ident_normalization: false,
};
pub struct PlannerHint {
pub enable_push_down_able_dist_query: AtomicBool,
}
/// Planner produces logical plans from SQL AST
// TODO(yingwen): Rewrite Planner instead of using datafusion's planner
pub struct Planner<'a, P: MetaProvider> {
provider: &'a P,
request_id: RequestId,
read_parallelism: usize,
dyn_config: &'a DynamicConfig,
}
impl<'a, P: MetaProvider> Planner<'a, P> {
/// Create a new logical planner
pub fn new(
provider: &'a P,
request_id: RequestId,
read_parallelism: usize,
dyn_config: &'a DynamicConfig,
) -> Self {
Self {
provider,
request_id,
read_parallelism,
dyn_config,
}
}
/// Create a logical plan from Statement
///
/// Takes the ownership of statement because some statements like INSERT
/// statements contains lots of data
pub fn statement_to_plan(&self, statement: Statement) -> Result<Plan> {
trace!(
"Statement to plan, request_id:{}, statement:{:?}",
self.request_id,
statement
);
let adapter =
ContextProviderAdapter::new(self.provider, self.read_parallelism, self.dyn_config);
// SqlToRel needs to hold the reference to adapter, thus we can't both holds the
// adapter and the SqlToRel in Planner, which is a self-referential
// case. We wrap a PlannerDelegate to workaround this and avoid the usage of
// pin.
let planner = PlannerDelegate::new(adapter);
match statement {
Statement::Standard(s) => planner.sql_statement_to_plan(*s),
Statement::Create(s) => planner.create_table_to_plan(*s),
Statement::Drop(s) => planner.drop_table_to_plan(s),
Statement::Describe(s) => planner.describe_table_to_plan(s),
Statement::AlterModifySetting(s) => planner.alter_modify_setting_to_plan(s),
Statement::AlterAddColumn(s) => planner.alter_add_column_to_plan(s),
Statement::ShowCreate(s) => planner.show_create_to_plan(s),
Statement::ShowTables(s) => planner.show_tables_to_plan(s),
Statement::ShowDatabases => planner.show_databases_to_plan(),
Statement::Exists(s) => planner.exists_table_to_plan(s),
}
}
pub fn promql_expr_to_plan(&self, expr: PromExpr) -> Result<(Plan, Arc<ColumnNames>)> {
let adapter =
ContextProviderAdapter::new(self.provider, self.read_parallelism, self.dyn_config);
// SqlToRel needs to hold the reference to adapter, thus we can't both holds the
// adapter and the SqlToRel in Planner, which is a self-referential
// case. We wrap a PlannerDelegate to workaround this and avoid the usage of
// pin.
let planner = PlannerDelegate::new(adapter);
expr.to_plan(planner.meta_provider, self.read_parallelism)
.context(BuildPromPlanError)
}
pub fn remote_prom_req_to_plan(&self, query: PromRemoteQuery) -> Result<RemoteQueryPlan> {
let adapter =
ContextProviderAdapter::new(self.provider, self.read_parallelism, self.dyn_config);
let planner = PlannerDelegate::new(adapter);
remote_query_to_plan(query, planner.meta_provider).context(BuildPromPlanError)
}
pub fn influxql_stmt_to_plan(&self, statement: InfluxqlStatement) -> Result<Plan> {
let adapter =
ContextProviderAdapter::new(self.provider, self.read_parallelism, self.dyn_config);
let planner = crate::influxql::planner::Planner::new(adapter);
planner
.statement_to_plan(statement)
.context(BuildInfluxqlPlan)
}
pub fn write_req_to_plan(
&self,
schema_config: &SchemaConfig,
write_table: &WriteTableRequest,
) -> Result<Plan> {
Ok(Plan::Create(CreateTablePlan {
engine: schema_config.default_engine_type.clone(),
if_not_exists: true,
table: write_table.table.clone(),
table_schema: build_schema_from_write_table_request(schema_config, write_table)?,
options: HashMap::default(),
partition_info: None,
}))
}
}
pub fn build_column_schema(
column_name: &str,
data_type: DatumKind,
is_tag: bool,
) -> Result<ColumnSchema> {
let builder = column_schema::Builder::new(column_name.to_string(), data_type)
.is_nullable(true)
.is_tag(is_tag);
builder.build().with_context(|| InvalidColumnSchema {
column_name: column_name.to_string(),
})
}
pub fn build_schema_from_write_table_request(
schema_config: &SchemaConfig,
write_table_req: &WriteTableRequest,
) -> Result<Schema> {
let WriteTableRequest {
table,
field_names,
tag_names,
entries: write_entries,
} = write_table_req;
let mut schema_builder =
SchemaBuilder::with_capacity(field_names.len()).auto_increment_column_id(true);
ensure!(
!write_entries.is_empty(),
InvalidWriteEntry {
msg: "empty write entries".to_string()
}
);
let mut name_column_map: BTreeMap<_, ColumnSchema> = BTreeMap::new();
for write_entry in write_entries {
// parse tags
for tag in &write_entry.tags {
let name_index = tag.name_index as usize;
ensure!(
name_index < tag_names.len(),
InvalidWriteEntry {
msg: format!(
"tag {tag:?} is not found in tag_names:{tag_names:?}, table:{table}",
),
}
);
let tag_name = &tag_names[name_index];
let tag_value = tag
.value
.as_ref()
.with_context(|| InvalidWriteEntry {
msg: format!("Tag({tag_name}) value is needed, table_name:{table} "),
})?
.value
.as_ref()
.with_context(|| InvalidWriteEntry {
msg: format!("Tag({tag_name}) value type is not supported, table_name:{table}"),
})?;
let data_type = try_get_data_type_from_value(tag_value)?;
if let Some(column_schema) = name_column_map.get(tag_name) {
ensure_data_type_compatible(table, tag_name, true, data_type, column_schema)?;
}
let column_schema = build_column_schema(tag_name, data_type, true)?;
name_column_map.insert(tag_name, column_schema);
}
// parse fields
for field_group in &write_entry.field_groups {
for field in &field_group.fields {
if (field.name_index as usize) < field_names.len() {
let field_name = &field_names[field.name_index as usize];
let field_value = field
.value
.as_ref()
.with_context(|| InvalidWriteEntry {
msg: format!("Field({field_name}) value is needed, table:{table}"),
})?
.value
.as_ref()
.with_context(|| InvalidWriteEntry {
msg: format!(
"Field({field_name}) value type is not supported, table:{table}"
),
})?;
let data_type = try_get_data_type_from_value(field_value)?;
if let Some(column_schema) = name_column_map.get(field_name) {
ensure_data_type_compatible(
table,
field_name,
false,
data_type,
column_schema,
)?;
}
let column_schema = build_column_schema(field_name, data_type, false)?;
name_column_map.insert(field_name, column_schema);
}
}
}
}
// Timestamp column will be the last column
let timestamp_column_schema = column_schema::Builder::new(
schema_config.default_timestamp_column_name.clone(),
DatumKind::Timestamp,
)
.is_nullable(false)
.build()
.with_context(|| InvalidColumnSchema {
column_name: schema_config.default_timestamp_column_name.clone(),
})?;
// Use (tsid, timestamp) as primary key.
let tsid_column_schema =
column_schema::Builder::new(TSID_COLUMN.to_string(), DatumKind::UInt64)
.is_nullable(false)
.build()
.with_context(|| InvalidColumnSchema {
column_name: TSID_COLUMN.to_string(),
})?;
schema_builder = schema_builder
.add_key_column(tsid_column_schema)
.context(BuildTableSchema {})?
.add_key_column(timestamp_column_schema)
.context(BuildTableSchema {})?;
for col in name_column_map.into_values() {
schema_builder = schema_builder
.add_normal_column(col)
.context(BuildTableSchema {})?;
}
schema_builder
.primary_key_indexes(vec![0, 1])
.build()
.context(BuildTableSchema {})
}
fn ensure_data_type_compatible(
table_name: &str,
column_name: &str,
is_tag: bool,
data_type: DatumKind,
column_schema: &ColumnSchema,
) -> Result<()> {
ensure!(
column_schema.is_tag == is_tag,
InvalidWriteEntry {
msg: format!(
"Duplicated column: {column_name} in fields and tags for table: {table_name}",
),
}
);
ensure!(
column_schema.data_type == data_type,
InvalidWriteEntry {
msg: format!(
"Column: {} in table: {} data type is not same, expected: {}, actual: {}",
column_name, table_name, column_schema.data_type, data_type,
),
}
);
Ok(())
}
pub fn try_get_data_type_from_value(value: &PbValue) -> Result<DatumKind> {
match value {
PbValue::Float64Value(_) => Ok(DatumKind::Double),
PbValue::StringValue(_) => Ok(DatumKind::String),
PbValue::Int64Value(_) => Ok(DatumKind::Int64),
PbValue::Float32Value(_) => Ok(DatumKind::Float),
PbValue::Int32Value(_) => Ok(DatumKind::Int32),
PbValue::Int16Value(_) => Ok(DatumKind::Int16),
PbValue::Int8Value(_) => Ok(DatumKind::Int8),
PbValue::BoolValue(_) => Ok(DatumKind::Boolean),
PbValue::Uint64Value(_) => Ok(DatumKind::UInt64),
PbValue::Uint32Value(_) => Ok(DatumKind::UInt32),
PbValue::Uint16Value(_) => Ok(DatumKind::UInt16),
PbValue::Uint8Value(_) => Ok(DatumKind::UInt8),
PbValue::TimestampValue(_) => Ok(DatumKind::Timestamp),
PbValue::VarbinaryValue(_) => Ok(DatumKind::Varbinary),
}
}
/// A planner wraps the datafusion's logical planner, and delegate sql like
/// select/explain to datafusion's planner.
pub(crate) struct PlannerDelegate<'a, P: MetaProvider> {
meta_provider: ContextProviderAdapter<'a, P>,
}
impl<'a, P: MetaProvider> PlannerDelegate<'a, P> {
pub(crate) fn new(meta_provider: ContextProviderAdapter<'a, P>) -> Self {
Self { meta_provider }
}
pub(crate) fn sql_statement_to_plan(self, mut sql_stmt: SqlStatement) -> Result<Plan> {
match sql_stmt {
// Query statement use datafusion planner
SqlStatement::Explain { .. } | SqlStatement::Query(_) => {
normalize_func_name(&mut sql_stmt);
self.sql_statement_to_datafusion_plan(sql_stmt)
}
SqlStatement::Insert { .. } => self.insert_to_plan(sql_stmt),
_ => UnsupportedStatement.fail(),
}
}
fn sql_statement_to_datafusion_plan(self, sql_stmt: SqlStatement) -> Result<Plan> {
let df_planner = SqlToRel::new_with_options(&self.meta_provider, DEFAULT_PARSER_OPTS);
let table_name = parse_table_name_with_standard(&sql_stmt);
let df_plan = df_planner
.sql_statement_to_plan(sql_stmt)
.context(DatafusionPlan)?;
let df_plan = optimize_plan(&df_plan).context(DatafusionPlan)?;
debug!("Sql statement to datafusion plan, df_plan:\n{:#?}", df_plan);
// Get all tables needed in the plan
let tables = self.meta_provider.try_into_container().context(FindMeta)?;
Ok(Plan::Query(QueryPlan {
df_plan,
table_name,
tables: Arc::new(tables),
}))
}
fn tsid_column_schema() -> Result<ColumnSchema> {
column_schema::Builder::new(TSID_COLUMN.to_string(), DatumKind::UInt64)
.is_nullable(false)
.build()
.context(InvalidColumnSchema {
column_name: TSID_COLUMN,
})
}
fn create_table_schema(
columns: &[Ident],
primary_key_columns: &[Ident],
mut columns_by_name: HashMap<&str, ColumnSchema>,
column_idxs_by_name: HashMap<&str, usize>,
) -> Result<Schema> {
assert_eq!(columns_by_name.len(), column_idxs_by_name.len());
let mut schema_builder =
schema::Builder::with_capacity(columns_by_name.len()).auto_increment_column_id(true);
// Collect the key columns.
// TODO: Here we put key column in front of all columns, this may change column
// order defined by users.
let primary_key_indexes = (0..primary_key_columns.len()).collect();
schema_builder = schema_builder.primary_key_indexes(primary_key_indexes);
for key_col in primary_key_columns {
let col_name = key_col.value.as_str();
let col = columns_by_name
.remove(col_name)
.context(UndefinedColumnInPrimaryKey { name: col_name })?;
schema_builder = schema_builder
.add_key_column(col)
.context(BuildTableSchema)?;
}
// Collect the normal columns.
for normal_col in columns {
let col_name = normal_col.value.as_str();
// Only normal columns are kept in the `columns_by_name`.
if let Some(col) = columns_by_name.remove(col_name) {
schema_builder = schema_builder
.add_normal_column(col)
.context(BuildTableSchema)?;
}
}
schema_builder.build().context(BuildTableSchema)
}
// Find the primary key columns and ensure at most only one exists.
fn find_and_ensure_primary_key_columns(
constraints: &[TableConstraint],
) -> Result<Option<Vec<Ident>>> {
let mut primary_key_columns: Option<Vec<Ident>> = None;
for constraint in constraints {
if let TableConstraint::Unique {
columns,
is_primary,
..
} = constraint
{
if *is_primary {
ensure!(
primary_key_columns.is_none(),
DuplicatePrimaryKey {
first: primary_key_columns.unwrap(),
second: columns.clone()
}
);
primary_key_columns = Some(columns.clone());
}
}
}
Ok(primary_key_columns)
}
// Find the timestamp column and ensure its valid existence (only one).
fn find_and_ensure_timestamp_column(
columns_by_name: &HashMap<&str, ColumnSchema>,
constraints: &[TableConstraint],
) -> Result<Ident> {
let mut timestamp_column_name = None;
for constraint in constraints {
if let TableConstraint::Unique { columns, .. } = constraint {
if parser::is_timestamp_key_constraint(constraint) {
// Only one timestamp key constraint
ensure!(timestamp_column_name.is_none(), InvalidTimestampKey);
// Only one column in constraint
ensure!(columns.len() == 1, InvalidTimestampKey);
let timestamp_ident = columns[0].clone();
let timestamp_column = columns_by_name
.get(timestamp_ident.value.as_str())
.context(TimestampColumnNotFound {
name: ×tamp_ident.value,
})?;
// Ensure the timestamp key's type is timestamp.
ensure!(
timestamp_column.data_type == DatumKind::Timestamp,
InvalidTimestampKey
);
// Ensure the timestamp key is not a tag.
ensure!(
!timestamp_column.is_tag,
TimestampKeyTag {
name: ×tamp_ident.value,
}
);
timestamp_column_name = Some(timestamp_ident);
}
}
}
timestamp_column_name.context(RequireTimestamp)
}
fn create_table_to_plan(&self, stmt: CreateTable) -> Result<Plan> {
ensure!(!stmt.table_name.is_empty(), CreateTableNameEmpty);
debug!("Create table to plan, stmt:{:?}", stmt);
// Build all column schemas.
let mut columns_by_name = stmt
.columns
.iter()
.map(|col| Ok((col.name.value.as_str(), parse_column(col)?)))
.collect::<Result<HashMap<_, _>>>()?;
let mut column_idxs_by_name: HashMap<_, _> = stmt
.columns
.iter()
.enumerate()
.map(|(idx, col)| (col.name.value.as_str(), idx))
.collect();
// Tsid column is a reserved column.
ensure!(
!columns_by_name.contains_key(TSID_COLUMN),
ColumnNameReserved {
name: TSID_COLUMN.to_string(),
}
);
let timestamp_column =
Self::find_and_ensure_timestamp_column(&columns_by_name, &stmt.constraints)?;
let tsid_column = Ident::with_quote(DEFAULT_QUOTE_CHAR, TSID_COLUMN);
let mut columns: Vec<_> = stmt.columns.iter().map(|col| col.name.clone()).collect();
let mut add_tsid_column = || {
columns_by_name.insert(TSID_COLUMN, Self::tsid_column_schema()?);
column_idxs_by_name.insert(TSID_COLUMN, columns.len());
columns.push(tsid_column.clone());
Ok(())
};
let primary_key_columns =
match Self::find_and_ensure_primary_key_columns(&stmt.constraints)? {
Some(primary_key_columns) => {
// Ensure the primary key is defined already.
for col in &primary_key_columns {
let col_name = &col.value;
if col_name == TSID_COLUMN {
// tsid column is a reserved column which can't be
// defined by user, so let's add it manually.
add_tsid_column()?;
}
}
primary_key_columns
}
None => {
// No primary key is provided explicitly, so let's use `(tsid,
// timestamp_key)` as the default primary key.
add_tsid_column()?;
vec![tsid_column, timestamp_column]
}
};
let table_schema = Self::create_table_schema(
&columns,
&primary_key_columns,
columns_by_name,
column_idxs_by_name,
)?;
let partition_info = match stmt.partition {
Some(p) => Some(PartitionParser::parse(p)?),
None => None,
};
let options = parse_options(stmt.options)?;
// ensure default value options are valid
ensure_column_default_value_valid(table_schema.columns(), &self.meta_provider)?;
// TODO: support create table on other catalog/schema
let table_name = stmt.table_name.to_string();
let table_ref = get_table_ref(&table_name);
let table = table_ref.table().to_string();
let plan = CreateTablePlan {
engine: stmt.engine,
if_not_exists: stmt.if_not_exists,
table,
table_schema,
options,
// TODO: sql parse supports `partition by` syntax.
partition_info,
};
debug!("Create table to plan, plan:{:?}", plan);
Ok(Plan::Create(plan))
}
fn drop_table_to_plan(&self, stmt: DropTable) -> Result<Plan> {
debug!("Drop table to plan, stmt:{:?}", stmt);
let (table_name, partition_info) =
if let Some(table) = self.find_table(&stmt.table_name.to_string())? {
let table_name = table.name().to_string();
let partition_info = table.partition_info();
(table_name, partition_info)
} else if stmt.if_exists {
let table_name = stmt.table_name.to_string();
(table_name, None)
} else {
return TableNotFound {
name: stmt.table_name.to_string(),
}
.fail();
};
let plan = DropTablePlan {
engine: stmt.engine,
if_exists: stmt.if_exists,
table: table_name,
partition_info,
};
debug!("Drop table to plan, plan:{:?}", plan);
Ok(Plan::Drop(plan))
}
fn describe_table_to_plan(&self, stmt: DescribeTable) -> Result<Plan> {
let table_name = stmt.table_name.to_string();
let table = self
.find_table(&table_name)?
.context(TableNotFound { name: table_name })?;
Ok(Plan::Describe(DescribeTablePlan { table }))
}
// REQUIRE: SqlStatement must be INSERT stmt
fn insert_to_plan(&self, sql_stmt: SqlStatement) -> Result<Plan> {
match sql_stmt {
SqlStatement::Insert {
table_name,
columns,
source,
..
} => {
let table_name = TableName::from(table_name).to_string();
let table = self
.find_table(&table_name)?
.context(TableNotFound { name: table_name })?;
let schema = table.schema();
// Column name and its index in insert stmt: {column name} => index
let column_names_idx: HashMap<_, _> = columns
.iter()
.enumerate()
.map(|(idx, ident)| (&ident.value, idx))
.collect();
ensure!(
column_names_idx.len() == columns.len(),
InsertDuplicateColumns
);
validate_insert_stmt(table.name(), &schema, &column_names_idx)?;
let df_fields = schema
.columns()
.iter()
.map(|column_schema| {
DFField::new_unqualified(
&column_schema.name,
column_schema.data_type.to_arrow_data_type(),
column_schema.is_nullable,
)
})
.collect::<Vec<_>>();
let df_schema = DFSchema::new_with_metadata(df_fields, HashMap::new())
.context(CreateDatafusionSchema)?;
let df_planner =
SqlToRel::new_with_options(&self.meta_provider, DEFAULT_PARSER_OPTS);
// Index in insert values stmt of each column in table schema
let mut column_index_in_insert = Vec::with_capacity(schema.num_columns());
// Column index in schema to its default-value-expr
let mut default_value_map = BTreeMap::new();
// Check all not null columns are provided in stmt, also init
// `column_index_in_insert`
for (idx, column) in schema.columns().iter().enumerate() {
if let Some(tsid_idx) = schema.index_of_tsid() {
if idx == tsid_idx {
// This is a tsid column.
column_index_in_insert.push(InsertMode::Auto);
continue;
}
}
match column_names_idx.get(&column.name) {
Some(idx_in_insert) => {
// This column in schema is also in insert stmt
column_index_in_insert.push(InsertMode::Direct(*idx_in_insert));
}
None => {
// This column in schema is not in insert stmt
if let Some(expr) = &column.default_value {
let expr = df_planner
.sql_to_expr(
expr.clone(),
&df_schema,
&mut PlannerContext::new(),
)
.context(DatafusionExpr)?;
default_value_map.insert(idx, expr);
column_index_in_insert.push(InsertMode::Auto);
} else if column.is_nullable {
column_index_in_insert.push(InsertMode::Null);
} else {
// Column can not be null and input does not contains that column
return InsertMissingColumn {
table: table.name(),
column: &column.name,
}
.fail();
}
}
}
}
let rows = build_row_group(schema, source, column_index_in_insert)?;
Ok(Plan::Insert(InsertPlan {
table,
rows,
default_value_map,
}))
}
// We already known this stmt is a INSERT stmt
_ => unreachable!(),
}
}
fn alter_modify_setting_to_plan(&self, stmt: AlterModifySetting) -> Result<Plan> {
let table_name = stmt.table_name.to_string();
let table = self