Skip to content

Apache DataFusion SQL Query Engine

Refactor SessionContext, SessionState and SessionConfig to support multi-tenancy configurations - Part 2 (#2029)

mingmwang5936edc2a94d
diff --git a/ballista/rust/core/src/serde/logical_plan/mod.rs b/ballista/rust/core/src/serde/logical_plan/mod.rs
index 2e95c175da..e1fc0a84aa 100644
--- a/ballista/rust/core/src/serde/logical_plan/mod.rs
+++ b/ballista/rust/core/src/serde/logical_plan/mod.rs
@@ -228,6 +228,7 @@ impl AsLogicalPlan for LogicalPlanNode {
};
let object_store = ctx
+ .runtime_env()
.object_store(scan.path.as_str())
.map_err(|e| {
BallistaError::NotImplemented(format!(
@@ -1287,9 +1288,10 @@ mod roundtrip_tests {
let codec: BallistaCodec<protobuf::LogicalPlanNode, protobuf::PhysicalPlanNode> =
BallistaCodec::default();
let custom_object_store = Arc::new(TestObjectStore {});
- ctx.register_object_store("test", custom_object_store.clone());
+ ctx.runtime_env()
+ .register_object_store("test", custom_object_store.clone());
- let (os, _) = ctx.object_store("test://foo.csv")?;
+ let (os, _) = ctx.runtime_env().object_store("test://foo.csv")?;
println!("Object Store {:?}", os);
diff --git a/ballista/rust/core/src/serde/mod.rs b/ballista/rust/core/src/serde/mod.rs
index 19ff22af8e..9e60c1b64b 100644
--- a/ballista/rust/core/src/serde/mod.rs
+++ b/ballista/rust/core/src/serde/mod.rs
@@ -350,6 +350,7 @@ mod tests {
use datafusion::datasource::object_store::local::LocalFileSystem;
use datafusion::error::DataFusionError;
use datafusion::execution::context::{QueryPlanner, SessionState, TaskContext};
+ use datafusion::execution::runtime_env::{RuntimeConfig, RuntimeEnv};
use datafusion::logical_plan::plan::Extension;
use datafusion::logical_plan::{
col, DFSchemaRef, Expr, LogicalPlan, LogicalPlanBuilder, UserDefinedLogicalNode,
@@ -699,10 +700,11 @@ mod tests {
#[tokio::test]
async fn test_extension_plan() -> crate::error::Result<()> {
let store = Arc::new(LocalFileSystem {});
- let config =
- SessionConfig::new().with_query_planner(Arc::new(TopKQueryPlanner {}));
+ let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap());
+ let session_state = SessionState::with_config(SessionConfig::new(), runtime)
+ .with_query_planner(Arc::new(TopKQueryPlanner {}));
- let ctx = SessionContext::with_config(config);
+ let ctx = SessionContext::with_state(session_state);
let scan = LogicalPlanBuilder::scan_csv(
store,
diff --git a/ballista/rust/core/src/serde/physical_plan/from_proto.rs b/ballista/rust/core/src/serde/physical_plan/from_proto.rs
index 79161a315a..97c31b9a9d 100644
--- a/ballista/rust/core/src/serde/physical_plan/from_proto.rs
+++ b/ballista/rust/core/src/serde/physical_plan/from_proto.rs
@@ -29,7 +29,7 @@ use chrono::{TimeZone, Utc};
use datafusion::datasource::object_store::local::LocalFileSystem;
use datafusion::datasource::object_store::{FileMeta, SizedFile};
use datafusion::datasource::PartitionedFile;
-use datafusion::execution::context::SessionState;
+use datafusion::execution::context::ExecutionProps;
use datafusion::physical_plan::file_format::FileScanConfig;
@@ -153,12 +153,12 @@ impl TryFrom<&protobuf::PhysicalExprNode> for Arc<dyn PhysicalExpr> {
.map(|x| x.try_into())
.collect::<Result<Vec<_>, _>>()?;
- // TODO Do not create new the SessionState
- let session_state = SessionState::new();
+ // TODO Do not create new the ExecutionProps
+ let execution_props = ExecutionProps::new();
let fun_expr = functions::create_physical_fun(
&(&scalar_function).into(),
- &session_state.execution_props,
+ &execution_props,
)?;
Arc::new(ScalarFunctionExpr::new(
diff --git a/ballista/rust/core/src/serde/physical_plan/mod.rs b/ballista/rust/core/src/serde/physical_plan/mod.rs
index 936de0e65b..ef42b796cd 100644
--- a/ballista/rust/core/src/serde/physical_plan/mod.rs
+++ b/ballista/rust/core/src/serde/physical_plan/mod.rs
@@ -909,7 +909,7 @@ fn decode_scan_config(
.collect::<Result<Vec<_>, _>>()?;
let object_store = if let Some(file) = file_groups.get(0).and_then(|h| h.get(0)) {
- ctx.object_store(file.file_meta.path())?.0
+ ctx.runtime_env().object_store(file.file_meta.path())?.0
} else {
Arc::new(LocalFileSystem {})
};
diff --git a/ballista/rust/core/src/utils.rs b/ballista/rust/core/src/utils.rs
index a668b7334c..b769cd60b1 100644
--- a/ballista/rust/core/src/utils.rs
+++ b/ballista/rust/core/src/utils.rs
@@ -47,6 +47,7 @@ use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use datafusion::physical_plan::common::batch_byte_size;
use datafusion::physical_plan::empty::EmptyExec;
+use datafusion::execution::runtime_env::{RuntimeConfig, RuntimeEnv};
use datafusion::physical_plan::file_format::{CsvExec, ParquetExec};
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_plan::hash_aggregate::HashAggregateExec;
@@ -234,11 +235,16 @@ pub fn create_df_ctx_with_ballista_query_planner<T: 'static + AsLogicalPlan>(
let scheduler_url = format!("http://{}:{}", scheduler_host, scheduler_port);
let planner: Arc<BallistaQueryPlanner<T>> =
Arc::new(BallistaQueryPlanner::new(scheduler_url, config.clone()));
- let config = SessionConfig::new()
- .with_query_planner(planner)
+
+ let session_config = SessionConfig::new()
.with_target_partitions(config.default_shuffle_partitions())
.with_information_schema(true);
- SessionContext::with_config(config)
+ let session_state = SessionState::with_config(
+ session_config,
+ Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap()),
+ )
+ .with_query_planner(planner);
+ SessionContext::with_state(session_state)
}
pub struct BallistaQueryPlanner<T: AsLogicalPlan> {
diff --git a/ballista/rust/scheduler/src/scheduler_server/mod.rs b/ballista/rust/scheduler/src/scheduler_server/mod.rs
index 6386d6b0c7..37f95b3ad0 100644
--- a/ballista/rust/scheduler/src/scheduler_server/mod.rs
+++ b/ballista/rust/scheduler/src/scheduler_server/mod.rs
@@ -179,13 +179,23 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerServer<T
}
}
-/// Create a DataFusion context that is compatible with Ballista
+/// Create a DataFusion session context that is compatible with Ballista Configuration
pub fn create_datafusion_context(config: &BallistaConfig) -> SessionContext {
let config =
SessionConfig::new().with_target_partitions(config.default_shuffle_partitions());
SessionContext::with_config(config)
}
+/// Update the existing DataFusion session context with Ballista Configuration
+pub fn update_datafusion_context(
+ session_ctx: Arc<SessionContext>,
+ config: &BallistaConfig,
+) -> Arc<SessionContext> {
+ session_ctx.state.write().config.target_partitions =
+ config.default_shuffle_partitions();
+ session_ctx
+}
+
#[cfg(all(test, feature = "sled"))]
mod test {
use std::sync::Arc;
diff --git a/datafusion-proto/src/from_proto.rs b/datafusion-proto/src/from_proto.rs
index 1502f5fe4a..f351aa85c1 100644
--- a/datafusion-proto/src/from_proto.rs
+++ b/datafusion-proto/src/from_proto.rs
@@ -1168,7 +1168,7 @@ pub fn parse_expr(
ExprType::ScalarUdfExpr(protobuf::ScalarUdfExprNode { fun_name, args }) => {
let scalar_fn = ctx
.state
- .lock()
+ .read()
.get_function_meta(fun_name.as_str()).ok_or_else(|| Error::General(format!("invalid aggregate function message, function {} is not registered in the ExecutionContext", fun_name)))?;
Ok(Expr::ScalarUDF {
@@ -1182,7 +1182,7 @@ pub fn parse_expr(
ExprType::AggregateUdfExpr(protobuf::AggregateUdfExprNode { fun_name, args }) => {
let agg_fn = ctx
.state
- .lock()
+ .read()
.get_aggregate_meta(fun_name.as_str()).ok_or_else(|| Error::General(format!("invalid aggregate function message, function {} is not registered in the ExecutionContext", fun_name)))?;
Ok(Expr::AggregateUDF {
diff --git a/datafusion/benches/sort_limit_query_sql.rs b/datafusion/benches/sort_limit_query_sql.rs
index 097191e0f0..7860ebc450 100644
--- a/datafusion/benches/sort_limit_query_sql.rs
+++ b/datafusion/benches/sort_limit_query_sql.rs
@@ -84,7 +84,7 @@ fn create_context() -> Arc<Mutex<SessionContext>> {
rt.block_on(async {
// create local session context
let mut ctx = SessionContext::new();
- ctx.state.lock().config.target_partitions = 1;
+ ctx.state.write().config.target_partitions = 1;
let task_ctx = ctx.task_ctx();
let mem_table = MemTable::load(Arc::new(csv.await), Some(partitions), task_ctx)
diff --git a/datafusion/src/dataframe.rs b/datafusion/src/dataframe.rs
index 263087d9d1..ae2cc76519 100644
--- a/datafusion/src/dataframe.rs
+++ b/datafusion/src/dataframe.rs
@@ -34,13 +34,13 @@ use crate::arrow::datatypes::SchemaRef;
use crate::arrow::util::pretty;
use crate::datasource::TableProvider;
use crate::datasource::TableType;
-use crate::execution::context::{SessionContext, SessionState, TaskContext};
+use crate::execution::context::{SessionState, TaskContext};
use crate::physical_plan::file_format::{plan_to_csv, plan_to_parquet};
use crate::physical_plan::{collect, collect_partitioned};
use crate::physical_plan::{execute_stream, execute_stream_partitioned, ExecutionPlan};
use crate::scalar::ScalarValue;
use crate::sql::utils::find_window_exprs;
-use parking_lot::Mutex;
+use parking_lot::RwLock;
use std::any::Any;
/// DataFrame represents a logical set of rows with the same named columns.
@@ -69,13 +69,13 @@ use std::any::Any;
/// # }
/// ```
pub struct DataFrame {
- session_state: Arc<Mutex<SessionState>>,
+ session_state: Arc<RwLock<SessionState>>,
plan: LogicalPlan,
}
impl DataFrame {
/// Create a new Table based on an existing logical plan
- pub fn new(session_state: Arc<Mutex<SessionState>>, plan: &LogicalPlan) -> Self {
+ pub fn new(session_state: Arc<RwLock<SessionState>>, plan: &LogicalPlan) -> Self {
Self {
session_state,
plan: plan.clone(),
@@ -84,10 +84,9 @@ impl DataFrame {
/// Create a physical plan
pub async fn create_physical_plan(&self) -> Result<Arc<dyn ExecutionPlan>> {
- let state = self.session_state.lock().clone();
- let ctx = SessionContext::from(Arc::new(Mutex::new(state)));
- let plan = ctx.optimize(&self.plan)?;
- ctx.create_physical_plan(&plan).await
+ let state = self.session_state.read().clone();
+ let optimized_plan = state.optimize(&self.plan)?;
+ state.create_physical_plan(&optimized_plan).await
}
/// Filter the DataFrame by column. Returns a new DataFrame only containing the
@@ -351,8 +350,8 @@ impl DataFrame {
/// ```
pub async fn collect(&self) -> Result<Vec<RecordBatch>> {
let plan = self.create_physical_plan().await?;
- let task_ctx = Arc::new(TaskContext::from(&self.session_state.lock().clone()));
- collect(plan, task_ctx).await
+ let task_ctx = Arc::new(TaskContext::from(&self.session_state.read().clone()));
+ Ok(collect(plan, task_ctx).await?)
}
/// Print results.
@@ -406,7 +405,7 @@ impl DataFrame {
/// ```
pub async fn execute_stream(&self) -> Result<SendableRecordBatchStream> {
let plan = self.create_physical_plan().await?;
- let task_ctx = Arc::new(TaskContext::from(&self.session_state.lock().clone()));
+ let task_ctx = Arc::new(TaskContext::from(&self.session_state.read().clone()));
execute_stream(plan, task_ctx).await
}
@@ -426,8 +425,8 @@ impl DataFrame {
/// ```
pub async fn collect_partitioned(&self) -> Result<Vec<Vec<RecordBatch>>> {
let plan = self.create_physical_plan().await?;
- let task_ctx = Arc::new(TaskContext::from(&self.session_state.lock().clone()));
- collect_partitioned(plan, task_ctx).await
+ let task_ctx = Arc::new(TaskContext::from(&self.session_state.read().clone()));
+ Ok(collect_partitioned(plan, task_ctx).await?)
}
/// Executes this DataFrame and returns one stream per partition.
@@ -447,8 +446,8 @@ impl DataFrame {
&self,
) -> Result<Vec<SendableRecordBatchStream>> {
let plan = self.create_physical_plan().await?;
- let task_ctx = Arc::new(TaskContext::from(&self.session_state.lock().clone()));
- execute_stream_partitioned(plan, task_ctx).await
+ let task_ctx = Arc::new(TaskContext::from(&self.session_state.read().clone()));
+ Ok(execute_stream_partitioned(plan, task_ctx).await?)
}
/// Returns the schema describing the output of this DataFrame in terms of columns returned,
@@ -511,7 +510,7 @@ impl DataFrame {
/// # }
/// ```
pub fn registry(&self) -> Arc<dyn FunctionRegistry> {
- let registry = self.session_state.lock().clone();
+ let registry = self.session_state.read().clone();
Arc::new(registry)
}
@@ -563,9 +562,8 @@ impl DataFrame {
/// Write a `DataFrame` to a CSV file.
pub async fn write_csv(&self, path: &str) -> Result<()> {
let plan = self.create_physical_plan().await?;
- let state = self.session_state.lock().clone();
- let ctx = SessionContext::from(Arc::new(Mutex::new(state)));
- plan_to_csv(&ctx, plan, path).await
+ let state = self.session_state.read().clone();
+ plan_to_csv(&state, plan, path).await
}
/// Write a `DataFrame` to a Parquet file.
@@ -575,9 +573,8 @@ impl DataFrame {
writer_properties: Option<WriterProperties>,
) -> Result<()> {
let plan = self.create_physical_plan().await?;
- let state = self.session_state.lock().clone();
- let ctx = SessionContext::from(Arc::new(Mutex::new(state)));
- plan_to_parquet(&ctx, plan, path, writer_properties).await
+ let state = self.session_state.read().clone();
+ plan_to_parquet(&state, plan, path, writer_properties).await
}
}
diff --git a/datafusion/src/datasource/object_store/mod.rs b/datafusion/src/datasource/object_store/mod.rs
index aad70e70a3..3a9da67017 100644
--- a/datafusion/src/datasource/object_store/mod.rs
+++ b/datafusion/src/datasource/object_store/mod.rs
@@ -163,7 +163,7 @@ pub trait ObjectStore: Sync + Send + Debug {
static LOCAL_SCHEME: &str = "file";
-/// A Registry holds all the object stores at runtime with a scheme for each store.
+/// A Registry holds all the object stores at Runtime with a scheme for each store.
/// This allows the user to extend DataFusion with different storage systems such as S3 or HDFS
/// and query data inside these systems.
pub struct ObjectStoreRegistry {
diff --git a/datafusion/src/execution/context.rs b/datafusion/src/execution/context.rs
index 33672ff62e..b484f2565b 100644
--- a/datafusion/src/execution/context.rs
+++ b/datafusion/src/execution/context.rs
@@ -40,9 +40,8 @@ use crate::{
},
};
use log::{debug, trace};
-use parking_lot::Mutex;
+use parking_lot::RwLock;
use std::collections::{HashMap, HashSet};
-use std::path::PathBuf;
use std::string::String;
use std::sync::Arc;
@@ -55,7 +54,6 @@ use crate::catalog::{
};
use crate::dataframe::DataFrame;
use crate::datasource::listing::ListingTableConfig;
-use crate::datasource::object_store::{ObjectStore, ObjectStoreRegistry};
use crate::datasource::TableProvider;
use crate::error::{DataFusionError, Result};
use crate::logical_plan::{
@@ -93,12 +91,7 @@ use chrono::{DateTime, Utc};
use parquet::file::properties::WriterProperties;
use uuid::Uuid;
-use super::{
- disk_manager::DiskManagerConfig,
- memory_manager::MemoryManagerConfig,
- options::{AvroReadOptions, CsvReadOptions},
- DiskManager, MemoryManager,
-};
+use super::options::{AvroReadOptions, CsvReadOptions};
/// SessionContext is the main interface for executing queries with DataFusion. It stands for
/// the connection between user and DataFusion/Ballista cluster.
@@ -145,8 +138,10 @@ use super::{
pub struct SessionContext {
/// Uuid for the session
session_id: String,
- /// Internal state for the context
- pub state: Arc<Mutex<SessionState>>,
+ /// Session start time
+ pub session_start_time: DateTime<Utc>,
+ /// Shared session state for the session
+ pub state: Arc<RwLock<SessionState>>,
}
impl Default for SessionContext {
@@ -156,56 +151,44 @@ impl Default for SessionContext {
}
impl SessionContext {
- /// Creates a new execution context using a default configuration.
+ /// Creates a new execution context using a default session configuration.
pub fn new() -> Self {
Self::with_config(SessionConfig::new())
}
- /// Creates a new session context using the provided configuration.
+ /// Creates a new session context using the provided session configuration.
pub fn with_config(config: SessionConfig) -> Self {
- let catalog_list = Arc::new(MemoryCatalogList::new()) as Arc<dyn CatalogList>;
-
- if config.create_default_catalog_and_schema {
- let default_catalog = MemoryCatalogProvider::new();
-
- default_catalog.register_schema(
- config.default_schema.as_str(),
- Arc::new(MemorySchemaProvider::new()),
- );
-
- let default_catalog: Arc<dyn CatalogProvider> = if config.information_schema {
- Arc::new(CatalogWithInformationSchema::new(
- Arc::downgrade(&catalog_list),
- Arc::new(default_catalog),
- ))
- } else {
- Arc::new(default_catalog)
- };
+ let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap());
+ Self::with_config_rt(config, runtime)
+ }
- catalog_list
- .register_catalog(config.default_catalog.clone(), default_catalog);
+ /// Creates a new session context using the provided configuration and RuntimeEnv.
+ pub fn with_config_rt(config: SessionConfig, runtime: Arc<RuntimeEnv>) -> Self {
+ let state = SessionState::with_config(config, runtime);
+ Self {
+ session_id: state.session_id.clone(),
+ session_start_time: chrono::Utc::now(),
+ state: Arc::new(RwLock::new(state)),
}
+ }
- let runtime_env = Arc::new(RuntimeEnv::new(config.runtime.clone()).unwrap());
- let state = SessionState {
- session_id: Uuid::new_v4().to_string(),
- catalog_list,
- scalar_functions: HashMap::new(),
- aggregate_functions: HashMap::new(),
- config,
- execution_props: ExecutionProps::new(),
- object_store_registry: Arc::new(ObjectStoreRegistry::new()),
- runtime_env,
- };
+ /// Creates a new session context using the provided session state.
+ pub fn with_state(state: SessionState) -> Self {
Self {
session_id: state.session_id.clone(),
- state: Arc::new(Mutex::new(state)),
+ session_start_time: chrono::Utc::now(),
+ state: Arc::new(RwLock::new(state)),
}
}
/// Return the [RuntimeEnv] used to run queries with this [SessionContext]
pub fn runtime_env(&self) -> Arc<RuntimeEnv> {
- self.state.lock().runtime_env.clone()
+ self.state.read().runtime_env.clone()
+ }
+
+ /// Return a copied version of config for this Session
+ pub fn copied_config(&self) -> SessionConfig {
+ self.state.read().config.clone()
}
/// Creates a dataframe that will execute a SQL query.
@@ -246,7 +229,7 @@ impl SessionContext {
format: file_format,
collect_stat: false,
file_extension: file_extension.to_owned(),
- target_partitions: self.state.lock().config.target_partitions,
+ target_partitions: self.copied_config().target_partitions,
table_partition_cols: vec![],
};
@@ -345,7 +328,7 @@ impl SessionContext {
}
// create a query planner
- let state = self.state.lock().clone();
+ let state = self.state.read().clone();
let query_planner = SqlToRel::new(&state);
query_planner.statement_to_plan(statements.pop_front().unwrap())
}
@@ -357,7 +340,7 @@ impl SessionContext {
provider: Arc<dyn VarProvider + Send + Sync>,
) {
self.state
- .lock()
+ .write()
.execution_props
.add_var_provider(variable_type, provider);
}
@@ -371,7 +354,7 @@ impl SessionContext {
/// `SELECT "my_FUNC"(x)` will look for a function named `"my_FUNC"`
pub fn register_udf(&mut self, f: ScalarUDF) {
self.state
- .lock()
+ .write()
.scalar_functions
.insert(f.name.clone(), Arc::new(f));
}
@@ -385,7 +368,7 @@ impl SessionContext {
/// `SELECT "my_UDAF"(x)` will look for an aggregate named `"my_UDAF"`
pub fn register_udaf(&mut self, f: AggregateUDF) {
self.state
- .lock()
+ .write()
.aggregate_functions
.insert(f.name.clone(), Arc::new(f));
}
@@ -398,8 +381,8 @@ impl SessionContext {
options: AvroReadOptions<'_>,
) -> Result<Arc<DataFrame>> {
let uri: String = uri.into();
- let (object_store, path) = self.object_store(&uri)?;
- let target_partitions = self.state.lock().config.target_partitions;
+ let (object_store, path) = self.runtime_env().object_store(&uri)?;
+ let target_partitions = self.copied_config().target_partitions;
Ok(Arc::new(DataFrame::new(
self.state.clone(),
&LogicalPlanBuilder::scan_avro(
@@ -429,8 +412,8 @@ impl SessionContext {
options: CsvReadOptions<'_>,
) -> Result<Arc<DataFrame>> {
let uri: String = uri.into();
- let (object_store, path) = self.object_store(&uri)?;
- let target_partitions = self.state.lock().config.target_partitions;
+ let (object_store, path) = self.runtime_env().object_store(&uri)?;
+ let target_partitions = self.copied_config().target_partitions;
Ok(Arc::new(DataFrame::new(
self.state.clone(),
&LogicalPlanBuilder::scan_csv(
@@ -451,8 +434,8 @@ impl SessionContext {
uri: impl Into<String>,
) -> Result<Arc<DataFrame>> {
let uri: String = uri.into();
- let (object_store, path) = self.object_store(&uri)?;
- let target_partitions = self.state.lock().config.target_partitions;
+ let (object_store, path) = self.runtime_env().object_store(&uri)?;
+ let target_partitions = self.copied_config().target_partitions;
let logical_plan =
LogicalPlanBuilder::scan_parquet(object_store, path, None, target_partitions)
.await?
@@ -481,7 +464,7 @@ impl SessionContext {
options: ListingOptions,
provided_schema: Option<SchemaRef>,
) -> Result<()> {
- let (object_store, path) = self.object_store(uri)?;
+ let (object_store, path) = self.runtime_env().object_store(uri)?;
let resolved_schema = match provided_schema {
None => {
options
@@ -507,7 +490,7 @@ impl SessionContext {
options: CsvReadOptions<'_>,
) -> Result<()> {
let listing_options =
- options.to_listing_options(self.state.lock().config.target_partitions);
+ options.to_listing_options(self.copied_config().target_partitions);
self.register_listing_table(
name,
@@ -524,8 +507,8 @@ impl SessionContext {
/// executed against this context.
pub async fn register_parquet(&mut self, name: &str, uri: &str) -> Result<()> {
let (target_partitions, enable_pruning) = {
- let m = self.state.lock();
- (m.config.target_partitions, m.config.parquet_pruning)
+ let conf = self.copied_config();
+ (conf.target_partitions, conf.parquet_pruning)
};
let file_format = ParquetFormat::default().with_enable_pruning(enable_pruning);
@@ -551,7 +534,7 @@ impl SessionContext {
options: AvroReadOptions<'_>,
) -> Result<()> {
let listing_options =
- options.to_listing_options(self.state.lock().config.target_partitions);
+ options.to_listing_options(self.copied_config().target_partitions);
self.register_listing_table(name, uri, listing_options, options.schema)
.await?;
@@ -570,21 +553,13 @@ impl SessionContext {
catalog: Arc<dyn CatalogProvider>,
) -> Option<Arc<dyn CatalogProvider>> {
let name = name.into();
-
- let state = self.state.lock();
- let catalog = if state.config.information_schema {
- let is = state
- .catalog_list
- .catalog("datafusion")
- .unwrap()
- .schema("information_schema");
- match is {
- Some(_) => catalog,
- None => Arc::new(CatalogWithInformationSchema::new(
- Arc::downgrade(&state.catalog_list),
- catalog,
- )),
- }
+ let information_schema = self.copied_config().information_schema;
+ let state = self.state.read();
+ let catalog = if information_schema {
+ Arc::new(CatalogWithInformationSchema::new(
+ Arc::downgrade(&state.catalog_list),
+ catalog,
+ ))
} else {
catalog
};
@@ -594,36 +569,7 @@ impl SessionContext {
/// Retrieves a `CatalogProvider` instance by name
pub fn catalog(&self, name: &str) -> Option<Arc<dyn CatalogProvider>> {
- self.state.lock().catalog_list.catalog(name)
- }
-
- /// Registers a object store with scheme using a custom `ObjectStore` so that
- /// an external file system or object storage system could be used against this context.
- ///
- /// Returns the `ObjectStore` previously registered for this scheme, if any
- pub fn register_object_store(
- &self,
- scheme: impl Into<String>,
- object_store: Arc<dyn ObjectStore>,
- ) -> Option<Arc<dyn ObjectStore>> {
- let scheme = scheme.into();
-
- self.state
- .lock()
- .object_store_registry
- .register_store(scheme, object_store)
- }
-
- /// Retrieves a `ObjectStore` instance by scheme
- pub fn object_store<'a>(
- &self,
- uri: &'a str,
- ) -> Result<(Arc<dyn ObjectStore>, &'a str)> {
- self.state
- .lock()
- .object_store_registry
- .get_by_uri(uri)
- .map_err(DataFusionError::from)
+ self.state.read().catalog_list.catalog(name)
}
/// Registers a table using a custom `TableProvider` so that
@@ -639,7 +585,7 @@ impl SessionContext {
) -> Result<Option<Arc<dyn TableProvider>>> {
let table_ref = table_ref.into();
self.state
- .lock()
+ .read()
.schema_for_ref(table_ref)?
.register_table(table_ref.table().to_owned(), provider)
}
@@ -653,11 +599,25 @@ impl SessionContext {
) -> Result<Option<Arc<dyn TableProvider>>> {
let table_ref = table_ref.into();
self.state
- .lock()
+ .read()
.schema_for_ref(table_ref)?
.deregister_table(table_ref.table())
}
+ /// Check whether the given table exists in the schema provider or not
+ /// Returns true if the table exists.
+ pub fn table_exist<'a>(
+ &'a self,
+ table_ref: impl Into<TableReference<'a>>,
+ ) -> Result<bool> {
+ let table_ref = table_ref.into();
+ Ok(self
+ .state
+ .read()
+ .schema_for_ref(table_ref)?
+ .table_exist(table_ref.table()))
+ }
+
/// Retrieves a DataFrame representing a table previously registered by calling the
/// register_table function.
///
@@ -667,7 +627,7 @@ impl SessionContext {
table_ref: impl Into<TableReference<'a>>,
) -> Result<Arc<DataFrame>> {
let table_ref = table_ref.into();
- let schema = self.state.lock().schema_for_ref(table_ref)?;
+ let schema = self.state.read().schema_for_ref(table_ref)?;
match schema.table(table_ref.table()) {
Some(ref provider) => {
let plan = LogicalPlanBuilder::scan(
@@ -696,7 +656,7 @@ impl SessionContext {
pub fn tables(&self) -> Result<HashSet<String>> {
Ok(self
.state
- .lock()
+ .read()
// a bare reference will always resolve to the default catalog and schema
.schema_for_ref(TableReference::Bare { table: "" })?
.table_names()
@@ -707,26 +667,7 @@ impl SessionContext {
/// Optimizes the logical plan by applying optimizer rules.
pub fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {
- if let LogicalPlan::Explain(e) = plan {
- let mut stringified_plans = e.stringified_plans.clone();
-
- // optimize the child plan, capturing the output of each optimizer
- let plan =
- self.optimize_internal(e.plan.as_ref(), |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));
- })?;
-
- Ok(LogicalPlan::Explain(Explain {
- verbose: e.verbose,
- plan: Arc::new(plan),
- stringified_plans,
- schema: e.schema.clone(),
- }))
- } else {
- self.optimize_internal(plan, |_, _| {})
- }
+ self.state.read().optimize(plan)
}
/// Creates a physical plan from a logical plan.
@@ -734,8 +675,8 @@ impl SessionContext {
&self,
logical_plan: &LogicalPlan,
) -> Result<Arc<dyn ExecutionPlan>> {
- let (state, planner) = {
- let mut state = self.state.lock();
+ let state_cloned = {
+ let mut state = self.state.write();
state.execution_props.start_execution();
// We need to clone `state` to release the lock that is not `Send`. We could
@@ -747,10 +688,10 @@ impl SessionContext {
// original state after it has been cloned, they will not be picked up by the
// clone but that is okay, as it is equivalent to postponing the state update
// by keeping the lock until the end of the function scope.
- (state.clone(), Arc::clone(&state.config.query_planner))
+ state.clone()
};
- planner.create_physical_plan(logical_plan, &state).await
+ state_cloned.create_physical_plan(logical_plan).await
}
/// Executes a query and writes the results to a partitioned CSV file.
@@ -759,7 +700,8 @@ impl SessionContext {
plan: Arc<dyn ExecutionPlan>,
path: impl AsRef<str>,
) -> Result<()> {
- plan_to_csv(self, plan, path).await
+ let state = self.state.read().clone();
+ plan_to_csv(&state, plan, path).await
}
/// Executes a query and writes the results to a partitioned Parquet file.
@@ -769,35 +711,8 @@ impl SessionContext {
path: impl AsRef<str>,
writer_properties: Option<WriterProperties>,
) -> Result<()> {
- plan_to_parquet(self, plan, path, writer_properties).await
- }
-
- /// Optimizes the logical plan by applying optimizer rules, and
- /// invoking observer function after each call
- fn optimize_internal<F>(
- &self,
- plan: &LogicalPlan,
- mut observer: F,
- ) -> Result<LogicalPlan>
- where
- F: FnMut(&LogicalPlan, &dyn OptimizerRule),
- {
- let state = &mut self.state.lock();
- let execution_props = &mut state.execution_props.clone();
- let optimizers = &state.config.optimizers;
-
- let execution_props = execution_props.start_execution();
-
- let mut new_plan = plan.clone();
- debug!("Input logical plan:\n{}\n", plan.display_indent());
- trace!("Full input logical plan:\n{:?}", plan);
- for optimizer in optimizers {
- new_plan = optimizer.optimize(&new_plan, execution_props)?;
- observer(&new_plan, optimizer.as_ref());
- }
- debug!("Optimized logical plan:\n{}\n", new_plan.display_indent());
- trace!("Full Optimized logical plan:\n {:?}", plan);
- Ok(new_plan)
+ let state = self.state.read().clone();
+ plan_to_parquet(&state, plan, path, writer_properties).await
}
/// Get a new TaskContext to run in this session
@@ -806,24 +721,17 @@ impl SessionContext {
}
}
-impl From<Arc<Mutex<SessionState>>> for SessionContext {
- fn from(state: Arc<Mutex<SessionState>>) -> Self {
- let session_id = state.lock().session_id.clone();
- SessionContext { session_id, state }
- }
-}
-
impl FunctionRegistry for SessionContext {
fn udfs(&self) -> HashSet<String> {
- self.state.lock().udfs()
+ self.state.read().udfs()
}
fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {
- self.state.lock().udf(name)
+ self.state.read().udf(name)
}
fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {
- self.state.lock().udaf(name)
+ self.state.read().udaf(name)
}
}
@@ -856,17 +764,28 @@ impl QueryPlanner for DefaultQueryPlanner {
}
}
-/// Configuration options for execution context
+/// Session Configuration entry name for 'BATCH_SIZE'
+pub const BATCH_SIZE: &str = "batch_size";
+/// Session Configuration entry name for 'TARGET_PARTITIONS'
+pub const TARGET_PARTITIONS: &str = "target_partitions";
+/// Session Configuration entry name for 'REPARTITION_JOINS'
+pub const REPARTITION_JOINS: &str = "repartition_joins";
+/// Session Configuration entry name for 'REPARTITION_AGGREGATIONS'
+pub const REPARTITION_AGGREGATIONS: &str = "repartition_aggregations";
+/// Session Configuration entry name for 'REPARTITION_WINDOWS'
+pub const REPARTITION_WINDOWS: &str = "repartition_windows";
+/// Session Configuration entry name for 'PARQUET_PRUNING'
+pub const PARQUET_PRUNING: &str = "parquet_pruning";
+
+/// Configuration options for session context
#[derive(Clone)]
pub struct SessionConfig {
+ /// Default batch size while creating new batches, it's especially useful
+ /// for buffer-in-memory batches since creating tiny batches would results
+ /// in too much metadata memory consumption.
+ pub batch_size: usize,
/// Number of partitions for query execution. Increasing partitions can increase concurrency.
pub target_partitions: usize,
- /// Responsible for optimizing a logical plan
- optimizers: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
- /// Responsible for optimizing a physical execution plan
- pub physical_optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
- /// Responsible for planning `LogicalPlan`s, and `ExecutionPlan`
- query_planner: Arc<dyn QueryPlanner + Send + Sync>,
/// Default catalog name for table resolution
default_catalog: String,
/// Default schema name for table resolution
@@ -886,39 +805,14 @@ pub struct SessionConfig {
/// parallel using the provided `target_partitions` level
pub repartition_windows: bool,
/// Should DataFusion parquet reader using the predicate to prune data
- parquet_pruning: bool,
- /// Runtime configurations such as memory threshold and local disk for spill
- pub runtime: RuntimeConfig,
+ pub parquet_pruning: bool,
}
impl Default for SessionConfig {
fn default() -> Self {
Self {
+ batch_size: 8192,
target_partitions: num_cpus::get(),
- optimizers: vec![
- // Simplify expressions first to maximize the chance
- // of applying other optimizations
- Arc::new(SimplifyExpressions::new()),
- Arc::new(EliminateFilter::new()),
- Arc::new(CommonSubexprEliminate::new()),
- Arc::new(EliminateLimit::new()),
- Arc::new(ProjectionPushDown::new()),
- Arc::new(FilterPushDown::new()),
- Arc::new(LimitPushDown::new()),
- Arc::new(SingleDistinctToGroupBy::new()),
- // ToApproxPerc must be applied last because
- // it rewrites only the function and may interfere with
- // other rules
- Arc::new(ToApproxPerc::new()),
- ],
- physical_optimizers: vec![
- Arc::new(AggregateStatistics::new()),
- Arc::new(HashBuildProbeOrder::new()),
- Arc::new(CoalesceBatches::new()),
- Arc::new(Repartition::new()),
- Arc::new(AddCoalescePartitionsExec::new()),
- ],
- query_planner: Arc::new(DefaultQueryPlanner {}),
default_catalog: "datafusion".to_owned(),
default_schema: "public".to_owned(),
create_default_catalog_and_schema: true,
@@ -927,7 +821,6 @@ impl Default for SessionConfig {
repartition_aggregations: true,
repartition_windows: true,
parquet_pruning: true,
- runtime: RuntimeConfig::default(),
}
}
}
@@ -938,64 +831,19 @@ impl SessionConfig {
Default::default()
}
- /// Customize target_partitions
- pub fn with_target_partitions(mut self, n: usize) -> Self {
- // partition count must be greater than zero
- assert!(n > 0);
- self.target_partitions = n;
- self
- }
-
/// Customize batch size
pub fn with_batch_size(mut self, n: usize) -> Self {
// batch size must be greater than zero
assert!(n > 0);
- self.runtime.batch_size = n;
+ self.batch_size = n;
self
}
- /// Replace the default query planner
- pub fn with_query_planner(
- mut self,
- query_planner: Arc<dyn QueryPlanner + Send + Sync>,
- ) -> Self {
- self.query_planner = query_planner;
- self
- }
-
- /// Replace the optimizer rules
- pub fn with_optimizer_rules(
- mut self,
- optimizers: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
- ) -> Self {
- self.optimizers = optimizers;
- self
- }
-
- /// Replace the physical optimizer rules
- pub fn with_physical_optimizer_rules(
- mut self,
- physical_optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
- ) -> Self {
- self.physical_optimizers = physical_optimizers;
- self
- }
-
- /// Adds a new [`OptimizerRule`]
- pub fn add_optimizer_rule(
- mut self,
- optimizer_rule: Arc<dyn OptimizerRule + Send + Sync>,
- ) -> Self {
- self.optimizers.push(optimizer_rule);
- self
- }
-
- /// Adds a new [`PhysicalOptimizerRule`]
- pub fn add_physical_optimizer_rule(
- mut self,
- optimizer_rule: Arc<dyn PhysicalOptimizerRule + Send + Sync>,
- ) -> Self {
- self.physical_optimizers.push(optimizer_rule);
+ /// Customize target_partitions
+ pub fn with_target_partitions(mut self, n: usize) -> Self {
+ // partition count must be greater than zero
+ assert!(n > 0);
+ self.target_partitions = n;
self
}
@@ -1045,54 +893,6 @@ impl SessionConfig {
self.parquet_pruning = enabled;
self
}
-
- /// Customize runtime config
- pub fn with_runtime_config(mut self, config: RuntimeConfig) -> Self {
- self.runtime = config;
- self
- }
-
- /// Use an an existing [MemoryManager]
- pub fn with_existing_memory_manager(mut self, existing: Arc<MemoryManager>) -> Self {
- self.runtime = self
- .runtime
- .with_memory_manager(MemoryManagerConfig::new_existing(existing));
- self
- }
-
- /// Specify the total memory to use while running the DataFusion
- /// plan to `max_memory * memory_fraction` in bytes.
- ///
- /// Note DataFusion does not yet respect this limit in all cases.
- pub fn with_memory_limit(
- mut self,
- max_memory: usize,
- memory_fraction: f64,
- ) -> Result<Self> {
- self.runtime =
- self.runtime
- .with_memory_manager(MemoryManagerConfig::try_new_limit(
- max_memory,
- memory_fraction,
- )?);
- Ok(self)
- }
-
- /// Use an an existing [DiskManager]
- pub fn with_existing_disk_manager(mut self, existing: Arc<DiskManager>) -> Self {
- self.runtime = self
- .runtime
- .with_disk_manager(DiskManagerConfig::new_existing(existing));
- self
- }
-
- /// Use the specified path to create any needed temporary files
- pub fn with_temp_file_path(mut self, path: impl Into<PathBuf>) -> Self {
- self.runtime = self
- .runtime
- .with_disk_manager(DiskManagerConfig::new_specified(vec![path.into()]));
- self
- }
}
/// Holds per-execution properties and data (such as starting timestamps, etc).
@@ -1162,41 +962,84 @@ impl ExecutionProps {
pub struct SessionState {
/// Uuid for the session
session_id: String,
+ /// Responsible for optimizing a logical plan
+ pub optimizers: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
+ /// Responsible for optimizing a physical execution plan
+ pub physical_optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
+ /// Responsible for planning `LogicalPlan`s, and `ExecutionPlan`
+ pub query_planner: Arc<dyn QueryPlanner + Send + Sync>,
/// Collection of catalogs containing schemas and ultimately TableProviders
pub catalog_list: Arc<dyn CatalogList>,
/// Scalar functions that are registered with the context
pub scalar_functions: HashMap<String, Arc<ScalarUDF>>,
/// Aggregate functions registered in the context
pub aggregate_functions: HashMap<String, Arc<AggregateUDF>>,
- /// Context configuration
+ /// Session configuration
pub config: SessionConfig,
/// Execution properties
pub execution_props: ExecutionProps,
- /// Object Store that are registered with the context
- pub object_store_registry: Arc<ObjectStoreRegistry>,
/// Runtime environment
pub runtime_env: Arc<RuntimeEnv>,
}
-impl Default for SessionState {
- fn default() -> Self {
- Self::new()
- }
-}
-
impl SessionState {
- /// Returns new SessionState
- pub fn new() -> Self {
+ /// Returns new SessionState using the provided configuration and runtime
+ pub fn with_config(config: SessionConfig, runtime: Arc<RuntimeEnv>) -> Self {
let session_id = Uuid::new_v4().to_string();
+
+ let catalog_list = Arc::new(MemoryCatalogList::new()) as Arc<dyn CatalogList>;
+ if config.create_default_catalog_and_schema {
+ let default_catalog = MemoryCatalogProvider::new();
+
+ default_catalog.register_schema(
+ &config.default_schema,
+ Arc::new(MemorySchemaProvider::new()),
+ );
+
+ let default_catalog: Arc<dyn CatalogProvider> = if config.information_schema {
+ Arc::new(CatalogWithInformationSchema::new(
+ Arc::downgrade(&catalog_list),
+ Arc::new(default_catalog),
+ ))
+ } else {
+ Arc::new(default_catalog)
+ };
+ catalog_list
+ .register_catalog(config.default_catalog.clone(), default_catalog);
+ }
+
SessionState {
session_id,
- catalog_list: Arc::new(MemoryCatalogList::new()),
+ optimizers: vec![
+ // Simplify expressions first to maximize the chance
+ // of applying other optimizations
+ Arc::new(SimplifyExpressions::new()),
+ Arc::new(EliminateFilter::new()),
+ Arc::new(CommonSubexprEliminate::new()),
+ Arc::new(EliminateLimit::new()),
+ Arc::new(ProjectionPushDown::new()),
+ Arc::new(FilterPushDown::new()),
+ Arc::new(LimitPushDown::new()),
+ Arc::new(SingleDistinctToGroupBy::new()),
+ // ToApproxPerc must be applied last because
+ // it rewrites only the function and may interfere with
+ // other rules
+ Arc::new(ToApproxPerc::new()),
+ ],
+ physical_optimizers: vec![
+ Arc::new(AggregateStatistics::new()),
+ Arc::new(HashBuildProbeOrder::new()),
+ Arc::new(CoalesceBatches::new()),
+ Arc::new(Repartition::new()),
+ Arc::new(AddCoalescePartitionsExec::new()),
+ ],
+ query_planner: Arc::new(DefaultQueryPlanner {}),
+ catalog_list,
scalar_functions: HashMap::new(),
aggregate_functions: HashMap::new(),
- config: SessionConfig::new(),
+ config,
execution_props: ExecutionProps::new(),
- object_store_registry: Arc::new(ObjectStoreRegistry::new()),
- runtime_env: Arc::new(RuntimeEnv::default()),
+ runtime_env: runtime,
}
}
@@ -1213,7 +1056,7 @@ impl SessionState {
&'a self,
table_ref: impl Into<TableReference<'a>>,
) -> Result<Arc<dyn SchemaProvider>> {
- let resolved_ref = self.resolve_table_ref(table_ref.into());
+ let resolved_ref = self.resolve_table_ref(table_ref);
self.catalog_list
.catalog(resolved_ref.catalog)
@@ -1231,6 +1074,111 @@ impl SessionState {
))
})
}
+
+ /// Replace the default query planner
+ pub fn with_query_planner(
+ mut self,
+ query_planner: Arc<dyn QueryPlanner + Send + Sync>,
+ ) -> Self {
+ self.query_planner = query_planner;
+ self
+ }
+
+ /// Replace the optimizer rules
+ pub fn with_optimizer_rules(
+ mut self,
+ optimizers: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
+ ) -> Self {
+ self.optimizers = optimizers;
+ self
+ }
+
+ /// Replace the physical optimizer rules
+ pub fn with_physical_optimizer_rules(
+ mut self,
+ physical_optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
+ ) -> Self {
+ self.physical_optimizers = physical_optimizers;
+ self
+ }
+
+ /// Adds a new [`OptimizerRule`]
+ pub fn add_optimizer_rule(
+ mut self,
+ optimizer_rule: Arc<dyn OptimizerRule + Send + Sync>,
+ ) -> Self {
+ self.optimizers.push(optimizer_rule);
+ self
+ }
+
+ /// Adds a new [`PhysicalOptimizerRule`]
+ pub fn add_physical_optimizer_rule(
+ mut self,
+ optimizer_rule: Arc<dyn PhysicalOptimizerRule + Send + Sync>,
+ ) -> Self {
+ self.physical_optimizers.push(optimizer_rule);
+ self
+ }
+
+ /// Optimizes the logical plan by applying optimizer rules.
+ pub fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {
+ if let LogicalPlan::Explain(e) = plan {
+ let mut stringified_plans = e.stringified_plans.clone();
+
+ // optimize the child plan, capturing the output of each optimizer
+ let plan =
+ self.optimize_internal(e.plan.as_ref(), |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));
+ })?;
+
+ Ok(LogicalPlan::Explain(Explain {
+ verbose: e.verbose,
+ plan: Arc::new(plan),
+ stringified_plans,
+ schema: e.schema.clone(),
+ }))
+ } else {
+ self.optimize_internal(plan, |_, _| {})
+ }
+ }
+
+ /// Optimizes the logical plan by applying optimizer rules, and
+ /// invoking observer function after each call
+ fn optimize_internal<F>(
+ &self,
+ plan: &LogicalPlan,
+ mut observer: F,
+ ) -> Result<LogicalPlan>
+ where
+ F: FnMut(&LogicalPlan, &dyn OptimizerRule),
+ {
+ let execution_props = &mut self.execution_props.clone();
+ let optimizers = &self.optimizers;
+
+ let execution_props = execution_props.start_execution();
+
+ let mut new_plan = plan.clone();
+ debug!("Input logical plan:\n{}\n", plan.display_indent());
+ trace!("Full input logical plan:\n{:?}", plan);
+ for optimizer in optimizers {
+ new_plan = optimizer.optimize(&new_plan, execution_props)?;
+ observer(&new_plan, optimizer.as_ref());
+ }
+ debug!("Optimized logical plan:\n{}\n", new_plan.display_indent());
+ trace!("Full Optimized logical plan:\n {:?}", plan);
+ Ok(new_plan)
+ }
+
+ /// Creates a physical plan from a logical plan.
+ pub async fn create_physical_plan(
+ &self,
+ logical_plan: &LogicalPlan,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ let planner = self.query_planner.clone();
+ planner.create_physical_plan(logical_plan, self).await
+ }
}
impl ContextProvider for SessionState {
@@ -1308,8 +1256,8 @@ pub struct TaskContext {
pub session_id: String,
/// Optional Task Identify
pub task_id: Option<String>,
- /// Task settings
- pub task_settings: TaskProperties,
+ /// Task properties
+ pub properties: TaskProperties,
/// Runtime environment associated with this task context
pub runtime: Arc<RuntimeEnv>,
}
@@ -1325,23 +1273,54 @@ impl TaskContext {
Self {
task_id: Some(task_id),
session_id,
- task_settings: TaskProperties::KVPairs(task_settings),
+ properties: TaskProperties::KVPairs(task_settings),
runtime,
}
}
+
+ /// Return the SessionConfig associated with the Task
+ pub fn session_config(&self) -> SessionConfig {
+ let task_props = &self.properties;
+ match task_props {
+ TaskProperties::KVPairs(props) => {
+ let session_config = SessionConfig::new();
+ session_config
+ .with_batch_size(props.get(BATCH_SIZE).unwrap().parse().unwrap())
+ .with_target_partitions(
+ props.get(TARGET_PARTITIONS).unwrap().parse().unwrap(),
+ )
+ .with_repartition_joins(
+ props.get(REPARTITION_JOINS).unwrap().parse().unwrap(),
+ )
+ .with_repartition_aggregations(
+ props
+ .get(REPARTITION_AGGREGATIONS)
+ .unwrap()
+ .parse()
+ .unwrap(),
+ )
+ .with_repartition_windows(
+ props.get(REPARTITION_WINDOWS).unwrap().parse().unwrap(),
+ )
+ .with_parquet_pruning(
+ props.get(PARQUET_PRUNING).unwrap().parse().unwrap(),
+ )
+ }
+ TaskProperties::SessionConfig(session_config) => session_config.clone(),
+ }
+ }
}
/// Create a new task context instance from SessionContext
impl From<&SessionContext> for TaskContext {
fn from(session: &SessionContext) -> Self {
- let state_clone = session.state.lock().clone();
let session_id = session.session_id.clone();
- let config = state_clone.config;
+ let config = session.state.read().config.clone();
let runtime = session.runtime_env();
Self {
task_id: None,
session_id,
- task_settings: TaskProperties::SessionConfig(config),
+ properties: TaskProperties::SessionConfig(config),
runtime,
}
}
@@ -1356,7 +1335,7 @@ impl From<&SessionState> for TaskContext {
Self {
task_id: None,
session_id,
- task_settings: TaskProperties::SessionConfig(config),
+ properties: TaskProperties::SessionConfig(config),
runtime,
}
}
@@ -1402,11 +1381,9 @@ mod tests {
// configure with same memory / disk manager
let memory_manager = ctx1.runtime_env().memory_manager.clone();
let disk_manager = ctx1.runtime_env().disk_manager.clone();
- let config = SessionConfig::new()
- .with_existing_memory_manager(memory_manager.clone())
- .with_existing_disk_manager(disk_manager.clone());
- let ctx2 = SessionContext::with_config(config);
+ let ctx2 =
+ SessionContext::with_config_rt(SessionConfig::new(), ctx1.runtime_env());
assert!(std::ptr::eq(
Arc::as_ptr(&memory_manager),
@@ -2904,9 +2881,10 @@ mod tests {
#[tokio::test]
async fn custom_query_planner() -> Result<()> {
- let mut ctx = SessionContext::with_config(
- SessionConfig::new().with_query_planner(Arc::new(MyQueryPlanner {})),
- );
+ let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap());
+ let session_state = SessionState::with_config(SessionConfig::new(), runtime)
+ .with_query_planner(Arc::new(MyQueryPlanner {}));
+ let mut ctx = SessionContext::with_state(session_state);
let df = ctx.sql("SELECT 1").await?;
df.collect().await.expect_err("query not supported");
@@ -3023,7 +3001,7 @@ mod tests {
ctx.register_catalog("my_catalog", catalog);
let catalog_list_weak = {
- let state = ctx.state.lock();
+ let state = ctx.state.read();
Arc::downgrade(&state.catalog_list)
};
diff --git a/datafusion/src/execution/runtime_env.rs b/datafusion/src/execution/runtime_env.rs
index e993b385ec..b5925d24f8 100644
--- a/datafusion/src/execution/runtime_env.rs
+++ b/datafusion/src/execution/runtime_env.rs
@@ -15,8 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-//! Execution runtime environment that tracks memory, disk and various configurations
-//! that are used during physical plan execution.
+//! Execution runtime environment that holds object Store, memory manager, disk manager
+//! and various system level components that are used during physical plan execution.
use crate::{
error::Result,
@@ -26,19 +26,21 @@ use crate::{
},
};
+use crate::datasource::object_store::{ObjectStore, ObjectStoreRegistry};
+use datafusion_common::DataFusionError;
use std::fmt::{Debug, Formatter};
+use std::path::PathBuf;
use std::sync::Arc;
#[derive(Clone)]
-/// Execution runtime environment. This structure is passed to the
-/// physical plans when they are run.
+/// Execution runtime environment.
pub struct RuntimeEnv {
- /// Default batch size while creating new batches
- pub batch_size: usize,
/// Runtime memory management
pub memory_manager: Arc<MemoryManager>,
/// Manage temporary files during query execution
pub disk_manager: Arc<DiskManager>,
+ /// Object Store Registry
+ pub object_store_registry: Arc<ObjectStoreRegistry>,
}
impl Debug for RuntimeEnv {
@@ -51,23 +53,17 @@ impl RuntimeEnv {
/// Create env based on configuration
pub fn new(config: RuntimeConfig) -> Result<Self> {
let RuntimeConfig {
- batch_size,
memory_manager,
disk_manager,
} = config;
Ok(Self {
- batch_size,
memory_manager: MemoryManager::new(memory_manager),
disk_manager: DiskManager::try_new(disk_manager)?,
+ object_store_registry: Arc::new(ObjectStoreRegistry::new()),
})
}
- /// Get execution batch size based on config
- pub fn batch_size(&self) -> usize {
- self.batch_size
- }
-
/// Register the consumer to get it tracked
pub fn register_requester(&self, id: &MemoryConsumerId) {
self.memory_manager.register_requester(id);
@@ -87,6 +83,30 @@ impl RuntimeEnv {
pub fn shrink_tracker_usage(&self, delta: usize) {
self.memory_manager.shrink_tracker_usage(delta)
}
+
+ /// Registers a object store with scheme using a custom `ObjectStore` so that
+ /// an external file system or object storage system could be used against this context.
+ ///
+ /// Returns the `ObjectStore` previously registered for this scheme, if any
+ pub fn register_object_store(
+ &self,
+ scheme: impl Into<String>,
+ object_store: Arc<dyn ObjectStore>,
+ ) -> Option<Arc<dyn ObjectStore>> {
+ let scheme = scheme.into();
+ self.object_store_registry
+ .register_store(scheme, object_store)
+ }
+
+ /// Retrieves a `ObjectStore` instance by scheme
+ pub fn object_store<'a>(
+ &self,
+ uri: &'a str,
+ ) -> Result<(Arc<dyn ObjectStore>, &'a str)> {
+ self.object_store_registry
+ .get_by_uri(uri)
+ .map_err(DataFusionError::from)
+ }
}
impl Default for RuntimeEnv {
@@ -95,13 +115,9 @@ impl Default for RuntimeEnv {
}
}
-#[derive(Clone)]
+#[derive(Clone, Default)]
/// Execution runtime configuration
pub struct RuntimeConfig {
- /// Default batch size while creating new batches, it's especially useful
- /// for buffer-in-memory batches since creating tiny batches would results
- /// in too much metadata memory consumption.
- pub batch_size: usize,
/// DiskManager to manage temporary disk file usage
pub disk_manager: DiskManagerConfig,
/// MemoryManager to limit access to memory
@@ -114,14 +130,6 @@ impl RuntimeConfig {
Default::default()
}
- /// Customize batch size
- pub fn with_batch_size(mut self, n: usize) -> Self {
- // batch size must be greater than zero
- assert!(n > 0);
- self.batch_size = n;
- self
- }
-
/// Customize disk manager
pub fn with_disk_manager(mut self, disk_manager: DiskManagerConfig) -> Self {
self.disk_manager = disk_manager;
@@ -133,14 +141,19 @@ impl RuntimeConfig {
self.memory_manager = memory_manager;
self
}
-}
-impl Default for RuntimeConfig {
- fn default() -> Self {
- Self {
- batch_size: 8192,
- disk_manager: DiskManagerConfig::default(),
- memory_manager: MemoryManagerConfig::default(),
- }
+ /// Specify the total memory to use while running the DataFusion
+ /// plan to `max_memory * memory_fraction` in bytes.
+ ///
+ /// Note DataFusion does not yet respect this limit in all cases.
+ pub fn with_memory_limit(self, max_memory: usize, memory_fraction: f64) -> Self {
+ self.with_memory_manager(
+ MemoryManagerConfig::try_new_limit(max_memory, memory_fraction).unwrap(),
+ )
+ }
+
+ /// Use the specified path to create any needed temporary files
+ pub fn with_temp_file_path(self, path: impl Into<PathBuf>) -> Self {
+ self.with_disk_manager(DiskManagerConfig::new_specified(vec![path.into()]))
}
}
diff --git a/datafusion/src/physical_optimizer/aggregate_statistics.rs b/datafusion/src/physical_optimizer/aggregate_statistics.rs
index 8a7d790b4e..9af053f934 100644
--- a/datafusion/src/physical_optimizer/aggregate_statistics.rs
+++ b/datafusion/src/physical_optimizer/aggregate_statistics.rs
@@ -297,7 +297,7 @@ mod tests {
) -> Result<()> {
let session_ctx = SessionContext::new();
let task_ctx = session_ctx.task_ctx();
- let conf = session_ctx.state.lock().clone().config;
+ let conf = session_ctx.copied_config();
let optimized = AggregateStatistics::new().optimize(Arc::new(plan), &conf)?;
let (col, count) = match nulls {
diff --git a/datafusion/src/physical_optimizer/coalesce_batches.rs b/datafusion/src/physical_optimizer/coalesce_batches.rs
index fbfca7b439..4c9edb4525 100644
--- a/datafusion/src/physical_optimizer/coalesce_batches.rs
+++ b/datafusion/src/physical_optimizer/coalesce_batches.rs
@@ -75,7 +75,7 @@ impl PhysicalOptimizerRule for CoalesceBatches {
// we should do that once https://issues.apache.org/jira/browse/ARROW-11059 is
// implemented. For now, we choose half the configured batch size to avoid copies
// when a small number of rows are removed from a batch
- let target_batch_size = config.runtime.batch_size / 2;
+ let target_batch_size = config.batch_size / 2;
Arc::new(CoalesceBatchesExec::new(plan.clone(), target_batch_size))
} else {
plan.clone()
diff --git a/datafusion/src/physical_plan/file_format/avro.rs b/datafusion/src/physical_plan/file_format/avro.rs
index 89cae4e143..3ee23a95af 100644
--- a/datafusion/src/physical_plan/file_format/avro.rs
+++ b/datafusion/src/physical_plan/file_format/avro.rs
@@ -120,7 +120,7 @@ impl ExecutionPlan for AvroExec {
) -> Result<SendableRecordBatchStream> {
let proj = self.base_config.projected_file_column_names();
- let batch_size = context.runtime.batch_size();
+ let batch_size = context.session_config().batch_size;
let file_schema = Arc::clone(&self.base_config.file_schema);
// The avro reader cannot limit the number of records, so `remaining` is ignored.
diff --git a/datafusion/src/physical_plan/file_format/csv.rs b/datafusion/src/physical_plan/file_format/csv.rs
index 0f38291e5e..37418b0e97 100644
--- a/datafusion/src/physical_plan/file_format/csv.rs
+++ b/datafusion/src/physical_plan/file_format/csv.rs
@@ -18,7 +18,7 @@
//! Execution plan for reading CSV files
use crate::error::{DataFusionError, Result};
-use crate::execution::context::{SessionContext, TaskContext};
+use crate::execution::context::{SessionState, TaskContext};
use crate::physical_plan::expressions::PhysicalSortExpr;
use crate::physical_plan::{
DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,
@@ -124,7 +124,7 @@ impl ExecutionPlan for CsvExec {
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
- let batch_size = context.runtime.batch_size();
+ let batch_size = context.session_config().batch_size;
let file_schema = Arc::clone(&self.base_config.file_schema);
let file_projection = self.base_config.file_column_projection_indices();
let has_header = self.has_header;
@@ -180,7 +180,7 @@ impl ExecutionPlan for CsvExec {
}
pub async fn plan_to_csv(
- context: &SessionContext,
+ state: &SessionState,
plan: Arc<dyn ExecutionPlan>,
path: impl AsRef<str>,
) -> Result<()> {
@@ -196,7 +196,7 @@ pub async fn plan_to_csv(
let path = fs_path.join(&filename);
let file = fs::File::create(path)?;
let mut writer = csv::Writer::new(file);
- let task_ctx = context.task_ctx();
+ let task_ctx = Arc::new(TaskContext::from(state));
let stream = plan.execute(i, task_ctx).await?;
let handle: JoinHandle<Result<()>> = task::spawn(async move {
stream
diff --git a/datafusion/src/physical_plan/file_format/json.rs b/datafusion/src/physical_plan/file_format/json.rs
index 9c3a2e1eca..52a9e9f99c 100644
--- a/datafusion/src/physical_plan/file_format/json.rs
+++ b/datafusion/src/physical_plan/file_format/json.rs
@@ -99,7 +99,7 @@ impl ExecutionPlan for NdJsonExec {
) -> Result<SendableRecordBatchStream> {
let proj = self.base_config.projected_file_column_names();
- let batch_size = context.runtime.batch_size();
+ let batch_size = context.session_config().batch_size;
let file_schema = Arc::clone(&self.base_config.file_schema);
// The json reader cannot limit the number of records, so `remaining` is ignored.
diff --git a/datafusion/src/physical_plan/file_format/parquet.rs b/datafusion/src/physical_plan/file_format/parquet.rs
index c20d0f563b..54dfb92b7c 100644
--- a/datafusion/src/physical_plan/file_format/parquet.rs
+++ b/datafusion/src/physical_plan/file_format/parquet.rs
@@ -27,7 +27,7 @@ use std::{any::Any, convert::TryInto};
use crate::datasource::file_format::parquet::ChunkObjectReader;
use crate::datasource::object_store::ObjectStore;
use crate::datasource::PartitionedFile;
-use crate::execution::context::{SessionContext, TaskContext};
+use crate::execution::context::{SessionState, TaskContext};
use crate::physical_plan::expressions::PhysicalSortExpr;
use crate::{
error::{DataFusionError, Result},
@@ -225,7 +225,7 @@ impl ExecutionPlan for ParquetExec {
None => (0..self.base_config.file_schema.fields().len()).collect(),
};
let pruning_predicate = self.pruning_predicate.clone();
- let batch_size = context.runtime.batch_size();
+ let batch_size = context.session_config().batch_size;
let limit = self.base_config.limit;
let object_store = Arc::clone(&self.base_config.object_store);
let partition_col_proj = PartitionColumnProjector::new(
@@ -527,7 +527,7 @@ fn read_partition(
/// Executes a query and writes the results to a partitioned Parquet file.
pub async fn plan_to_parquet(
- context: &SessionContext,
+ state: &SessionState,
plan: Arc<dyn ExecutionPlan>,
path: impl AsRef<str>,
writer_properties: Option<WriterProperties>,
@@ -548,7 +548,7 @@ pub async fn plan_to_parquet(
plan.schema(),
writer_properties.clone(),
)?;
- let task_ctx = context.task_ctx();
+ let task_ctx = Arc::new(TaskContext::from(state));
let stream = plan.execute(i, task_ctx).await?;
let handle: JoinHandle<Result<()>> = task::spawn(async move {
stream
@@ -588,7 +588,7 @@ mod tests {
use super::*;
use crate::execution::options::CsvReadOptions;
- use crate::prelude::SessionConfig;
+ use crate::prelude::{SessionConfig, SessionContext};
use arrow::array::Float32Array;
use arrow::{
array::{Int64Array, Int8Array, StringArray},
diff --git a/datafusion/src/physical_plan/planner.rs b/datafusion/src/physical_plan/planner.rs
index afe41600de..ee4494cf58 100644
--- a/datafusion/src/physical_plan/planner.rs
+++ b/datafusion/src/physical_plan/planner.rs
@@ -1408,7 +1408,7 @@ impl DefaultPhysicalPlanner {
where
F: FnMut(&dyn ExecutionPlan, &dyn PhysicalOptimizerRule),
{
- let optimizers = &session_state.config.physical_optimizers;
+ let optimizers = &session_state.physical_optimizers;
debug!(
"Input physical plan:\n{}\n",
displayable(plan.as_ref()).indent()
@@ -1444,10 +1444,12 @@ mod tests {
use crate::datasource::object_store::local::LocalFileSystem;
use crate::execution::context::TaskContext;
use crate::execution::options::CsvReadOptions;
+ use crate::execution::runtime_env::{RuntimeConfig, RuntimeEnv};
use crate::logical_plan::plan::Extension;
use crate::physical_plan::{
expressions, DisplayFormatType, Partitioning, Statistics,
};
+ use crate::prelude::SessionConfig;
use crate::scalar::ScalarValue;
use crate::{
logical_plan::LogicalPlanBuilder, physical_plan::SendableRecordBatchStream,
@@ -1463,7 +1465,8 @@ mod tests {
use std::{any::Any, fmt};
fn make_session_state() -> SessionState {
- SessionState::new()
+ let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap());
+ SessionState::with_config(SessionConfig::new(), runtime)
}
async fn plan(logical_plan: &LogicalPlan) -> Result<Arc<dyn ExecutionPlan>> {
diff --git a/datafusion/src/physical_plan/sorts/sort.rs b/datafusion/src/physical_plan/sorts/sort.rs
index b2bf604665..84a07695a8 100644
--- a/datafusion/src/physical_plan/sorts/sort.rs
+++ b/datafusion/src/physical_plan/sorts/sort.rs
@@ -37,6 +37,7 @@ use crate::physical_plan::{
common, DisplayFormatType, Distribution, EmptyRecordBatchStream, ExecutionPlan,
Partitioning, SendableRecordBatchStream, Statistics,
};
+use crate::prelude::SessionConfig;
use arrow::array::ArrayRef;
pub use arrow::compute::SortOptions;
use arrow::compute::{lexsort_to_indices, take, SortColumn, TakeOptions};
@@ -75,6 +76,7 @@ struct ExternalSorter {
spills: Mutex<Vec<NamedTempFile>>,
/// Sort expressions
expr: Vec<PhysicalSortExpr>,
+ session_config: Arc<SessionConfig>,
runtime: Arc<RuntimeEnv>,
metrics_set: CompositeMetricsSet,
metrics: BaselineMetrics,
@@ -86,6 +88,7 @@ impl ExternalSorter {
schema: SchemaRef,
expr: Vec<PhysicalSortExpr>,
metrics_set: CompositeMetricsSet,
+ session_config: Arc<SessionConfig>,
runtime: Arc<RuntimeEnv>,
) -> Self {
let metrics = metrics_set.new_intermediate_baseline(partition_id);
@@ -95,6 +98,7 @@ impl ExternalSorter {
in_mem_batches: Mutex::new(vec![]),
spills: Mutex::new(vec![]),
expr,
+ session_config,
runtime,
metrics_set,
metrics,
@@ -152,7 +156,7 @@ impl ExternalSorter {
self.schema.clone(),
&self.expr,
tracking_metrics,
- self.runtime.clone(),
+ self.session_config.batch_size,
)))
} else if in_mem_batches.len() > 0 {
let tracking_metrics = self
@@ -577,6 +581,7 @@ async fn do_sort(
schema.clone(),
expr,
metrics_set,
+ Arc::new(context.session_config()),
context.runtime.clone(),
);
context.runtime.register_requester(sorter.id());
@@ -592,6 +597,7 @@ mod tests {
use super::*;
use crate::datasource::object_store::local::LocalFileSystem;
use crate::execution::context::SessionConfig;
+ use crate::execution::runtime_env::RuntimeConfig;
use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use crate::physical_plan::expressions::col;
use crate::physical_plan::memory::MemoryExec;
@@ -678,8 +684,9 @@ mod tests {
#[tokio::test]
async fn test_sort_spill() -> Result<()> {
// trigger spill there will be 4 batches with 5.5KB for each
- let config = SessionConfig::new().with_memory_limit(12288, 1.0)?;
- let session_ctx = SessionContext::with_config(config);
+ let config = RuntimeConfig::new().with_memory_limit(12288, 1.0);
+ let runtime = Arc::new(RuntimeEnv::new(config)?);
+ let session_ctx = SessionContext::with_config_rt(SessionConfig::new(), runtime);
let schema = test_util::aggr_test_schema();
let partitions = 4;
diff --git a/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs b/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs
index b04af04ba5..5082b9f7ff 100644
--- a/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs
+++ b/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs
@@ -43,7 +43,6 @@ use futures::{Stream, StreamExt};
use crate::error::{DataFusionError, Result};
use crate::execution::context::TaskContext;
-use crate::execution::runtime_env::RuntimeEnv;
use crate::physical_plan::sorts::{RowIndex, SortKeyCursor, SortedStream, StreamWrapper};
use crate::physical_plan::{
common::spawn_execution, expressions::PhysicalSortExpr, DisplayFormatType,
@@ -201,7 +200,7 @@ impl ExecutionPlan for SortPreservingMergeExec {
self.schema(),
&self.expr,
tracking_metrics,
- context.runtime.clone(),
+ context.session_config().batch_size,
)))
}
}
@@ -303,7 +302,7 @@ impl SortPreservingMergeStream {
schema: SchemaRef,
expressions: &[PhysicalSortExpr],
tracking_metrics: MemTrackingMetrics,
- runtime: Arc<RuntimeEnv>,
+ batch_size: usize,
) -> Self {
let stream_count = receivers.len();
let batches = (0..stream_count)
@@ -325,7 +324,7 @@ impl SortPreservingMergeStream {
in_progress: vec![],
next_batch_id: 0,
min_heap: BinaryHeap::with_capacity(stream_count),
- batch_size: runtime.batch_size(),
+ batch_size,
}
}
@@ -334,7 +333,7 @@ impl SortPreservingMergeStream {
schema: SchemaRef,
expressions: &[PhysicalSortExpr],
tracking_metrics: MemTrackingMetrics,
- runtime: Arc<RuntimeEnv>,
+ batch_size: usize,
) -> Self {
let stream_count = streams.len();
let batches = (0..stream_count)
@@ -360,7 +359,7 @@ impl SortPreservingMergeStream {
in_progress: vec![],
next_batch_id: 0,
min_heap: BinaryHeap::with_capacity(stream_count),
- batch_size: runtime.batch_size(),
+ batch_size,
}
}
@@ -1228,7 +1227,7 @@ mod tests {
batches.schema(),
sort.as_slice(),
tracking_metrics,
- task_ctx.runtime.clone(),
+ task_ctx.session_config().batch_size,
);
let mut merged = common::collect(Box::pin(merge_stream)).await.unwrap();
diff --git a/datafusion/tests/order_spill_fuzz.rs b/datafusion/tests/order_spill_fuzz.rs
index 53dadb7f17..c052382d5e 100644
--- a/datafusion/tests/order_spill_fuzz.rs
+++ b/datafusion/tests/order_spill_fuzz.rs
@@ -23,7 +23,7 @@ use arrow::{
record_batch::RecordBatch,
};
use datafusion::execution::memory_manager::MemoryManagerConfig;
-use datafusion::execution::runtime_env::RuntimeConfig;
+use datafusion::execution::runtime_env::{RuntimeConfig, RuntimeEnv};
use datafusion::physical_plan::expressions::{col, PhysicalSortExpr};
use datafusion::physical_plan::memory::MemoryExec;
use datafusion::physical_plan::sorts::sort::SortExec;
@@ -78,8 +78,8 @@ async fn run_sort(pool_size: usize, size_spill: Vec<(usize, bool)>) {
let runtime_config = RuntimeConfig::new().with_memory_manager(
MemoryManagerConfig::try_new_limit(pool_size, 1.0).unwrap(),
);
- let session_config = SessionConfig::new().with_runtime_config(runtime_config);
- let session_ctx = SessionContext::with_config(session_config);
+ let runtime = Arc::new(RuntimeEnv::new(runtime_config).unwrap());
+ let session_ctx = SessionContext::with_config_rt(SessionConfig::new(), runtime);
let task_ctx = session_ctx.task_ctx();
let collected = collect(sort.clone(), task_ctx).await.unwrap();
diff --git a/datafusion/tests/user_defined_plan.rs b/datafusion/tests/user_defined_plan.rs
index 37c47969fb..30b4229259 100644
--- a/datafusion/tests/user_defined_plan.rs
+++ b/datafusion/tests/user_defined_plan.rs
@@ -87,6 +87,7 @@ use std::{any::Any, collections::BTreeMap, fmt, sync::Arc};
use async_trait::async_trait;
use datafusion::execution::context::{ExecutionProps, TaskContext};
+use datafusion::execution::runtime_env::{RuntimeConfig, RuntimeEnv};
use datafusion::logical_plan::plan::{Extension, Sort};
use datafusion::logical_plan::{DFSchemaRef, Limit};
@@ -242,12 +243,12 @@ async fn topk_plan() -> Result<()> {
}
fn make_topk_context() -> SessionContext {
- let config = SessionConfig::new()
+ let config = SessionConfig::new().with_target_partitions(48);
+ let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap());
+ let state = SessionState::with_config(config, runtime)
.with_query_planner(Arc::new(TopKQueryPlanner {}))
- .with_target_partitions(48)
.add_optimizer_rule(Arc::new(TopKOptimizerRule {}));
-
- SessionContext::with_config(config)
+ SessionContext::with_state(state)
}
// ------ The implementation of the TopK code follows -----