Apache DataFusion SQL Query Engine
Support filtering specific sqllogictests identified by line number (#16029)
Gabriel17fe504b0b8c
diff --git a/datafusion/sqllogictest/README.md b/datafusion/sqllogictest/README.mdindex 77162f4001..a71f920a42 100644--- a/datafusion/sqllogictest/README.md+++ b/datafusion/sqllogictest/README.md@@ -156,6 +156,14 @@ sqllogictests also supports `cargo test` style substring matches on file names tcargo test --test sqllogictests -- information```+Additionally, executing specific tests within a file is also supported. Tests are identified by line number within+the .slt file; for example, the following command will run the test in line `709` for file `information.slt` along+with any other preparatory statements:++```shell+cargo test --test sqllogictests -- information:709+```+## Running tests: Postgres compatibilityTest files that start with prefix `pg_compat_` verify compatibilitydiff --git a/datafusion/sqllogictest/bin/sqllogictests.rs b/datafusion/sqllogictest/bin/sqllogictests.rsindex f8a4ec6665..4d6bce2088 100644--- a/datafusion/sqllogictest/bin/sqllogictests.rs+++ b/datafusion/sqllogictest/bin/sqllogictests.rs@@ -20,8 +20,8 @@ use datafusion::common::instant::Instant;use datafusion::common::utils::get_available_parallelism;use datafusion::common::{exec_err, DataFusionError, Result};use datafusion_sqllogictest::{- df_value_validator, read_dir_recursive, setup_scratch_dir, value_normalizer,- DataFusion, TestContext,+ df_value_validator, read_dir_recursive, setup_scratch_dir, should_skip_file,+ should_skip_record, value_normalizer, DataFusion, Filter, TestContext,};use futures::stream::StreamExt;use indicatif::{@@ -135,12 +135,19 @@ async fn run_tests() -> Result<()> {let m_clone = m.clone();let m_style_clone = m_style.clone();+ let filters = options.filters.clone();SpawnedTask::spawn(async move {match (options.postgres_runner, options.complete) {(false, false) => {- run_test_file(test_file, validator, m_clone, m_style_clone)- .await?+ run_test_file(+ test_file,+ validator,+ m_clone,+ m_style_clone,+ filters.as_ref(),+ )+ .await?}(false, true) => {run_complete_file(test_file, validator, m_clone, m_style_clone)@@ -152,6 +159,7 @@ async fn run_tests() -> Result<()> {validator,m_clone,m_style_clone,+ filters.as_ref(),).await?}@@ -207,6 +215,7 @@ async fn run_test_file(validator: Validator,mp: MultiProgress,mp_style: ProgressStyle,+ filters: &[Filter],) -> Result<()> {let TestFile {path,@@ -235,7 +244,7 @@ async fn run_test_file(runner.with_column_validator(strict_column_validator);runner.with_normalizer(value_normalizer);runner.with_validator(validator);- let result = run_file_in_runner(path, runner).await;+ let result = run_file_in_runner(path, runner, filters).await;pb.finish_and_clear();result}@@ -243,6 +252,7 @@ async fn run_test_file(async fn run_file_in_runner<D: AsyncDB, M: MakeConnection<Conn = D>>(path: PathBuf,mut runner: sqllogictest::Runner<D, M>,+ filters: &[Filter],) -> Result<()> {let path = path.canonicalize()?;let records =@@ -252,6 +262,9 @@ async fn run_file_in_runner<D: AsyncDB, M: MakeConnection<Conn = D>>(if let Record::Halt { .. } = record {break;}+ if should_skip_record::<D>(&record, filters) {+ continue;+ }if let Err(err) = runner.run_async(record).await {errs.push(format!("{err}"));}@@ -318,6 +331,7 @@ async fn run_test_file_with_postgres(validator: Validator,mp: MultiProgress,mp_style: ProgressStyle,+ filters: &[Filter],) -> Result<()> {use datafusion_sqllogictest::Postgres;let TestFile {@@ -339,7 +353,7 @@ async fn run_test_file_with_postgres(runner.with_column_validator(strict_column_validator);runner.with_normalizer(value_normalizer);runner.with_validator(validator);- let result = run_file_in_runner(path, runner).await;+ let result = run_file_in_runner(path, runner, filters).await;pb.finish_and_clear();result}@@ -350,6 +364,7 @@ async fn run_test_file_with_postgres(_validator: Validator,_mp: MultiProgress,_mp_style: ProgressStyle,+ _filters: &[Filter],) -> Result<()> {use datafusion::common::plan_err;plan_err!("Can not run with postgres as postgres feature is not enabled")@@ -569,8 +584,11 @@ struct Options {#[clap(long, env = "INCLUDE_TPCH", help = "Include tpch files")]include_tpch: bool,- #[clap(action, help = "test filter (substring match on filenames)")]- filters: Vec<String>,+ #[clap(+ action,+ help = "test filter (substring match on filenames with optional :{line_number} suffix)"+ )]+ filters: Vec<Filter>,#[clap(long,@@ -623,15 +641,7 @@ impl Options {/// filter and that does a substring match on each input. returns/// true f this path should be runfn check_test_file(&self, path: &Path) -> bool {- if self.filters.is_empty() {- return true;- }-- // otherwise check if any filter matches- let path_string = path.to_string_lossy();- self.filters- .iter()- .any(|filter| path_string.contains(filter))+ !should_skip_file(path, &self.filters)}/// Postgres runner executes only tests in files with specific names or indiff --git a/datafusion/sqllogictest/src/filters.rs b/datafusion/sqllogictest/src/filters.rsnew file mode 100644index 0000000000..44482236f7--- /dev/null+++ b/datafusion/sqllogictest/src/filters.rs@@ -0,0 +1,170 @@+// 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::sql::parser::{DFParserBuilder, Statement};+use sqllogictest::{AsyncDB, Record};+use sqlparser::ast::{SetExpr, Statement as SqlStatement};+use sqlparser::dialect::dialect_from_str;+use std::path::Path;+use std::str::FromStr;++/// Filter specification that determines whether a certain sqllogictest record in+/// a certain file should be filtered. In order for a [`Filter`] to match a test case:+///+/// - The test must belong to a file whose absolute path contains the `file_substring` substring.+/// - If a `line_number` is specified, the test must be declared in that same line number.+///+/// If a [`Filter`] matches a specific test case, then the record is executed, if there's+/// no match, the record is skipped.+///+/// Filters can be parsed from strings of the form `<file_name>:line_number`. For example,+/// `foo.slt:100` matches any test whose name contains `foo.slt` and the test starts on line+/// number 100.+#[derive(Debug, Clone)]+pub struct Filter {+ file_substring: String,+ line_number: Option<u32>,+}++impl FromStr for Filter {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ let parts: Vec<&str> = s.rsplitn(2, ':').collect();+ if parts.len() == 2 {+ match parts[0].parse::<u32>() {+ Ok(line) => Ok(Filter {+ file_substring: parts[1].to_string(),+ line_number: Some(line),+ }),+ Err(_) => Err(format!("Cannot parse line number from '{s}'")),+ }+ } else {+ Ok(Filter {+ file_substring: s.to_string(),+ line_number: None,+ })+ }+ }+}++/// Given a list of [`Filter`]s, determines if the whole file in the provided+/// path can be skipped.+///+/// - If there's at least 1 filter whose file name is a substring of the provided path,+/// it returns true.+/// - If the provided filter list is empty, it returns false.+pub fn should_skip_file(path: &Path, filters: &[Filter]) -> bool {+ if filters.is_empty() {+ return false;+ }++ let path_string = path.to_string_lossy();+ for filter in filters {+ if path_string.contains(&filter.file_substring) {+ return false;+ }+ }+ true+}++/// Determines whether a certain sqllogictest record should be skipped given the provided+/// filters.+///+/// If there's at least 1 matching filter, or the filter list is empty, it returns false.+///+/// There are certain records that will never be skipped even if they are not matched+/// by any filters, like CREATE TABLE, INSERT INTO, DROP or SELECT * INTO statements,+/// as they populate tables necessary for other tests to work.+pub fn should_skip_record<D: AsyncDB>(+ record: &Record<D::ColumnType>,+ filters: &[Filter],+) -> bool {+ if filters.is_empty() {+ return false;+ }++ let (sql, loc) = match record {+ Record::Statement { sql, loc, .. } => (sql, loc),+ Record::Query { sql, loc, .. } => (sql, loc),+ _ => return false,+ };++ let statement = if let Some(statement) = parse_or_none(sql, "Postgres") {+ statement+ } else if let Some(statement) = parse_or_none(sql, "generic") {+ statement+ } else {+ return false;+ };++ if !statement_is_skippable(&statement) {+ return false;+ }++ for filter in filters {+ if !loc.file().contains(&filter.file_substring) {+ continue;+ }+ if let Some(line_num) = filter.line_number {+ if loc.line() != line_num {+ continue;+ }+ }++ // This filter matches both file name substring and the exact+ // line number (if one was provided), so don't skip it.+ return false;+ }++ true+}++fn statement_is_skippable(statement: &Statement) -> bool {+ // Only SQL statements can be skipped.+ let Statement::Statement(sql_stmt) = statement else {+ return false;+ };++ // Cannot skip SELECT INTO statements, as they can also create tables+ // that further test cases will use.+ if let SqlStatement::Query(v) = sql_stmt.as_ref() {+ if let SetExpr::Select(v) = v.body.as_ref() {+ if v.into.is_some() {+ return false;+ }+ }+ }++ // Only SELECT and EXPLAIN statements can be skipped, as any other+ // statement might be populating tables that future test cases will use.+ matches!(+ sql_stmt.as_ref(),+ SqlStatement::Query(_) | SqlStatement::Explain { .. }+ )+}++fn parse_or_none(sql: &str, dialect: &str) -> Option<Statement> {+ let Ok(Ok(Some(statement))) = DFParserBuilder::new(sql)+ .with_dialect(dialect_from_str(dialect).unwrap().as_ref())+ .build()+ .map(|mut v| v.parse_statements().map(|mut v| v.pop_front()))+ else {+ return None;+ };+ Some(statement)+}diff --git a/datafusion/sqllogictest/src/lib.rs b/datafusion/sqllogictest/src/lib.rsindex 1a208aa3fa..cf190f1a93 100644--- a/datafusion/sqllogictest/src/lib.rs+++ b/datafusion/sqllogictest/src/lib.rs@@ -38,8 +38,10 @@ pub use engines::DataFusion;#[cfg(feature = "postgres")]pub use engines::Postgres;+mod filters;mod test_context;mod util;+pub use filters::*;pub use test_context::TestContext;pub use util::*;