forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession_state.rs
More file actions
2513 lines (2235 loc) · 88.1 KB
/
session_state.rs
File metadata and controls
2513 lines (2235 loc) · 88.1 KB
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! [`SessionState`]: information required to run queries in a session
use std::any::Any;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::sync::Arc;
use crate::catalog::{CatalogProviderList, SchemaProvider, TableProviderFactory};
use crate::datasource::file_format::FileFormatFactory;
#[cfg(feature = "sql")]
use crate::datasource::provider_as_source;
use crate::execution::SessionStateDefaults;
use crate::execution::context::{EmptySerializerRegistry, FunctionFactory, QueryPlanner};
use crate::physical_planner::{DefaultPhysicalPlanner, PhysicalPlanner};
use arrow_schema::{DataType, FieldRef};
use datafusion_catalog::MemoryCatalogProviderList;
use datafusion_catalog::information_schema::{
INFORMATION_SCHEMA, InformationSchemaProvider,
};
use datafusion_catalog::{TableFunction, TableFunctionImpl};
use datafusion_common::alias::AliasGenerator;
#[cfg(feature = "sql")]
use datafusion_common::config::Dialect;
use datafusion_common::config::{ConfigExtension, ConfigOptions, TableOptions};
use datafusion_common::display::{PlanType, StringifiedPlan, ToStringifiedPlan};
use datafusion_common::tree_node::TreeNode;
use datafusion_common::{
DFSchema, DataFusionError, ResolvedTableReference, TableReference, config_err,
exec_err, plan_datafusion_err,
};
use datafusion_execution::TaskContext;
use datafusion_execution::config::SessionConfig;
use datafusion_execution::runtime_env::RuntimeEnv;
#[cfg(feature = "sql")]
use datafusion_expr::TableSource;
use datafusion_expr::execution_props::ExecutionProps;
use datafusion_expr::expr_rewriter::FunctionRewrite;
use datafusion_expr::planner::ExprPlanner;
#[cfg(feature = "sql")]
use datafusion_expr::planner::{RelationPlanner, TypePlanner};
use datafusion_expr::registry::{FunctionRegistry, SerializerRegistry};
use datafusion_expr::simplify::SimplifyContext;
use datafusion_expr::{AggregateUDF, Explain, Expr, LogicalPlan, ScalarUDF, WindowUDF};
use datafusion_optimizer::simplify_expressions::ExprSimplifier;
use datafusion_optimizer::{
Analyzer, AnalyzerRule, Optimizer, OptimizerConfig, OptimizerRule,
};
use datafusion_physical_expr::create_physical_expr;
use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
use datafusion_physical_optimizer::PhysicalOptimizerRule;
use datafusion_physical_optimizer::optimizer::PhysicalOptimizer;
use datafusion_physical_plan::ExecutionPlan;
use datafusion_session::Session;
#[cfg(feature = "sql")]
use datafusion_sql::{
parser::{DFParserBuilder, Statement},
planner::{ContextProvider, ParserOptions, PlannerContext, SqlToRel},
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use itertools::Itertools;
use log::{debug, info};
use object_store::ObjectStore;
#[cfg(feature = "sql")]
use sqlparser::{
ast::{Expr as SQLExpr, ExprWithAlias as SQLExprWithAlias},
dialect::dialect_from_str,
};
use url::Url;
use uuid::Uuid;
/// `SessionState` contains all the necessary state to plan and execute queries,
/// such as configuration, functions, and runtime environment. Please see the
/// documentation on [`SessionContext`] for more information.
///
///
/// # Example: `SessionState` from a [`SessionContext`]
///
/// ```
/// use datafusion::prelude::*;
/// let ctx = SessionContext::new();
/// let state = ctx.state();
/// ```
///
/// # Example: `SessionState` via [`SessionStateBuilder`]
///
/// You can also use [`SessionStateBuilder`] to build a `SessionState` object
/// directly:
///
/// ```
/// use datafusion::prelude::*;
/// # use datafusion::{error::Result, assert_batches_eq};
/// # use datafusion::execution::session_state::SessionStateBuilder;
/// # use datafusion_execution::runtime_env::RuntimeEnv;
/// # use std::sync::Arc;
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let state = SessionStateBuilder::new()
/// .with_config(SessionConfig::new())
/// .with_runtime_env(Arc::new(RuntimeEnv::default()))
/// .with_default_features()
/// .build();
/// Ok(())
/// # }
/// ```
///
/// Note that there is no `Default` or `new()` for SessionState,
/// to avoid accidentally running queries or other operations without passing through
/// the [`SessionConfig`] or [`RuntimeEnv`]. See [`SessionStateBuilder`] and
/// [`SessionContext`].
///
/// [`SessionContext`]: crate::execution::context::SessionContext
#[derive(Clone)]
pub struct SessionState {
/// A unique UUID that identifies the session
session_id: String,
/// Responsible for analyzing and rewrite a logical plan before optimization
analyzer: Analyzer,
/// Provides support for customizing the SQL planner, e.g. to add support for custom operators like `->>` or `?`
expr_planners: Vec<Arc<dyn ExprPlanner>>,
#[cfg(feature = "sql")]
relation_planners: Vec<Arc<dyn RelationPlanner>>,
/// Provides support for customizing the SQL type planning
#[cfg(feature = "sql")]
type_planner: Option<Arc<dyn TypePlanner>>,
/// Responsible for optimizing a logical plan
optimizer: Optimizer,
/// Responsible for optimizing a physical execution plan
physical_optimizers: PhysicalOptimizer,
/// Responsible for planning `LogicalPlan`s, and `ExecutionPlan`
query_planner: Arc<dyn QueryPlanner + Send + Sync>,
/// Collection of catalogs containing schemas and ultimately TableProviders
catalog_list: Arc<dyn CatalogProviderList>,
/// Table Functions
table_functions: HashMap<String, Arc<TableFunction>>,
/// Scalar functions that are registered with the context
scalar_functions: HashMap<String, Arc<ScalarUDF>>,
/// Aggregate functions registered in the context
aggregate_functions: HashMap<String, Arc<AggregateUDF>>,
/// Window functions registered in the context
window_functions: HashMap<String, Arc<WindowUDF>>,
/// Deserializer registry for extensions.
serializer_registry: Arc<dyn SerializerRegistry>,
/// Holds registered external FileFormat implementations
file_formats: HashMap<String, Arc<dyn FileFormatFactory>>,
/// Session configuration
config: SessionConfig,
/// Table options
table_options: TableOptions,
/// Execution properties
execution_props: ExecutionProps,
/// TableProviderFactories for different file formats.
///
/// Maps strings like "JSON" to an instance of [`TableProviderFactory`]
///
/// This is used to create [`TableProvider`] instances for the
/// `CREATE EXTERNAL TABLE ... STORED AS <FORMAT>` for custom file
/// formats other than those built into DataFusion
///
/// [`TableProvider`]: crate::catalog::TableProvider
table_factories: HashMap<String, Arc<dyn TableProviderFactory>>,
/// Runtime environment
runtime_env: Arc<RuntimeEnv>,
/// [FunctionFactory] to support pluggable user defined function handler.
///
/// It will be invoked on `CREATE FUNCTION` statements.
/// thus, changing dialect o PostgreSql is required
function_factory: Option<Arc<dyn FunctionFactory>>,
cache_factory: Option<Arc<dyn CacheFactory>>,
/// Cache logical plans of prepared statements for later execution.
/// Key is the prepared statement name.
prepared_plans: HashMap<String, Arc<PreparedPlan>>,
}
impl Debug for SessionState {
/// Prefer having short fields at the top and long vector fields near the end
/// Group fields by
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut debug_struct = f.debug_struct("SessionState");
let ret = debug_struct
.field("session_id", &self.session_id)
.field("config", &self.config)
.field("runtime_env", &self.runtime_env)
.field("catalog_list", &self.catalog_list)
.field("serializer_registry", &self.serializer_registry)
.field("file_formats", &self.file_formats)
.field("execution_props", &self.execution_props)
.field("table_options", &self.table_options)
.field("table_factories", &self.table_factories)
.field("function_factory", &self.function_factory)
.field("cache_factory", &self.cache_factory)
.field("expr_planners", &self.expr_planners);
#[cfg(feature = "sql")]
let ret = ret.field("relation_planners", &self.relation_planners);
#[cfg(feature = "sql")]
let ret = ret.field("type_planner", &self.type_planner);
ret.field("query_planners", &self.query_planner)
.field("analyzer", &self.analyzer)
.field("optimizer", &self.optimizer)
.field("physical_optimizers", &self.physical_optimizers)
.field("table_functions", &self.table_functions)
.field("scalar_functions", &self.scalar_functions)
.field("aggregate_functions", &self.aggregate_functions)
.field("window_functions", &self.window_functions)
.field("prepared_plans", &self.prepared_plans)
.finish()
}
}
#[async_trait]
impl Session for SessionState {
fn session_id(&self) -> &str {
self.session_id()
}
fn config(&self) -> &SessionConfig {
self.config()
}
async fn create_physical_plan(
&self,
logical_plan: &LogicalPlan,
) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
self.create_physical_plan(logical_plan).await
}
fn create_physical_expr(
&self,
expr: Expr,
df_schema: &DFSchema,
) -> datafusion_common::Result<Arc<dyn PhysicalExpr>> {
self.create_physical_expr(expr, df_schema)
}
fn scalar_functions(&self) -> &HashMap<String, Arc<ScalarUDF>> {
&self.scalar_functions
}
fn aggregate_functions(&self) -> &HashMap<String, Arc<AggregateUDF>> {
&self.aggregate_functions
}
fn window_functions(&self) -> &HashMap<String, Arc<WindowUDF>> {
&self.window_functions
}
fn runtime_env(&self) -> &Arc<RuntimeEnv> {
self.runtime_env()
}
fn execution_props(&self) -> &ExecutionProps {
self.execution_props()
}
fn as_any(&self) -> &dyn Any {
self
}
fn table_options(&self) -> &TableOptions {
self.table_options()
}
fn table_options_mut(&mut self) -> &mut TableOptions {
self.table_options_mut()
}
fn task_ctx(&self) -> Arc<TaskContext> {
self.task_ctx()
}
}
impl SessionState {
pub(crate) fn resolve_table_ref(
&self,
table_ref: impl Into<TableReference>,
) -> ResolvedTableReference {
let catalog = &self.config_options().catalog;
table_ref
.into()
.resolve(&catalog.default_catalog, &catalog.default_schema)
}
/// Retrieve the [`SchemaProvider`] for a specific [`TableReference`], if it
/// exists.
pub fn schema_for_ref(
&self,
table_ref: impl Into<TableReference>,
) -> datafusion_common::Result<Arc<dyn SchemaProvider>> {
let resolved_ref = self.resolve_table_ref(table_ref);
if self.config.information_schema() && *resolved_ref.schema == *INFORMATION_SCHEMA
{
return Ok(Arc::new(InformationSchemaProvider::new(Arc::clone(
&self.catalog_list,
))));
}
self.catalog_list
.catalog(&resolved_ref.catalog)
.ok_or_else(|| {
plan_datafusion_err!(
"failed to resolve catalog: {}",
resolved_ref.catalog
)
})?
.schema(&resolved_ref.schema)
.ok_or_else(|| {
plan_datafusion_err!("failed to resolve schema: {}", resolved_ref.schema)
})
}
/// Add `analyzer_rule` to the end of the list of
/// [`AnalyzerRule`]s used to rewrite queries.
pub fn add_analyzer_rule(
&mut self,
analyzer_rule: Arc<dyn AnalyzerRule + Send + Sync>,
) -> &Self {
self.analyzer.rules.push(analyzer_rule);
self
}
// the add_optimizer_rule takes an owned reference
// it should probably be renamed to `with_optimizer_rule` to follow builder style
// and `add_optimizer_rule` that takes &mut self added instead of this
pub(crate) fn append_optimizer_rule(
&mut self,
optimizer_rule: Arc<dyn OptimizerRule + Send + Sync>,
) {
self.optimizer.rules.push(optimizer_rule);
}
/// Removes an optimizer rule by name, returning `true` if it existed.
pub(crate) fn remove_optimizer_rule(&mut self, name: &str) -> bool {
let original_len = self.optimizer.rules.len();
self.optimizer.rules.retain(|r| r.name() != name);
self.optimizer.rules.len() < original_len
}
/// Registers a [`FunctionFactory`] to handle `CREATE FUNCTION` statements
pub fn set_function_factory(&mut self, function_factory: Arc<dyn FunctionFactory>) {
self.function_factory = Some(function_factory);
}
/// Get the function factory
pub fn function_factory(&self) -> Option<&Arc<dyn FunctionFactory>> {
self.function_factory.as_ref()
}
/// Register a [`CacheFactory`] for custom caching strategy
pub fn set_cache_factory(&mut self, cache_factory: Arc<dyn CacheFactory>) {
self.cache_factory = Some(cache_factory);
}
/// Get the cache factory
pub fn cache_factory(&self) -> Option<&Arc<dyn CacheFactory>> {
self.cache_factory.as_ref()
}
/// Get the table factories
pub fn table_factories(&self) -> &HashMap<String, Arc<dyn TableProviderFactory>> {
&self.table_factories
}
/// Get the table factories
pub fn table_factories_mut(
&mut self,
) -> &mut HashMap<String, Arc<dyn TableProviderFactory>> {
&mut self.table_factories
}
/// Parse an SQL string into an DataFusion specific AST
/// [`Statement`]. See [`SessionContext::sql`] for running queries.
///
/// [`SessionContext::sql`]: crate::execution::context::SessionContext::sql
#[cfg(feature = "sql")]
pub fn sql_to_statement(
&self,
sql: &str,
dialect: &Dialect,
) -> datafusion_common::Result<Statement> {
let dialect = dialect_from_str(dialect).ok_or_else(|| {
plan_datafusion_err!(
"Unsupported SQL dialect: {dialect}. Available dialects: \
Generic, MySQL, PostgreSQL, Hive, SQLite, Snowflake, Redshift, \
MsSQL, ClickHouse, BigQuery, Ansi, DuckDB, Databricks."
)
})?;
let recursion_limit = self.config.options().sql_parser.recursion_limit;
let mut statements = DFParserBuilder::new(sql)
.with_dialect(dialect.as_ref())
.with_recursion_limit(recursion_limit)
.build()?
.parse_statements()?;
if statements.len() > 1 {
return datafusion_common::not_impl_err!(
"The context currently only supports a single SQL statement"
);
}
let statement = statements.pop_front().ok_or_else(|| {
plan_datafusion_err!("No SQL statements were provided in the query string")
})?;
Ok(statement)
}
/// parse a sql string into a sqlparser-rs AST [`SQLExpr`].
///
/// See [`Self::create_logical_expr`] for parsing sql to [`Expr`].
#[cfg(feature = "sql")]
pub fn sql_to_expr(
&self,
sql: &str,
dialect: &Dialect,
) -> datafusion_common::Result<SQLExpr> {
self.sql_to_expr_with_alias(sql, dialect).map(|x| x.expr)
}
/// parse a sql string into a sqlparser-rs AST [`SQLExprWithAlias`].
///
/// See [`Self::create_logical_expr`] for parsing sql to [`Expr`].
#[cfg(feature = "sql")]
pub fn sql_to_expr_with_alias(
&self,
sql: &str,
dialect: &Dialect,
) -> datafusion_common::Result<SQLExprWithAlias> {
let dialect = dialect_from_str(dialect).ok_or_else(|| {
plan_datafusion_err!(
"Unsupported SQL dialect: {dialect}. Available dialects: \
Generic, MySQL, PostgreSQL, Hive, SQLite, Snowflake, Redshift, \
MsSQL, ClickHouse, BigQuery, Ansi, DuckDB, Databricks."
)
})?;
let recursion_limit = self.config.options().sql_parser.recursion_limit;
let expr = DFParserBuilder::new(sql)
.with_dialect(dialect.as_ref())
.with_recursion_limit(recursion_limit)
.build()?
.parse_into_expr()?;
Ok(expr)
}
/// Resolve all table references in the SQL statement. Does not include CTE references.
///
/// See [`datafusion_sql::resolve::resolve_table_references`] for more information.
///
/// [`datafusion_sql::resolve::resolve_table_references`]: datafusion_sql::resolve::resolve_table_references
#[cfg(feature = "sql")]
pub fn resolve_table_references(
&self,
statement: &Statement,
) -> datafusion_common::Result<Vec<TableReference>> {
let enable_ident_normalization =
self.config.options().sql_parser.enable_ident_normalization;
let (table_refs, _) = datafusion_sql::resolve::resolve_table_references(
statement,
enable_ident_normalization,
)?;
Ok(table_refs)
}
/// Convert an AST Statement into a LogicalPlan
#[cfg(feature = "sql")]
pub async fn statement_to_plan(
&self,
statement: Statement,
) -> datafusion_common::Result<LogicalPlan> {
let references = self.resolve_table_references(&statement)?;
let mut provider = SessionContextProvider {
state: self,
tables: HashMap::with_capacity(references.len()),
};
for reference in references {
let resolved = self.resolve_table_ref(reference);
if let Entry::Vacant(v) = provider.tables.entry(resolved) {
let resolved = v.key();
if let Ok(schema) = self.schema_for_ref(resolved.clone())
&& let Some(table) = schema.table(&resolved.table).await?
{
v.insert(provider_as_source(table));
}
}
}
let query = SqlToRel::new_with_options(&provider, self.get_parser_options());
query.statement_to_plan(statement)
}
#[cfg(feature = "sql")]
fn get_parser_options(&self) -> ParserOptions {
let sql_parser_options = &self.config.options().sql_parser;
ParserOptions {
parse_float_as_decimal: sql_parser_options.parse_float_as_decimal,
enable_ident_normalization: sql_parser_options.enable_ident_normalization,
enable_options_value_normalization: sql_parser_options
.enable_options_value_normalization,
support_varchar_with_length: sql_parser_options.support_varchar_with_length,
map_string_types_to_utf8view: sql_parser_options.map_string_types_to_utf8view,
collect_spans: sql_parser_options.collect_spans,
default_null_ordering: sql_parser_options
.default_null_ordering
.as_str()
.into(),
}
}
/// Creates a [`LogicalPlan`] from the provided SQL string. This
/// interface will plan any SQL DataFusion supports, including DML
/// like `CREATE TABLE`, and `COPY` (which can write to local
/// files.
///
/// See [`SessionContext::sql`] and
/// [`SessionContext::sql_with_options`] for a higher-level
/// interface that handles DDL and verification of allowed
/// statements.
///
/// [`SessionContext::sql`]: crate::execution::context::SessionContext::sql
/// [`SessionContext::sql_with_options`]: crate::execution::context::SessionContext::sql_with_options
#[cfg(feature = "sql")]
pub async fn create_logical_plan(
&self,
sql: &str,
) -> datafusion_common::Result<LogicalPlan> {
let dialect = self.config.options().sql_parser.dialect;
let statement = self.sql_to_statement(sql, &dialect)?;
let plan = self.statement_to_plan(statement).await?;
Ok(plan)
}
/// Creates a datafusion style AST [`Expr`] from a SQL string.
///
/// See example on [SessionContext::parse_sql_expr](crate::execution::context::SessionContext::parse_sql_expr)
#[cfg(feature = "sql")]
pub fn create_logical_expr(
&self,
sql: &str,
df_schema: &DFSchema,
) -> datafusion_common::Result<Expr> {
let dialect = self.config.options().sql_parser.dialect;
let sql_expr = self.sql_to_expr_with_alias(sql, &dialect)?;
self.create_logical_expr_from_sql_expr(sql_expr, df_schema)
}
/// Creates a datafusion style AST [`Expr`] from a SQL expression.
#[cfg(feature = "sql")]
pub fn create_logical_expr_from_sql_expr(
&self,
sql_expr: SQLExprWithAlias,
df_schema: &DFSchema,
) -> datafusion_common::Result<Expr> {
let provider = SessionContextProvider {
state: self,
tables: HashMap::new(),
};
let query = SqlToRel::new_with_options(&provider, self.get_parser_options());
query.sql_to_expr_with_alias(sql_expr, df_schema, &mut PlannerContext::new())
}
/// Returns the [`Analyzer`] for this session
pub fn analyzer(&self) -> &Analyzer {
&self.analyzer
}
/// Returns the [`Optimizer`] for this session
pub fn optimizer(&self) -> &Optimizer {
&self.optimizer
}
/// Returns the [`ExprPlanner`]s for this session
pub fn expr_planners(&self) -> &[Arc<dyn ExprPlanner>] {
&self.expr_planners
}
#[cfg(feature = "sql")]
/// Returns the registered relation planners in priority order.
pub fn relation_planners(&self) -> &[Arc<dyn RelationPlanner>] {
&self.relation_planners
}
#[cfg(feature = "sql")]
/// Registers a [`RelationPlanner`] to customize SQL relation planning.
///
/// Newly registered planners are given higher priority than existing ones.
pub fn register_relation_planner(
&mut self,
planner: Arc<dyn RelationPlanner>,
) -> datafusion_common::Result<()> {
self.relation_planners.insert(0, planner);
Ok(())
}
/// Returns the [`QueryPlanner`] for this session
pub fn query_planner(&self) -> &Arc<dyn QueryPlanner + Send + Sync> {
&self.query_planner
}
/// Optimizes the logical plan by applying optimizer rules.
pub fn optimize(&self, plan: &LogicalPlan) -> datafusion_common::Result<LogicalPlan> {
if let LogicalPlan::Explain(e) = plan {
let mut stringified_plans = e.stringified_plans.clone();
// analyze & capture output of each rule
let analyzer_result = self.analyzer.execute_and_check(
e.plan.as_ref().clone(),
&self.options(),
|analyzed_plan, analyzer| {
let analyzer_name = analyzer.name().to_string();
let plan_type = PlanType::AnalyzedLogicalPlan { analyzer_name };
stringified_plans.push(analyzed_plan.to_stringified(plan_type));
},
);
let analyzed_plan = match analyzer_result {
Ok(plan) => plan,
Err(DataFusionError::Context(analyzer_name, err)) => {
let plan_type = PlanType::AnalyzedLogicalPlan { analyzer_name };
stringified_plans
.push(StringifiedPlan::new(plan_type, err.to_string()));
return Ok(LogicalPlan::Explain(Explain {
verbose: e.verbose,
plan: Arc::clone(&e.plan),
explain_format: e.explain_format.clone(),
stringified_plans,
schema: Arc::clone(&e.schema),
logical_optimization_succeeded: false,
}));
}
Err(e) => return Err(e),
};
// to delineate the analyzer & optimizer phases in explain output
stringified_plans
.push(analyzed_plan.to_stringified(PlanType::FinalAnalyzedLogicalPlan));
// optimize the child plan, capturing the output of each optimizer
let optimized_plan = self.optimizer.optimize(
analyzed_plan,
self,
|optimized_plan, optimizer| {
let optimizer_name = optimizer.name().to_string();
let plan_type = PlanType::OptimizedLogicalPlan { optimizer_name };
stringified_plans.push(optimized_plan.to_stringified(plan_type));
},
);
let (plan, logical_optimization_succeeded) = match optimized_plan {
Ok(plan) => (Arc::new(plan), true),
Err(DataFusionError::Context(optimizer_name, err)) => {
let plan_type = PlanType::OptimizedLogicalPlan { optimizer_name };
stringified_plans
.push(StringifiedPlan::new(plan_type, err.to_string()));
(Arc::clone(&e.plan), false)
}
Err(e) => return Err(e),
};
Ok(LogicalPlan::Explain(Explain {
verbose: e.verbose,
explain_format: e.explain_format.clone(),
plan,
stringified_plans,
schema: Arc::clone(&e.schema),
logical_optimization_succeeded,
}))
} else {
let analyzed_plan = self.analyzer.execute_and_check(
plan.clone(),
&self.options(),
|_, _| {},
)?;
self.optimizer.optimize(analyzed_plan, self, |_, _| {})
}
}
/// Creates a physical [`ExecutionPlan`] plan from a [`LogicalPlan`].
///
/// Note: this first calls [`Self::optimize`] on the provided
/// plan.
///
/// This function will error for [`LogicalPlan`]s such as catalog DDL like
/// `CREATE TABLE`, which do not have corresponding physical plans and must
/// be handled by another layer, typically [`SessionContext`].
///
/// [`SessionContext`]: crate::execution::context::SessionContext
pub async fn create_physical_plan(
&self,
logical_plan: &LogicalPlan,
) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
let logical_plan = self.optimize(logical_plan)?;
self.query_planner
.create_physical_plan(&logical_plan, self)
.await
}
/// Create a [`PhysicalExpr`] from an [`Expr`] after applying type
/// coercion, and function rewrites.
///
/// Note: The expression is not [simplified] or otherwise optimized:
/// `a = 1 + 2` will not be simplified to `a = 3` as this is a more involved process.
/// See the [expr_api] example for how to simplify expressions.
///
/// # See Also:
/// * [`SessionContext::create_physical_expr`] for a higher-level API
/// * [`create_physical_expr`] for a lower-level API
///
/// [simplified]: datafusion_optimizer::simplify_expressions
/// [expr_api]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/query_planning/expr_api.rs
/// [`SessionContext::create_physical_expr`]: crate::execution::context::SessionContext::create_physical_expr
pub fn create_physical_expr(
&self,
expr: Expr,
df_schema: &DFSchema,
) -> datafusion_common::Result<Arc<dyn PhysicalExpr>> {
let config_options = self.config_options();
let simplify_context = SimplifyContext::builder()
.with_schema(Arc::new(df_schema.clone()))
.with_config_options(Arc::clone(config_options))
.with_query_execution_start_time(
self.execution_props().query_execution_start_time,
)
.build();
let simplifier = ExprSimplifier::new(simplify_context);
// apply type coercion here to ensure types match
let mut expr = simplifier.coerce(expr, df_schema)?;
// rewrite Exprs to functions if necessary
for rewrite in self.analyzer.function_rewrites() {
expr = expr
.transform_up(|expr| rewrite.rewrite(expr, df_schema, config_options))?
.data;
}
create_physical_expr(&expr, df_schema, self.execution_props())
}
/// Return the session ID
pub fn session_id(&self) -> &str {
&self.session_id
}
/// Return the runtime env
pub fn runtime_env(&self) -> &Arc<RuntimeEnv> {
&self.runtime_env
}
/// Return the execution properties
pub fn execution_props(&self) -> &ExecutionProps {
&self.execution_props
}
/// Return mutable execution properties
pub fn execution_props_mut(&mut self) -> &mut ExecutionProps {
&mut self.execution_props
}
/// Return the [`SessionConfig`]
pub fn config(&self) -> &SessionConfig {
&self.config
}
/// Return the mutable [`SessionConfig`].
pub fn config_mut(&mut self) -> &mut SessionConfig {
&mut self.config
}
/// Return the logical optimizers
pub fn optimizers(&self) -> &[Arc<dyn OptimizerRule + Send + Sync>] {
&self.optimizer.rules
}
/// Return the physical optimizers
pub fn physical_optimizers(&self) -> &[Arc<dyn PhysicalOptimizerRule + Send + Sync>] {
&self.physical_optimizers.rules
}
/// return the configuration options
pub fn config_options(&self) -> &Arc<ConfigOptions> {
self.config.options()
}
/// Mark the start of the execution
pub fn mark_start_execution(&mut self) {
let config = Arc::clone(self.config.options());
self.execution_props.mark_start_execution(config);
}
/// Return the table options
pub fn table_options(&self) -> &TableOptions {
&self.table_options
}
/// return the TableOptions options with its extensions
pub fn default_table_options(&self) -> TableOptions {
Session::default_table_options(self)
}
/// Returns a mutable reference to [`TableOptions`]
pub fn table_options_mut(&mut self) -> &mut TableOptions {
&mut self.table_options
}
/// Registers a [`ConfigExtension`] as a table option extension that can be
/// referenced from SQL statements executed against this context.
pub fn register_table_options_extension<T: ConfigExtension>(&mut self, extension: T) {
self.table_options.extensions.insert(extension)
}
/// Adds or updates a [FileFormatFactory] which can be used with COPY TO or
/// CREATE EXTERNAL TABLE statements for reading and writing files of custom
/// formats.
pub fn register_file_format(
&mut self,
file_format: Arc<dyn FileFormatFactory>,
overwrite: bool,
) -> Result<(), DataFusionError> {
let ext = file_format.get_ext().to_lowercase();
match (self.file_formats.entry(ext.clone()), overwrite) {
(Entry::Vacant(e), _) => {
e.insert(file_format);
}
(Entry::Occupied(mut e), true) => {
e.insert(file_format);
}
(Entry::Occupied(_), false) => {
return config_err!(
"File type already registered for extension {ext}. Set overwrite to true to replace this extension."
);
}
};
Ok(())
}
/// Retrieves a [FileFormatFactory] based on file extension which has been registered
/// via SessionContext::register_file_format. Extensions are not case sensitive.
pub fn get_file_format_factory(
&self,
ext: &str,
) -> Option<Arc<dyn FileFormatFactory>> {
self.file_formats.get(&ext.to_lowercase()).cloned()
}
/// Get a new TaskContext to run in this session
pub fn task_ctx(&self) -> Arc<TaskContext> {
Arc::new(TaskContext::from(self))
}
/// Return catalog list
pub fn catalog_list(&self) -> &Arc<dyn CatalogProviderList> {
&self.catalog_list
}
/// Set the catalog list
pub fn register_catalog_list(&mut self, catalog_list: Arc<dyn CatalogProviderList>) {
self.catalog_list = catalog_list;
}
/// Return reference to scalar_functions
pub fn scalar_functions(&self) -> &HashMap<String, Arc<ScalarUDF>> {
&self.scalar_functions
}
/// Return reference to aggregate_functions
pub fn aggregate_functions(&self) -> &HashMap<String, Arc<AggregateUDF>> {
&self.aggregate_functions
}
/// Return reference to window functions
pub fn window_functions(&self) -> &HashMap<String, Arc<WindowUDF>> {
&self.window_functions
}
/// Return reference to table_functions
pub fn table_functions(&self) -> &HashMap<String, Arc<TableFunction>> {
&self.table_functions
}
/// Return [SerializerRegistry] for extensions
pub fn serializer_registry(&self) -> &Arc<dyn SerializerRegistry> {
&self.serializer_registry
}
/// Return version of the cargo package that produced this query
pub fn version(&self) -> &str {
env!("CARGO_PKG_VERSION")
}
/// Register a user defined table function
pub fn register_udtf(&mut self, name: &str, fun: Arc<dyn TableFunctionImpl>) {
self.table_functions.insert(
name.to_owned(),
Arc::new(TableFunction::new(name.to_owned(), fun)),
);
}
/// Deregister a user defined table function
pub fn deregister_udtf(
&mut self,
name: &str,
) -> datafusion_common::Result<Option<Arc<dyn TableFunctionImpl>>> {
let udtf = self.table_functions.remove(name);
Ok(udtf.map(|x| Arc::clone(x.function())))
}
/// Store the logical plan and the parameter types of a prepared statement.
pub(crate) fn store_prepared(
&mut self,
name: String,
fields: Vec<FieldRef>,
plan: Arc<LogicalPlan>,
) -> datafusion_common::Result<()> {
match self.prepared_plans.entry(name) {
Entry::Vacant(e) => {
e.insert(Arc::new(PreparedPlan { fields, plan }));
Ok(())
}
Entry::Occupied(e) => {
exec_err!("Prepared statement '{}' already exists", e.key())
}
}
}
/// Get the prepared plan with the given name.
pub(crate) fn get_prepared(&self, name: &str) -> Option<Arc<PreparedPlan>> {
self.prepared_plans.get(name).map(Arc::clone)
}
/// Remove the prepared plan with the given name.
pub(crate) fn remove_prepared(
&mut self,
name: &str,
) -> datafusion_common::Result<()> {
match self.prepared_plans.remove(name) {
Some(_) => Ok(()),
None => exec_err!("Prepared statement '{}' does not exist", name),
}
}
}
/// A builder to be used for building [`SessionState`]'s. Defaults will
/// be used for all values unless explicitly provided.
///
/// See example on [`SessionState`]
#[derive(Clone)]
pub struct SessionStateBuilder {
session_id: Option<String>,
analyzer: Option<Analyzer>,
expr_planners: Option<Vec<Arc<dyn ExprPlanner>>>,
#[cfg(feature = "sql")]
relation_planners: Option<Vec<Arc<dyn RelationPlanner>>>,
#[cfg(feature = "sql")]
type_planner: Option<Arc<dyn TypePlanner>>,
optimizer: Option<Optimizer>,
physical_optimizers: Option<PhysicalOptimizer>,
query_planner: Option<Arc<dyn QueryPlanner + Send + Sync>>,
catalog_list: Option<Arc<dyn CatalogProviderList>>,
table_functions: Option<HashMap<String, Arc<TableFunction>>>,
scalar_functions: Option<Vec<Arc<ScalarUDF>>>,
aggregate_functions: Option<Vec<Arc<AggregateUDF>>>,
window_functions: Option<Vec<Arc<WindowUDF>>>,
serializer_registry: Option<Arc<dyn SerializerRegistry>>,
file_formats: Option<Vec<Arc<dyn FileFormatFactory>>>,
config: Option<SessionConfig>,
table_options: Option<TableOptions>,
execution_props: Option<ExecutionProps>,
table_factories: Option<HashMap<String, Arc<dyn TableProviderFactory>>>,
runtime_env: Option<Arc<RuntimeEnv>>,
function_factory: Option<Arc<dyn FunctionFactory>>,
cache_factory: Option<Arc<dyn CacheFactory>>,
// fields to support convenience functions
analyzer_rules: Option<Vec<Arc<dyn AnalyzerRule + Send + Sync>>>,