vegarsti commented on code in PR #17633:
URL: https://github.com/apache/datafusion/pull/17633#discussion_r2383934243


##########
datafusion-examples/examples/table_sample.rs:
##########
@@ -0,0 +1,1252 @@
+// 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.
+
+use datafusion::common::{
+    arrow_datafusion_err, internal_err, not_impl_err, plan_datafusion_err, 
plan_err,
+    DFSchemaRef, ResolvedTableReference, Statistics, TableReference,
+};
+use datafusion::error::Result;
+use datafusion::logical_expr::sqlparser::ast::{
+    SetExpr, Statement, TableFactor, TableSampleMethod, TableSampleUnit,
+};
+use datafusion::logical_expr::{
+    Extension, LogicalPlan, LogicalPlanBuilder, TableSource, 
UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use std::any::Any;
+use std::collections::HashMap;
+
+use arrow::util::pretty::pretty_format_batches;
+
+use arrow_schema::SchemaRef;
+use async_trait::async_trait;
+use datafusion::datasource::provider_as_source;
+use datafusion::error::DataFusionError;
+use datafusion::execution::{
+    SendableRecordBatchStream, SessionState, SessionStateBuilder, TaskContext,
+};
+use datafusion::logical_expr::planner::ContextProvider;
+use datafusion::logical_expr::sqlparser::dialect::PostgreSqlDialect;
+use datafusion::logical_expr::sqlparser::parser::Parser;
+use datafusion::physical_expr::EquivalenceProperties;
+use datafusion::physical_plan::metrics::{
+    BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RecordOutput,
+};
+use datafusion::physical_plan::{
+    displayable, DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
+    RecordBatchStream,
+};
+use datafusion::physical_planner::{
+    DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner,
+};
+use datafusion::prelude::*;
+use datafusion::sql::planner::SqlToRel;
+use datafusion::sql::sqlparser::ast::TableSampleKind;
+use log::{debug, info};
+use std::fmt;
+use std::fmt::{Debug, Formatter};
+use std::hash::{Hash, Hasher};
+use std::pin::Pin;
+use std::str::FromStr;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use arrow::array::UInt32Array;
+use arrow::compute;
+use arrow::record_batch::RecordBatch;
+
+use datafusion::execution::context::QueryPlanner;
+use datafusion::execution::session_state::SessionContextProvider;
+use datafusion::sql::sqlparser::ast;
+use futures::stream::{Stream, StreamExt};
+use futures::{ready, TryStreamExt};
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+use rand_distr::{Distribution, Poisson};
+
+/// This example demonstrates how to extend DataFusion's SQL parser to 
recognize
+/// other syntax.
+///
+/// This example shows how to extend the DataFusion SQL planner to support the
+/// `TABLESAMPLE` clause in SQL queries and then use a custom user defined node
+/// to implement the sampling logic in the physical plan.
+
+#[tokio::main]
+async fn main() -> Result<()> {
+    let _ = env_logger::try_init();
+
+    let state = SessionStateBuilder::new()
+        .with_default_features()
+        .with_query_planner(Arc::new(TableSampleQueryPlanner {}))
+        .build();
+
+    let ctx = SessionContext::new_with_state(state.clone());
+
+    let testdata = datafusion::test_util::parquet_test_data();
+    ctx.register_parquet(
+        "alltypes_plain",
+        &format!("{testdata}/alltypes_plain.parquet"),
+        ParquetReadOptions::default(),
+    )
+    .await?;
+
+    // Construct a context provider from this parquet table source
+    let table_source = 
provider_as_source(ctx.table_provider("alltypes_plain").await?);
+    let resolved_table_ref = TableReference::bare("alltypes_plain").resolve(
+        &state.config_options().catalog.default_catalog,
+        &state.config_options().catalog.default_schema,
+    );
+    let context_provider = SessionContextProvider::new(
+        &state,
+        HashMap::<ResolvedTableReference, Arc<dyn TableSource>>::from([(
+            resolved_table_ref,
+            table_source.clone(),
+        )]),
+    );
+
+    let sql =
+        "SELECT int_col, double_col FROM alltypes_plain TABLESAMPLE 42 PERCENT 
REPEATABLE(5) WHERE int_col = 1";
+
+    let dialect = PostgreSqlDialect {};
+    let statements = Parser::parse_sql(&dialect, sql)?;
+    let statement = statements.first().expect("one statement");
+
+    // Classical way
+    // let sql_to_rel = SqlToRel::new(&context_provider);
+    // let logical_plan = sql_to_rel.sql_statement_to_plan(statement.clone())?;

Review Comment:
   Classical way to do what?



##########
datafusion-examples/examples/table_sample.rs:
##########
@@ -0,0 +1,1252 @@
+// 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.
+
+use datafusion::common::{
+    arrow_datafusion_err, internal_err, not_impl_err, plan_datafusion_err, 
plan_err,
+    DFSchemaRef, ResolvedTableReference, Statistics, TableReference,
+};
+use datafusion::error::Result;
+use datafusion::logical_expr::sqlparser::ast::{
+    SetExpr, Statement, TableFactor, TableSampleMethod, TableSampleUnit,
+};
+use datafusion::logical_expr::{
+    Extension, LogicalPlan, LogicalPlanBuilder, TableSource, 
UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use std::any::Any;
+use std::collections::HashMap;
+
+use arrow::util::pretty::pretty_format_batches;
+
+use arrow_schema::SchemaRef;
+use async_trait::async_trait;
+use datafusion::datasource::provider_as_source;
+use datafusion::error::DataFusionError;
+use datafusion::execution::{
+    SendableRecordBatchStream, SessionState, SessionStateBuilder, TaskContext,
+};
+use datafusion::logical_expr::planner::ContextProvider;
+use datafusion::logical_expr::sqlparser::dialect::PostgreSqlDialect;
+use datafusion::logical_expr::sqlparser::parser::Parser;
+use datafusion::physical_expr::EquivalenceProperties;
+use datafusion::physical_plan::metrics::{
+    BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RecordOutput,
+};
+use datafusion::physical_plan::{
+    displayable, DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
+    RecordBatchStream,
+};
+use datafusion::physical_planner::{
+    DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner,
+};
+use datafusion::prelude::*;
+use datafusion::sql::planner::SqlToRel;
+use datafusion::sql::sqlparser::ast::TableSampleKind;
+use log::{debug, info};
+use std::fmt;
+use std::fmt::{Debug, Formatter};
+use std::hash::{Hash, Hasher};
+use std::pin::Pin;
+use std::str::FromStr;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use arrow::array::UInt32Array;
+use arrow::compute;
+use arrow::record_batch::RecordBatch;
+
+use datafusion::execution::context::QueryPlanner;
+use datafusion::execution::session_state::SessionContextProvider;
+use datafusion::sql::sqlparser::ast;
+use futures::stream::{Stream, StreamExt};
+use futures::{ready, TryStreamExt};
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+use rand_distr::{Distribution, Poisson};
+
+/// This example demonstrates how to extend DataFusion's SQL parser to 
recognize
+/// other syntax.
+///
+/// This example shows how to extend the DataFusion SQL planner to support the
+/// `TABLESAMPLE` clause in SQL queries and then use a custom user defined node
+/// to implement the sampling logic in the physical plan.
+
+#[tokio::main]
+async fn main() -> Result<()> {
+    let _ = env_logger::try_init();
+
+    let state = SessionStateBuilder::new()
+        .with_default_features()
+        .with_query_planner(Arc::new(TableSampleQueryPlanner {}))
+        .build();
+
+    let ctx = SessionContext::new_with_state(state.clone());
+
+    let testdata = datafusion::test_util::parquet_test_data();
+    ctx.register_parquet(
+        "alltypes_plain",
+        &format!("{testdata}/alltypes_plain.parquet"),
+        ParquetReadOptions::default(),
+    )
+    .await?;
+
+    // Construct a context provider from this parquet table source
+    let table_source = 
provider_as_source(ctx.table_provider("alltypes_plain").await?);
+    let resolved_table_ref = TableReference::bare("alltypes_plain").resolve(
+        &state.config_options().catalog.default_catalog,
+        &state.config_options().catalog.default_schema,
+    );
+    let context_provider = SessionContextProvider::new(
+        &state,
+        HashMap::<ResolvedTableReference, Arc<dyn TableSource>>::from([(
+            resolved_table_ref,
+            table_source.clone(),
+        )]),
+    );
+
+    let sql =
+        "SELECT int_col, double_col FROM alltypes_plain TABLESAMPLE 42 PERCENT 
REPEATABLE(5) WHERE int_col = 1";
+
+    let dialect = PostgreSqlDialect {};
+    let statements = Parser::parse_sql(&dialect, sql)?;
+    let statement = statements.first().expect("one statement");
+
+    // Classical way
+    // let sql_to_rel = SqlToRel::new(&context_provider);
+    // let logical_plan = sql_to_rel.sql_statement_to_plan(statement.clone())?;
+
+    // Use sampling planner to create a logical plan
+    let table_sample_planner = TableSamplePlanner::new(&context_provider);
+    let logical_plan = 
table_sample_planner.create_logical_plan(statement.clone())?;
+
+    let physical_plan = ctx.state().create_physical_plan(&logical_plan).await?;
+
+    // Inspect physical plan
+    let displayable_plan = displayable(physical_plan.as_ref())
+        .indent(false)
+        .to_string();
+    info!("Physical plan:\n{displayable_plan}\n");
+    let first_line = displayable_plan.lines().next().unwrap();
+    assert_eq!(
+        first_line,
+        "SampleExec: lower_bound=0, upper_bound=0.42, with_replacement=false, 
seed=5"
+    );
+
+    // Execute via standard sql call - doesn't work
+    // let df = ctx.sql(sql).await?;
+    // let batches = df.collect().await?;
+
+    // Execute directly via physical plan
+    let task_context = Arc::new(TaskContext::from(&ctx));
+    let stream = physical_plan.execute(0, task_context)?;
+    let batches: Vec<_> = stream.try_collect().await?;
+
+    info!("Batches: {:?}", &batches);
+
+    let result_string = pretty_format_batches(&batches)
+        // pretty_format_batches_with_schema(table_source.schema(), &batches)

Review Comment:
   remove?



##########
datafusion-examples/examples/table_sample.rs:
##########
@@ -0,0 +1,1252 @@
+// 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.
+
+use datafusion::common::{
+    arrow_datafusion_err, internal_err, not_impl_err, plan_datafusion_err, 
plan_err,
+    DFSchemaRef, ResolvedTableReference, Statistics, TableReference,
+};
+use datafusion::error::Result;
+use datafusion::logical_expr::sqlparser::ast::{
+    SetExpr, Statement, TableFactor, TableSampleMethod, TableSampleUnit,
+};
+use datafusion::logical_expr::{
+    Extension, LogicalPlan, LogicalPlanBuilder, TableSource, 
UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use std::any::Any;
+use std::collections::HashMap;
+
+use arrow::util::pretty::pretty_format_batches;
+
+use arrow_schema::SchemaRef;
+use async_trait::async_trait;
+use datafusion::datasource::provider_as_source;
+use datafusion::error::DataFusionError;
+use datafusion::execution::{
+    SendableRecordBatchStream, SessionState, SessionStateBuilder, TaskContext,
+};
+use datafusion::logical_expr::planner::ContextProvider;
+use datafusion::logical_expr::sqlparser::dialect::PostgreSqlDialect;
+use datafusion::logical_expr::sqlparser::parser::Parser;
+use datafusion::physical_expr::EquivalenceProperties;
+use datafusion::physical_plan::metrics::{
+    BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RecordOutput,
+};
+use datafusion::physical_plan::{
+    displayable, DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
+    RecordBatchStream,
+};
+use datafusion::physical_planner::{
+    DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner,
+};
+use datafusion::prelude::*;
+use datafusion::sql::planner::SqlToRel;
+use datafusion::sql::sqlparser::ast::TableSampleKind;
+use log::{debug, info};
+use std::fmt;
+use std::fmt::{Debug, Formatter};
+use std::hash::{Hash, Hasher};
+use std::pin::Pin;
+use std::str::FromStr;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use arrow::array::UInt32Array;
+use arrow::compute;
+use arrow::record_batch::RecordBatch;
+
+use datafusion::execution::context::QueryPlanner;
+use datafusion::execution::session_state::SessionContextProvider;
+use datafusion::sql::sqlparser::ast;
+use futures::stream::{Stream, StreamExt};
+use futures::{ready, TryStreamExt};
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+use rand_distr::{Distribution, Poisson};
+
+/// This example demonstrates how to extend DataFusion's SQL parser to 
recognize
+/// other syntax.
+///
+/// This example shows how to extend the DataFusion SQL planner to support the
+/// `TABLESAMPLE` clause in SQL queries and then use a custom user defined node
+/// to implement the sampling logic in the physical plan.
+
+#[tokio::main]
+async fn main() -> Result<()> {
+    let _ = env_logger::try_init();
+
+    let state = SessionStateBuilder::new()
+        .with_default_features()
+        .with_query_planner(Arc::new(TableSampleQueryPlanner {}))
+        .build();
+
+    let ctx = SessionContext::new_with_state(state.clone());
+
+    let testdata = datafusion::test_util::parquet_test_data();
+    ctx.register_parquet(
+        "alltypes_plain",
+        &format!("{testdata}/alltypes_plain.parquet"),
+        ParquetReadOptions::default(),
+    )
+    .await?;
+
+    // Construct a context provider from this parquet table source
+    let table_source = 
provider_as_source(ctx.table_provider("alltypes_plain").await?);
+    let resolved_table_ref = TableReference::bare("alltypes_plain").resolve(
+        &state.config_options().catalog.default_catalog,
+        &state.config_options().catalog.default_schema,
+    );
+    let context_provider = SessionContextProvider::new(
+        &state,
+        HashMap::<ResolvedTableReference, Arc<dyn TableSource>>::from([(
+            resolved_table_ref,
+            table_source.clone(),
+        )]),
+    );
+
+    let sql =
+        "SELECT int_col, double_col FROM alltypes_plain TABLESAMPLE 42 PERCENT 
REPEATABLE(5) WHERE int_col = 1";
+
+    let dialect = PostgreSqlDialect {};
+    let statements = Parser::parse_sql(&dialect, sql)?;
+    let statement = statements.first().expect("one statement");
+
+    // Classical way
+    // let sql_to_rel = SqlToRel::new(&context_provider);
+    // let logical_plan = sql_to_rel.sql_statement_to_plan(statement.clone())?;
+
+    // Use sampling planner to create a logical plan
+    let table_sample_planner = TableSamplePlanner::new(&context_provider);
+    let logical_plan = 
table_sample_planner.create_logical_plan(statement.clone())?;
+
+    let physical_plan = ctx.state().create_physical_plan(&logical_plan).await?;
+
+    // Inspect physical plan
+    let displayable_plan = displayable(physical_plan.as_ref())
+        .indent(false)
+        .to_string();
+    info!("Physical plan:\n{displayable_plan}\n");
+    let first_line = displayable_plan.lines().next().unwrap();
+    assert_eq!(
+        first_line,
+        "SampleExec: lower_bound=0, upper_bound=0.42, with_replacement=false, 
seed=5"
+    );
+
+    // Execute via standard sql call - doesn't work
+    // let df = ctx.sql(sql).await?;
+    // let batches = df.collect().await?;

Review Comment:
   Remove?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to