Skip to content

Commit 86548e3

Browse files
committed
Clean up API, make examples easier
1 parent 0948517 commit 86548e3

File tree

6 files changed

+110
-62
lines changed

6 files changed

+110
-62
lines changed

datafusion-examples/examples/expr_api.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@ use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
2525
use datafusion::common::DFSchema;
2626
use datafusion::error::Result;
2727
use datafusion::optimizer::simplify_expressions::ExprSimplifier;
28-
use datafusion::physical_expr::{
29-
analyze, create_physical_expr, AnalysisContext, ExprBoundaries, PhysicalExpr,
30-
};
28+
use datafusion::physical_expr::{analyze, AnalysisContext, ExprBoundaries};
3129
use datafusion::prelude::*;
3230
use datafusion_common::{ScalarValue, ToDFSchema};
3331
use datafusion_expr::execution_props::ExecutionProps;
@@ -92,8 +90,8 @@ fn evaluate_demo() -> Result<()> {
9290
let expr = col("a").lt(lit(5)).or(col("a").eq(lit(8)));
9391

9492
// First, you make a "physical expression" from the logical `Expr`
95-
let ctx = SessionContext::new();
96-
let physical_expr = physical_expr(&batch.schema(), expr)?;
93+
let df_schema = DFSchema::try_from(batch.schema())?;
94+
let physical_expr = SessionContext::new().create_physical_expr(&df_schema, expr)?;
9795

9896
// Now, you can evaluate the expression against the RecordBatch
9997
let result = physical_expr.evaluate(&batch)?;
@@ -214,7 +212,7 @@ fn range_analysis_demo() -> Result<()> {
214212
// `date < '2020-10-01' AND date > '2020-09-01'`
215213

216214
// As always, we need to tell DataFusion the type of column "date"
217-
let schema = Schema::new(vec![make_field("date", DataType::Date32)]);
215+
let schema = Arc::new(Schema::new(vec![make_field("date", DataType::Date32)]));
218216

219217
// You can provide DataFusion any known boundaries on the values of `date`
220218
// (for example, maybe you know you only have data up to `2020-09-15`), but
@@ -223,9 +221,13 @@ fn range_analysis_demo() -> Result<()> {
223221
let boundaries = ExprBoundaries::try_new_unbounded(&schema)?;
224222

225223
// Now, we invoke the analysis code to perform the range analysis
226-
let physical_expr = physical_expr(&schema, expr)?;
227-
let analysis_result =
228-
analyze(&physical_expr, AnalysisContext::new(boundaries), &schema)?;
224+
let df_schema = DFSchema::try_from(schema)?;
225+
let physical_expr = SessionContext::new().create_physical_expr(&df_schema, expr)?;
226+
let analysis_result = analyze(
227+
&physical_expr,
228+
AnalysisContext::new(boundaries),
229+
df_schema.as_ref(),
230+
)?;
229231

230232
// The results of the analysis is an range, encoded as an `Interval`, for
231233
// each column in the schema, that must be true in order for the predicate

datafusion/common/src/dfschema.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,20 @@ impl DFSchema {
125125
}
126126
}
127127

128+
/// Return a reference to the inner Arrow [`Schema`]
129+
///
130+
/// Note this does not have the qualifier information
131+
pub fn as_arrow(&self) -> &Schema {
132+
self.inner.as_ref()
133+
}
134+
135+
/// Return a reference to the inner Arrow [`SchemaRef`]
136+
///
137+
/// Note this does not have the qualifier information
138+
pub fn inner(&self) -> &SchemaRef {
139+
&self.inner
140+
}
141+
128142
/// Create a `DFSchema` from an Arrow schema where all the fields have a given qualifier
129143
pub fn new_with_metadata(
130144
qualified_fields: Vec<(Option<TableReference>, Arc<Field>)>,
@@ -806,6 +820,12 @@ impl From<&DFSchema> for Schema {
806820
}
807821
}
808822

823+
impl AsRef<Schema> for DFSchema {
824+
fn as_ref(&self) -> &Schema {
825+
self.as_arrow()
826+
}
827+
}
828+
809829
/// Create a `DFSchema` from an Arrow schema
810830
impl TryFrom<Schema> for DFSchema {
811831
type Error = DataFusionError;

datafusion/core/src/execution/context/mod.rs

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,13 @@ use datafusion_common::{
7070
config::{ConfigExtension, TableOptions},
7171
exec_err, not_impl_err, plan_datafusion_err, plan_err,
7272
tree_node::{TreeNodeRecursion, TreeNodeVisitor},
73-
DFSchemaRef, SchemaReference, TableReference,
73+
DFSchema, SchemaReference, TableReference,
7474
};
7575
use datafusion_execution::registry::SerializerRegistry;
7676
use datafusion_expr::{
7777
logical_plan::{DdlStatement, Statement},
7878
var_provider::is_system_variables,
79-
Expr, StringifiedPlan, UserDefinedLogicalNode, WindowUDF,
79+
Expr, ExprSchemable, StringifiedPlan, UserDefinedLogicalNode, WindowUDF,
8080
};
8181
use datafusion_sql::{
8282
parser::{CopyToSource, CopyToStatement, DFParser},
@@ -96,7 +96,7 @@ pub use datafusion_execution::config::SessionConfig;
9696
pub use datafusion_execution::TaskContext;
9797
pub use datafusion_expr::execution_props::ExecutionProps;
9898
use datafusion_expr::expr_rewriter::FunctionRewrite;
99-
use datafusion_expr::simplify::SimplifyContext;
99+
use datafusion_expr::simplify::SimplifyInfo;
100100
use datafusion_optimizer::simplify_expressions::ExprSimplifier;
101101
use datafusion_physical_expr::create_physical_expr;
102102

@@ -520,10 +520,10 @@ impl SessionContext {
520520
/// examples.
521521
pub fn create_physical_expr(
522522
&self,
523-
schema: impl Into<DFSchemaRef>,
523+
df_schema: &DFSchema,
524524
expr: Expr,
525525
) -> Result<Arc<dyn PhysicalExpr>> {
526-
self.state.read().create_physical_expr(schema, expr)
526+
self.state.read().create_physical_expr(df_schema, expr)
527527
}
528528

529529
// return an empty dataframe
@@ -1966,7 +1966,9 @@ impl SessionState {
19661966
}
19671967

19681968
/// Creates a [`PhysicalExpr`] from an [`Expr`] after applying type
1969-
/// coercion, simplifications, and function rewrites.
1969+
/// coercion, and function rewrites.
1970+
///
1971+
/// Note that no simplification (TODO link) is applied.
19701972
///
19711973
/// TODO links to coercsion, simplificiation, and rewrites
19721974
///
@@ -1976,21 +1978,20 @@ impl SessionState {
19761978
/// ```
19771979
pub fn create_physical_expr(
19781980
&self,
1979-
schema: impl Into<DFSchemaRef>,
1981+
// todo make this schema
1982+
df_schema: &DFSchema,
19801983
expr: Expr,
19811984
) -> Result<Arc<dyn PhysicalExpr>> {
1982-
let df_schema = schema.into();
1983-
19841985
// Simplify
1985-
let props = ExecutionProps::new();
1986-
let simplifier = ExprSimplifier::new(
1987-
SimplifyContext::new(&props).with_schema(df_schema.clone()),
1988-
);
1986+
let simplifier =
1987+
ExprSimplifier::new(SessionSimpifyProvider::new(self, df_schema));
19891988

19901989
// apply type coercion here to ensure types match
1991-
let expr = simplifier.coerce(expr, df_schema.clone())?;
1990+
let expr = simplifier.coerce(expr, df_schema)?;
1991+
// TODO should we also simplify the expression?
1992+
// simplifier.simplify()
19921993

1993-
create_physical_expr(&expr, df_schema.as_ref(), &props)
1994+
create_physical_expr(&expr, df_schema, self.execution_props())
19941995
}
19951996

19961997
/// Return the session ID
@@ -2070,6 +2071,35 @@ impl SessionState {
20702071
}
20712072
}
20722073

2074+
struct SessionSimpifyProvider<'a> {
2075+
state: &'a SessionState,
2076+
df_schema: &'a DFSchema,
2077+
}
2078+
2079+
impl<'a> SessionSimpifyProvider<'a> {
2080+
fn new(state: &'a SessionState, df_schema: &'a DFSchema) -> Self {
2081+
Self { state, df_schema }
2082+
}
2083+
}
2084+
2085+
impl<'a> SimplifyInfo for SessionSimpifyProvider<'a> {
2086+
fn is_boolean_type(&self, expr: &Expr) -> Result<bool> {
2087+
Ok(expr.get_type(self.df_schema)? == DataType::Boolean)
2088+
}
2089+
2090+
fn nullable(&self, expr: &Expr) -> Result<bool> {
2091+
expr.nullable(self.df_schema)
2092+
}
2093+
2094+
fn execution_props(&self) -> &ExecutionProps {
2095+
self.state.execution_props()
2096+
}
2097+
2098+
fn get_data_type(&self, expr: &Expr) -> Result<DataType> {
2099+
expr.get_type(self.df_schema)
2100+
}
2101+
}
2102+
20732103
struct SessionContextProvider<'a> {
20742104
state: &'a SessionState,
20752105
tables: HashMap<String, Arc<dyn TableSource>>,

datafusion/core/src/test_util/parquet.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ impl TestParquetFile {
168168
let parquet_options = ctx.copied_table_options().parquet;
169169
if let Some(filter) = maybe_filter {
170170
let simplifier = ExprSimplifier::new(context);
171-
let filter = simplifier.coerce(filter, df_schema.clone()).unwrap();
171+
let filter = simplifier.coerce(filter, &df_schema).unwrap();
172172
let physical_filter_expr =
173173
create_physical_expr(&filter, &df_schema, &ExecutionProps::default())?;
174174
let parquet_exec = Arc::new(ParquetExec::new(

0 commit comments

Comments
 (0)