alamb commented on code in PR #4496:
URL: https://github.com/apache/arrow-datafusion/pull/4496#discussion_r1038958853
##########
datafusion/core/src/execution/context.rs:
##########
@@ -958,6 +958,22 @@ impl SessionContext {
}
}
+ /// Return a [`TabelProvider`] for the specified table.
+ pub fn table_provider<'a>(
Review Comment:
👍 it might be nice to refactor `fn table()` to call this function now to
avoid some duplication.
##########
datafusion/core/tests/sqllogictests/src/main.rs:
##########
@@ -138,7 +140,14 @@ fn format_batches(batches: &[RecordBatch]) ->
Result<String> {
}
async fn run_query(ctx: &SessionContext, sql: impl Into<String>) ->
Result<String> {
- let df = ctx.sql(&sql.into()).await.unwrap();
+ let sql = sql.into();
+ // Check if the sql is `insert`
+ if sql.trim_start().to_lowercase().starts_with("insert") {
+ // Process the insert statement
+ insert(ctx, sql).await?;
+ return Ok("".to_string());
+ }
Review Comment:
👍 I like this basic approach (special case the sql and route it to the test
runner implementation).
One thing that might be worth doing is to actually try and parse the input
into sql, to detect INSERT statements though I think string manipulation is
fine too or we could do this later
```rust
// Handle any test only special case statements
let sql = sql.into();
match DFParser::parse_sql(&sql) {
Ok(Statement(Insert)) => {
//debug!("Parsed statement: {:#?}", stmt);
}
Err(_) => {
// ignore anything else, including errors -- they will be
handled by the sql context below
}
};
```
##########
datafusion/core/tests/sqllogictests/test_files/insert.slt:
##########
@@ -0,0 +1,50 @@
+# 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.
+
+statement ok
+CREATE TABLE users AS VALUES(1,2),(2,3);
+
+query II rowsort
+select * from users;
+----
+1 2
+2 3
+
+statement ok
+insert into users values(2, 4);
+
+query II rowsort
+select * from users;
+----
+1 2
+2 3
+2 4
+
+statement ok
+insert into users values(1 + 10, 20);
+
+query II rowsort
+select * from users;
+----
+1 2
+2 3
+2 4
+11 20
+
+# Test insert into a undefined table
+statement error
Review Comment:
👍
##########
datafusion/core/tests/sqllogictests/src/error.rs:
##########
@@ -0,0 +1,83 @@
+// 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::DataFusionError;
+use sqllogictest::TestError;
+use sqlparser::parser::ParserError;
+use std::error;
+use std::fmt::{Display, Formatter};
+
+pub type Result<T> = std::result::Result<T, DFSqlLogicTestError>;
+
+/// DataFusion sql-logicaltest error
+#[derive(Debug)]
+pub enum DFSqlLogicTestError {
+ /// Error from sqllogictest-rs
+ SqlLogicTest(TestError),
+ /// Error from datafusion
+ DataFusion(DataFusionError),
+ /// Error returned when SQL is syntactically incorrect.
+ Sql(ParserError),
+ /// Error returned on a branch that we know it is possible
+ /// but to which we still have no implementation for.
+ /// Often, these errors are tracked in our issue tracker.
+ NotImplemented(String),
+ /// Error returned from DFSqlLogicTest inner
+ Internal(String),
Review Comment:
I suggest we simply panic in the sqllogic runner in these cases so the
location of the error is easier to see
##########
datafusion/core/tests/sqllogictests/src/insert/mod.rs:
##########
@@ -0,0 +1,96 @@
+// 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.
+
+mod util;
+
+use crate::error::{DFSqlLogicTestError, Result};
+use crate::insert::util::LogicTestContextProvider;
+use datafusion::datasource::MemTable;
+use datafusion::prelude::SessionContext;
+use datafusion_common::{DFSchema, DataFusionError};
+use datafusion_expr::Expr as DFExpr;
+use datafusion_sql::parser::{DFParser, Statement};
+use datafusion_sql::planner::SqlToRel;
+use sqlparser::ast::{Expr, SetExpr, Statement as SQLStatement};
+use std::collections::HashMap;
+
+pub async fn insert(ctx: &SessionContext, sql: String) -> Result<String> {
+ // First, use sqlparser to get table name and insert values
+ let mut table_name = "".to_string();
+ let mut insert_values: Vec<Vec<Expr>> = vec![];
+ if let Statement::Statement(statement) = &DFParser::parse_sql(&sql)?[0] {
+ if let SQLStatement::Insert {
+ table_name: name,
+ source,
+ ..
+ } = &**statement
+ {
+ // Todo: check columns match table schema
+ table_name = name.to_string();
+ match &*source.body {
+ SetExpr::Values(values) => {
+ insert_values = values.0.clone();
+ }
+ _ => {
+ return Err(DFSqlLogicTestError::NotImplemented(
+ "Only support insert values".to_string(),
+ ));
+ }
+ }
+ }
+ } else {
+ return Err(DFSqlLogicTestError::Internal(format!(
+ "{:?} not an insert statement",
+ sql
+ )));
+ }
+
+ // Second, get table by table name
+ // Here we assume table must be in memory table.
+ let table_provider = ctx.table_provider(table_name.as_str())?;
+ let table_batches = table_provider
+ .as_any()
+ .downcast_ref::<MemTable>()
+ .ok_or_else(|| {
+ DFSqlLogicTestError::NotImplemented(
+ "only support use memory table in logictest".to_string(),
+ )
+ })?
+ .get_batches();
+
+ // Third, transfer insert values to `RecordBatch`
+ // Attention: schema info can be ignored. (insert values don't contain
schema info)
+ let sql_to_rel = SqlToRel::new(&LogicTestContextProvider {});
+ let mut insert_batches = Vec::with_capacity(insert_values.len());
+ for row in insert_values.into_iter() {
+ let logical_exprs = row
+ .into_iter()
+ .map(|expr| {
+ sql_to_rel.sql_to_rex(expr, &DFSchema::empty(), &mut
HashMap::new())
+ })
+ .collect::<std::result::Result<Vec<DFExpr>, DataFusionError>>()?;
+ // Directly use `select` to get `RecordBatch`
+ let dataframe = ctx.read_empty()?;
+ insert_batches.push(dataframe.select(logical_exprs)?.collect().await?)
+ }
+
+ // Final, append the `RecordBatch` to memtable's batches
+ let mut table_batches = table_batches.write();
Review Comment:
Rather than changing the batches in the existing memtable, what would you
think about creating a new memtable with the same name with the new values
(rather than modifying the original one)
I think you might be able to avoid changes to SessionContext and MemTable
entirely.
Something like this (untested)
```rust
// fetch existing batches
let mut existing_batches = ctx.table(table_name.as_str()).collect();
// append new batch
exsiting_batches.extend(insert_batches)
// Replace table provider provider
let new_provider = MemTable::try_new(batches[0].schema(), vec![batches]);
ctx.register_table(table_name, new_provider)
```
##########
datafusion/core/tests/sqllogictests/test_files/insert.slt:
##########
@@ -0,0 +1,50 @@
+# 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.
+
+statement ok
+CREATE TABLE users AS VALUES(1,2),(2,3);
Review Comment:

##########
datafusion/core/tests/sqllogictests/src/error.rs:
##########
@@ -0,0 +1,83 @@
+// 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::DataFusionError;
+use sqllogictest::TestError;
+use sqlparser::parser::ParserError;
+use std::error;
+use std::fmt::{Display, Formatter};
+
+pub type Result<T> = std::result::Result<T, DFSqlLogicTestError>;
+
+/// DataFusion sql-logicaltest error
+#[derive(Debug)]
+pub enum DFSqlLogicTestError {
Review Comment:
👍 this is a good idea
##########
datafusion/core/tests/sqllogictests/src/insert/mod.rs:
##########
@@ -0,0 +1,96 @@
+// 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.
+
+mod util;
+
+use crate::error::{DFSqlLogicTestError, Result};
+use crate::insert::util::LogicTestContextProvider;
+use datafusion::datasource::MemTable;
+use datafusion::prelude::SessionContext;
+use datafusion_common::{DFSchema, DataFusionError};
+use datafusion_expr::Expr as DFExpr;
+use datafusion_sql::parser::{DFParser, Statement};
+use datafusion_sql::planner::SqlToRel;
+use sqlparser::ast::{Expr, SetExpr, Statement as SQLStatement};
+use std::collections::HashMap;
+
+pub async fn insert(ctx: &SessionContext, sql: String) -> Result<String> {
+ // First, use sqlparser to get table name and insert values
+ let mut table_name = "".to_string();
+ let mut insert_values: Vec<Vec<Expr>> = vec![];
+ if let Statement::Statement(statement) = &DFParser::parse_sql(&sql)?[0] {
+ if let SQLStatement::Insert {
+ table_name: name,
+ source,
+ ..
+ } = &**statement
+ {
+ // Todo: check columns match table schema
+ table_name = name.to_string();
+ match &*source.body {
+ SetExpr::Values(values) => {
Review Comment:
This is very clever
--
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]