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
use std::collections::HashMap;
use std::sync::Arc;
use std::vec;
use arrow_schema::*;
use datafusion_common::field_not_found;
use sqlparser::ast::ExactNumberInfo;
use sqlparser::ast::TimezoneInfo;
use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};
use sqlparser::ast::{DataType as SQLDataType, Ident, ObjectName, TableAlias};
use datafusion_common::config::ConfigOptions;
use datafusion_common::{unqualified_field_not_found, DFSchema, DataFusionError, Result};
use datafusion_common::{OwnedTableReference, TableReference};
use datafusion_expr::logical_plan::{LogicalPlan, LogicalPlanBuilder};
use datafusion_expr::utils::find_column_exprs;
use datafusion_expr::TableSource;
use datafusion_expr::{col, AggregateUDF, Expr, ScalarUDF, SubqueryAlias};
use crate::utils::make_decimal_type;
pub trait ContextProvider {
fn get_table_provider(&self, name: TableReference) -> Result<Arc<dyn TableSource>>;
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>>;
fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>>;
fn get_variable_type(&self, variable_names: &[String]) -> Option<DataType>;
fn options(&self) -> &ConfigOptions;
}
#[derive(Debug)]
pub struct ParserOptions {
pub parse_float_as_decimal: bool,
pub enable_ident_normalization: bool,
}
impl Default for ParserOptions {
fn default() -> Self {
Self {
parse_float_as_decimal: false,
enable_ident_normalization: true,
}
}
}
#[derive(Debug, Clone)]
pub struct PlannerContext {
pub prepare_param_data_types: Vec<DataType>,
pub ctes: HashMap<String, LogicalPlan>,
pub outer_query_schema: Option<DFSchema>,
}
impl Default for PlannerContext {
fn default() -> Self {
Self::new()
}
}
impl PlannerContext {
pub fn new() -> Self {
Self {
prepare_param_data_types: vec![],
ctes: HashMap::new(),
outer_query_schema: None,
}
}
pub fn new_with_prepare_param_data_types(
prepare_param_data_types: Vec<DataType>,
) -> Self {
Self {
prepare_param_data_types,
ctes: HashMap::new(),
outer_query_schema: None,
}
}
}
pub struct SqlToRel<'a, S: ContextProvider> {
pub(crate) schema_provider: &'a S,
pub(crate) options: ParserOptions,
}
impl<'a, S: ContextProvider> SqlToRel<'a, S> {
pub fn new(schema_provider: &'a S) -> Self {
Self::new_with_options(schema_provider, ParserOptions::default())
}
pub fn new_with_options(schema_provider: &'a S, options: ParserOptions) -> Self {
SqlToRel {
schema_provider,
options,
}
}
pub fn build_schema(&self, columns: Vec<SQLColumnDef>) -> Result<Schema> {
let mut fields = Vec::with_capacity(columns.len());
for column in columns {
let data_type = self.convert_simple_data_type(&column.data_type)?;
let not_nullable = column
.options
.iter()
.any(|x| x.option == ColumnOption::NotNull);
fields.push(Field::new(
normalize_ident(column.name, self.options.enable_ident_normalization),
data_type,
!not_nullable,
));
}
Ok(Schema::new(fields))
}
pub(crate) fn apply_table_alias(
&self,
plan: LogicalPlan,
alias: TableAlias,
) -> Result<LogicalPlan> {
let apply_name_plan = LogicalPlan::SubqueryAlias(SubqueryAlias::try_new(
plan,
normalize_ident(alias.name, self.options.enable_ident_normalization),
)?);
self.apply_expr_alias(apply_name_plan, alias.columns)
}
pub(crate) fn apply_expr_alias(
&self,
plan: LogicalPlan,
idents: Vec<Ident>,
) -> Result<LogicalPlan> {
if idents.is_empty() {
Ok(plan)
} else if idents.len() != plan.schema().fields().len() {
Err(DataFusionError::Plan(format!(
"Source table contains {} columns but only {} names given as column alias",
plan.schema().fields().len(),
idents.len(),
)))
} else {
let fields = plan.schema().fields().clone();
LogicalPlanBuilder::from(plan)
.project(fields.iter().zip(idents.into_iter()).map(|(field, ident)| {
col(field.name()).alias(normalize_ident(
ident,
self.options.enable_ident_normalization,
))
}))?
.build()
}
}
pub(crate) fn validate_schema_satisfies_exprs(
&self,
schema: &DFSchema,
exprs: &[Expr],
) -> Result<()> {
find_column_exprs(exprs)
.iter()
.try_for_each(|col| match col {
Expr::Column(col) => match &col.relation {
Some(r) => {
schema.field_with_qualified_name(r, &col.name)?;
Ok(())
}
None => {
if !schema.fields_with_unqualified_name(&col.name).is_empty() {
Ok(())
} else {
Err(unqualified_field_not_found(col.name.as_str(), schema))
}
}
}
.map_err(|_: DataFusionError| {
field_not_found(col.relation.clone(), col.name.as_str(), schema)
}),
_ => Err(DataFusionError::Internal("Not a column".to_string())),
})
}
pub(crate) fn convert_data_type(&self, sql_type: &SQLDataType) -> Result<DataType> {
match sql_type {
SQLDataType::Array(Some(inner_sql_type)) => {
let data_type = self.convert_simple_data_type(inner_sql_type)?;
Ok(DataType::List(Box::new(Field::new(
"field", data_type, true,
))))
}
SQLDataType::Array(None) => Err(DataFusionError::NotImplemented(
"Arrays with unspecified type is not supported".to_string(),
)),
other => self.convert_simple_data_type(other),
}
}
fn convert_simple_data_type(&self, sql_type: &SQLDataType) -> Result<DataType> {
match sql_type {
SQLDataType::Boolean => Ok(DataType::Boolean),
SQLDataType::TinyInt(_) => Ok(DataType::Int8),
SQLDataType::SmallInt(_) => Ok(DataType::Int16),
SQLDataType::Int(_) | SQLDataType::Integer(_) => Ok(DataType::Int32),
SQLDataType::BigInt(_) => Ok(DataType::Int64),
SQLDataType::UnsignedTinyInt(_) => Ok(DataType::UInt8),
SQLDataType::UnsignedSmallInt(_) => Ok(DataType::UInt16),
SQLDataType::UnsignedInt(_) | SQLDataType::UnsignedInteger(_) => {
Ok(DataType::UInt32)
}
SQLDataType::UnsignedBigInt(_) => Ok(DataType::UInt64),
SQLDataType::Float(_) => Ok(DataType::Float32),
SQLDataType::Real => Ok(DataType::Float32),
SQLDataType::Double | SQLDataType::DoublePrecision => Ok(DataType::Float64),
SQLDataType::Char(_)
| SQLDataType::Varchar(_)
| SQLDataType::Text
| SQLDataType::String => Ok(DataType::Utf8),
SQLDataType::Timestamp(None, tz_info) => {
let tz = if matches!(tz_info, TimezoneInfo::Tz)
|| matches!(tz_info, TimezoneInfo::WithTimeZone)
{
self.schema_provider.options().execution.time_zone.clone()
} else {
None
};
Ok(DataType::Timestamp(TimeUnit::Nanosecond, tz))
}
SQLDataType::Date => Ok(DataType::Date32),
SQLDataType::Time(None, tz_info) => {
if matches!(tz_info, TimezoneInfo::None)
|| matches!(tz_info, TimezoneInfo::WithoutTimeZone)
{
Ok(DataType::Time64(TimeUnit::Nanosecond))
} else {
Err(DataFusionError::NotImplemented(format!(
"Unsupported SQL type {sql_type:?}"
)))
}
}
SQLDataType::Numeric(exact_number_info)
| SQLDataType::Decimal(exact_number_info) => {
let (precision, scale) = match *exact_number_info {
ExactNumberInfo::None => (None, None),
ExactNumberInfo::Precision(precision) => (Some(precision), None),
ExactNumberInfo::PrecisionAndScale(precision, scale) => {
(Some(precision), Some(scale))
}
};
make_decimal_type(precision, scale)
}
SQLDataType::Bytea => Ok(DataType::Binary),
SQLDataType::Nvarchar(_)
| SQLDataType::JSON
| SQLDataType::Uuid
| SQLDataType::Binary(_)
| SQLDataType::Varbinary(_)
| SQLDataType::Blob(_)
| SQLDataType::Datetime(_)
| SQLDataType::Interval
| SQLDataType::Regclass
| SQLDataType::Custom(_, _)
| SQLDataType::Array(_)
| SQLDataType::Enum(_)
| SQLDataType::Set(_)
| SQLDataType::MediumInt(_)
| SQLDataType::UnsignedMediumInt(_)
| SQLDataType::Character(_)
| SQLDataType::CharacterVarying(_)
| SQLDataType::CharVarying(_)
| SQLDataType::CharacterLargeObject(_)
| SQLDataType::CharLargeObject(_)
| SQLDataType::Timestamp(Some(_), _)
| SQLDataType::Time(Some(_), _)
| SQLDataType::Dec(_)
| SQLDataType::BigNumeric(_)
| SQLDataType::BigDecimal(_)
| SQLDataType::Clob(_) => Err(DataFusionError::NotImplemented(format!(
"Unsupported SQL type {sql_type:?}"
))),
}
}
pub(crate) fn object_name_to_table_reference(
&self,
object_name: ObjectName,
) -> Result<OwnedTableReference> {
object_name_to_table_reference(
object_name,
self.options.enable_ident_normalization,
)
}
}
pub fn object_name_to_table_reference(
object_name: ObjectName,
enable_normalization: bool,
) -> Result<OwnedTableReference> {
let ObjectName(idents) = object_name;
idents_to_table_reference(idents, enable_normalization)
}
pub(crate) fn idents_to_table_reference(
idents: Vec<Ident>,
enable_normalization: bool,
) -> Result<OwnedTableReference> {
struct IdentTaker(Vec<Ident>);
impl IdentTaker {
fn take(&mut self, enable_normalization: bool) -> String {
let ident = self.0.pop().expect("no more identifiers");
normalize_ident(ident, enable_normalization)
}
}
let mut taker = IdentTaker(idents);
match taker.0.len() {
1 => {
let table = taker.take(enable_normalization);
Ok(OwnedTableReference::bare(table))
}
2 => {
let table = taker.take(enable_normalization);
let schema = taker.take(enable_normalization);
Ok(OwnedTableReference::partial(schema, table))
}
3 => {
let table = taker.take(enable_normalization);
let schema = taker.take(enable_normalization);
let catalog = taker.take(enable_normalization);
Ok(OwnedTableReference::full(catalog, schema, table))
}
_ => Err(DataFusionError::Plan(format!(
"Unsupported compound identifier '{:?}'",
taker.0,
))),
}
}
pub fn object_name_to_qualifier(
sql_table_name: &ObjectName,
enable_normalization: bool,
) -> String {
let columns = vec!["table_name", "table_schema", "table_catalog"].into_iter();
sql_table_name
.0
.iter()
.rev()
.zip(columns)
.map(|(ident, column_name)| {
format!(
r#"{} = '{}'"#,
column_name,
normalize_ident(ident.clone(), enable_normalization)
)
})
.collect::<Vec<_>>()
.join(" AND ")
}
fn normalize_ident(id: Ident, enable_normalization: bool) -> String {
if enable_normalization {
return crate::utils::normalize_ident(id);
}
id.value
}