diff --git a/Cargo.toml b/Cargo.toml index c38de61c..acf50943 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,55 +1,94 @@ [package] name = "gluesql" -version = "0.5.0" -authors = ["Taehoon Moon "] +version = "0.6.0-planner-beta" +authors = ["Taehoon Moon ", "Kyran Gostelow "] edition = "2018" description = "GlueSQL - Open source SQL database engine fully written in Rust with pure functional execution layer, easily swappable storage and web assembly support!" license = "Apache-2.0" repository = "https://github.com/gluesql/gluesql" documentation = "https://docs.rs/gluesql/" readme = "README.md" -keywords = ["sql-database", "sql", "functional", "no-mut-in-the-middle", "webassembly"] +keywords = ["sql-database", "sql", "functional", "webassembly"] [package.metadata.docs.rs] all-features = true [features] -default = ["sled-storage", "alter-table", "expanded-api", "auto-increment"] + default = [ + # Storages + "sled-storage", + "csv-storage", + # Performance + "multithreading",# TODO: Multithreading optional (Remove uses without CFG) + # Functionality + "alter-table", + "auto-increment", + # Data + "double_quote_strings", + "implicit_float_conversion", + # API + "expanded-api", + ] -# ALTER TABLE is optional. -# You can include whether ALTER TABLE support or not for your custom database implementation. -alter-table = [] -auto-increment = [] + # Storages + sled-storage = ["sled", "bincode"] + csv-storage = ["csv", "linecount"] -expanded-api = ["serde_json"] + # Performance + multithreading = ["rayon"] + + # Functionality + alter-table = [] + auto-increment = [] + + # Data + double_quote_strings = [] + implicit_float_conversion = [] + + # API + expanded-api = ["serde_json"] -# Who wants to make a custom storage engine, -# default storage engine sled-storage is not required. -sled-storage = ["sled", "bincode"] [dependencies] -async-trait = "0.1.41" -async-recursion = "0.3.1" -boolinator = "2.4.0" -futures = "0.3" -indexmap = "1.6.0" -im-rc = "15.0.0" -iter-enum = "0.2.4" -itertools = "0.9.0" -pin-project = "1.0.1" -serde = { version = "1.0.117", features = ["derive"] } -sqlparser = { version = "0.8.0", features = ["serde"] } -thiserror = "1.0.21" -fstrings = "0.2.3" -regex = "1" - -# OPTIONAL DEPENDENCIES -# dependencies for sled-storage -serde_json = { version = "1.0.0", optional = true } - -# dependencies for sled-storage -bincode = { version = "1.3.1", optional = true } -sled = { version = "0.34.6", optional = true } + async-trait = "0.1.41" + async-recursion = "0.3.1" + boolinator = "2.4.0" + futures = "0.3" + indexmap = "1.6.0" + im-rc = "15.0.0" + iter-enum = "0.2.4" + itertools = "0.9.0" + pin-project = "1.0.1" + serde = { version = "1.0.117", features = ["derive"] } + sqlparser = { version = "0.8.0", features = ["serde"] } + thiserror = "1.0.21" + fstrings = "0.2.3" + regex = "1" + chrono = { version = "0.4.19", features = ["serde", "unstable-locales"] } + + # OPTIONAL DEPENDENCIES + # Multiple + # Sled and Expanded API + serde_json = { version = "1.0.0", optional = true } + + # Storages + # Sled + bincode = { version = "1.3.1", optional = true } + sled = { version = "0.34.6", optional = true } + + # CSV + csv = { version = "1.1.6", optional = true } + linecount = { version = "0.1.0", optional = true } + + # Performance + # Multithreading + rayon = { version = "1.5.0", optional = true } + + # Functionality + + # Data + + # API [dev-dependencies] tokio = { version = "0.3.3", features = ["macros", "rt"] } diff --git a/examples/api_usage.rs b/examples/api_usage.rs index de48e4e8..4ffd40b5 100644 --- a/examples/api_usage.rs +++ b/examples/api_usage.rs @@ -1,3 +1,4 @@ +/* #[cfg(feature = "sled-storage")] use futures::executor::block_on; #[cfg(feature = "sled-storage")] @@ -36,12 +37,12 @@ fn mutable_api() { for query in parse(sqls).unwrap() { glue.execute(&query).unwrap(); } -} +}*/ fn main() { #[cfg(feature = "sled-storage")] { - mutable_api(); - immutable_api(); + /*mutable_api(); + immutable_api();*/ } } diff --git a/examples/hello_world.rs b/examples/hello_world.rs index 6e1a37df..37462b62 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -1,4 +1,4 @@ -#[cfg(feature = "sled-storage")] +/*#[cfg(feature = "sled-storage")] mod hello_world { use gluesql::{parse, Glue, Payload, SledStorage, Value}; @@ -64,8 +64,8 @@ mod hello_world { println!("Hello {}!", to_greet); // Will always output "Hello World!" } } - +*/ fn main() { - #[cfg(feature = "sled-storage")] - hello_world::run(); + /*#[cfg(feature = "sled-storage")] + hello_world::run();*/ } diff --git a/examples/sled_multi_threaded.rs b/examples/sled_multi_threaded.rs index 269aaa74..c8a4d154 100644 --- a/examples/sled_multi_threaded.rs +++ b/examples/sled_multi_threaded.rs @@ -1,3 +1,4 @@ +/* #[cfg(feature = "sled-storage")] mod sled_multi_threaded { use { @@ -73,8 +74,8 @@ mod sled_multi_threaded { println!("Hello {}!", to_greet); // Will typically output "Hello Foo!" but will sometimes output "Hello World!"; depends on which thread finished first. } } - +*/ fn main() { - #[cfg(feature = "sled-storage")] - sled_multi_threaded::run(); + /*#[cfg(feature = "sled-storage")] + sled_multi_threaded::run();*/ } diff --git a/examples/using_config.rs b/examples/using_config.rs index c9991896..adb9f975 100644 --- a/examples/using_config.rs +++ b/examples/using_config.rs @@ -6,7 +6,7 @@ use gluesql::{parse, sled, Glue, SledStorage}; #[cfg(feature = "sled-storage")] fn main() { - let config = sled::Config::default() + /*let config = sled::Config::default() .path("data/using_config") .temporary(true) .mode(sled::Mode::HighThroughput); @@ -24,7 +24,7 @@ fn main() { for query in parse(sqls).unwrap() { glue.execute(&query).unwrap(); - } + }*/ } #[cfg(not(feature = "sled-storage"))] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..bff22551 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +#hard_tabs = true \ No newline at end of file diff --git a/src/data/literal.rs b/src/data/literal.rs deleted file mode 100644 index c816f372..00000000 --- a/src/data/literal.rs +++ /dev/null @@ -1,171 +0,0 @@ -use { - crate::result::{Error, Result}, - sqlparser::ast::{Expr, Ident, Value as AstValue}, - std::{borrow::Cow, cmp::Ordering, convert::TryFrom, fmt::Debug}, - Literal::*, -}; - -use {serde::Serialize, thiserror::Error}; - -#[derive(Error, Serialize, Debug, PartialEq)] -pub enum LiteralError { - #[error("unsupported literal type: {0}")] - UnsupportedLiteralType(String), - - #[error("unsupported expr: {0}")] - UnsupportedExpr(String), - - #[error("unsupported literal binary arithmetic between {0} and {1}")] - UnsupportedBinaryArithmetic(String, String), - - #[error("literal unary operation on non-numeric")] - UnaryOperationOnNonNumeric, - - #[error("unreachable literal binary arithmetic")] - UnreachableBinaryArithmetic, - - #[error("unreachable literal unary operation")] - UnreachableUnaryOperation, -} - -#[derive(Clone, Debug)] -pub enum Literal<'a> { - Boolean(bool), - Number(Cow<'a, String>), - Text(Cow<'a, String>), - Null, -} - -impl<'a> TryFrom<&'a AstValue> for Literal<'a> { - type Error = Error; - - fn try_from(ast_value: &'a AstValue) -> Result { - let literal = match ast_value { - AstValue::Boolean(v) => Boolean(*v), - AstValue::Number(v, false) => Number(Cow::Borrowed(v)), - AstValue::SingleQuotedString(v) => Text(Cow::Borrowed(v)), - AstValue::Null => Null, - _ => { - return Err(LiteralError::UnsupportedLiteralType(ast_value.to_string()).into()); - } - }; - - Ok(literal) - } -} - -impl<'a> TryFrom<&'a Expr> for Literal<'a> { - type Error = Error; - - fn try_from(expr: &'a Expr) -> Result { - match expr { - Expr::Value(literal) => Literal::try_from(literal), - Expr::Identifier(Ident { value, .. }) => Ok(Literal::Text(Cow::Borrowed(value))), - _ => Err(LiteralError::UnsupportedExpr(expr.to_string()).into()), - } - } -} - -impl PartialEq> for Literal<'_> { - fn eq(&self, other: &Literal) -> bool { - match (self, other) { - (Boolean(l), Boolean(r)) => l == r, - (Number(l), Number(r)) | (Text(l), Text(r)) => l == r, - _ => false, - } - } -} - -impl PartialOrd> for Literal<'_> { - fn partial_cmp(&self, other: &Literal) -> Option { - match (self, other) { - (Boolean(l), Boolean(r)) => Some(l.cmp(r)), - (Number(l), Number(r)) => match (l.parse::(), r.parse::()) { - (Ok(l), Ok(r)) => Some(l.cmp(&r)), - (_, Ok(r)) => match l.parse::() { - Ok(l) => l.partial_cmp(&(r as f64)), - _ => None, - }, - (Ok(l), _) => match r.parse::() { - Ok(r) => (l as f64).partial_cmp(&r), - _ => None, - }, - _ => match (l.parse::(), r.parse::()) { - (Ok(l), Ok(r)) => l.partial_cmp(&r), - _ => None, - }, - }, - (Text(l), Text(r)) => Some(l.cmp(r)), - _ => None, - } - } -} - -macro_rules! binary_op { - ($name:ident, $op:tt) => { - pub fn $name<'b>(&self, other: &Literal<'a>) -> Result> { - match (self, other) { - (Number(l), Number(r)) => { - match (l.parse::(), r.parse::()) { - (Ok(l), Ok(r)) => Ok((l $op r).to_string()), - (Ok(l), _) => match r.parse::() { - Ok(r) => Ok(((l as f64) $op r).to_string()), - _ => Err(LiteralError::UnreachableBinaryArithmetic.into()), - }, - (_, Ok(r)) => match l.parse::() { - Ok(l) => Ok((l $op (r as f64)).to_string()), - _ => Err(LiteralError::UnreachableBinaryArithmetic.into()), - }, - (_, _) => match (l.parse::(), r.parse::()) { - (Ok(l), Ok(r)) => Ok((l $op r).to_string()), - _ => Err(LiteralError::UnreachableBinaryArithmetic.into()), - }, - }.map(|v| Number(Cow::Owned(v))) - } - (Null, Number(_)) - | (Number(_), Null) - | (Null, Null) => { - Ok(Literal::Null) - } - _ => Err( - LiteralError::UnsupportedBinaryArithmetic( - format!("{:?}", self), - format!("{:?}", other), - ).into() - ), - } - } - } -} - -impl<'a> Literal<'a> { - pub fn unary_plus(&self) -> Result { - match self { - Number(v) => v - .parse::() - .map(|_| self.to_owned()) - .or_else(|_| v.parse::().map(|_| self.to_owned())) - .map_err(|_| LiteralError::UnreachableUnaryOperation.into()), - Null => Ok(Null), - _ => Err(LiteralError::UnaryOperationOnNonNumeric.into()), - } - } - - pub fn unary_minus(&self) -> Result { - match self { - Number(v) => v - .parse::() - .map(|v| (-v).to_string()) - .or_else(|_| v.parse::().map(|v| (-v).to_string())) - .map(|v| Number(Cow::Owned(v))) - .map_err(|_| LiteralError::UnreachableUnaryOperation.into()), - Null => Ok(Null), - _ => Err(LiteralError::UnaryOperationOnNonNumeric.into()), - } - } - - binary_op!(add, +); - binary_op!(subtract, -); - binary_op!(multiply, *); - binary_op!(divide, /); -} diff --git a/src/data/mod.rs b/src/data/mod.rs index 019456a3..9fed8c69 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -1,13 +1,11 @@ -mod literal; mod row; pub mod schema; mod table; pub mod value; pub use { - literal::{Literal, LiteralError}, - row::{bulk_build_rows_expr, bulk_build_rows_row, Row, RowError}, + row::{Row, RowError}, schema::Schema, table::{get_name, Table, TableError}, - value::{Value, ValueError}, + value::*, }; diff --git a/src/data/row.rs b/src/data/row.rs index 265a7212..cb614ea6 100644 --- a/src/data/row.rs +++ b/src/data/row.rs @@ -1,29 +1,14 @@ use { - crate::{ - data::{schema::ColumnDefExt, value::TryFromLiteral, Value}, - evaluate, - result::Result, - store::Store, - }, + crate::{data::Value, result::Result}, serde::{Deserialize, Serialize}, - sqlparser::ast::{ColumnDef, DataType, Expr, Ident}, std::fmt::Debug, thiserror::Error, }; #[derive(Error, Serialize, Debug, PartialEq)] pub enum RowError { - #[error("lack of required column: {0}")] - LackOfRequiredColumn(String), - - #[error("columns and values must match")] - WrongNumberOfValues, - #[error("conflict! row cannot be empty")] ConflictOnEmptyRow, - - #[error("unreachable")] - Unreachable, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -40,166 +25,4 @@ impl Row { .next() .ok_or_else(|| RowError::ConflictOnEmptyRow.into()) } - - pub async fn new( - storage: &dyn Store, - column_defs: &[ColumnDef], - columns: &[Ident], - expressions: &[Expr], - ) -> Result { - Ok(bulk_build_rows_expr( - storage, - column_defs, - columns, - vec![expressions.to_vec()], - false, - false, - ) - .await? - .into_iter() - .next() - .unwrap()) - } -} - -async fn evaluate_expression( - storage: &dyn Store, - expression: &Expr, - data_type: &DataType, -) -> Result { - Value::try_from_evaluated( - data_type, - evaluate(storage, None, None, expression, false).await?, - ) -} - -// For macro TODO: find a better way -async fn process_value( - _a: &dyn Store, - value: Value, - _b: &DataType, -) -> Result { - Ok(value) -} - -async fn process_expr( - storage: &dyn Store, - expression: Expr, - data_type: &DataType, -) -> Result { - evaluate_expression(storage, &expression, data_type).await -} - -macro_rules! bulk_build_rows { - ($type: ty, $name: ident, $processing_function: ident) => { - pub async fn $name( - storage: &dyn Store, - column_defs: &[ColumnDef], - columns: &[Ident], - rows: Vec>, - do_default: bool, - do_validate: bool, - ) -> Result> { - // FAIL: No mut - let table_columns_count = column_defs.len(); - let selection_columns_count = if columns.len() == 0 { - table_columns_count - } else { - columns.len() - }; - - if rows.iter().any(|row| row.len() != selection_columns_count) { - return Err(RowError::WrongNumberOfValues.into()); - } // KG: I don't like this - - let mut output_values: Vec> = Vec::new(); - output_values.resize(rows.len(), Vec::new()); - for row in &mut output_values { - row.resize(table_columns_count, Value::Null); - } - // This feels slow, how can we initialise better? - let column_defs_indexed = column_defs.into_iter().enumerate(); - for (column_index, column_def) in column_defs_indexed { - let ColumnDef { - name, data_type, .. - } = column_def; - - let name = name.to_string(); - let values_index = if columns.len() == 0 { - Some(column_index) - } else { - columns.iter().position(|target| target.value == name) - }; - - let nullable = column_def.is_nullable(); - #[cfg(feature = "auto-increment")] - let nullable = nullable || column_def.is_auto_incremented(); - - let default = column_def.get_default(); - let failure_value = if do_default && default.is_some() { - if let Some(default) = default { - FailureValue::Default(default) // We can't execute this here because some defaults might be functions and some functions might not always have the same result. - } else { - return Err(RowError::Unreachable.into()); - } - } else if nullable { - FailureValue::Null - } else { - FailureValue::Throw - }; - - for (row_index, row) in rows.iter().enumerate() { - output_values[row_index][column_index] = if let Some(index) = values_index { - let found = row[index].clone(); - let value = $processing_function(storage, found, data_type).await?; - - if do_validate { - value.validate_null(nullable)?; - value.validate_type(data_type)?; - } - value - } else { - match failure_value { - FailureValue::Throw => { - return Err(RowError::LackOfRequiredColumn(name.clone()).into()); - } - FailureValue::Null => Value::Null, - FailureValue::Default(expression) => { - evaluate_expression(storage, expression, data_type).await? - } - } - } - } - } - Ok(output_values.into_iter().map(Row).collect()) - } - }; -} - -bulk_build_rows!(Expr, bulk_build_rows_expr, process_expr); -bulk_build_rows!(Value, bulk_build_rows_value, process_value); - -pub async fn bulk_build_rows_row( - storage: &dyn Store, - column_defs: &[ColumnDef], - columns: &[Ident], - rows: Vec, - do_default: bool, - do_validate: bool, -) -> Result> { - bulk_build_rows_value( - storage, - column_defs, - columns, - rows.into_iter().map(|row| row.0).collect(), - do_default, - do_validate, - ) - .await -} - -enum FailureValue<'a> { - Default(&'a Expr), - Null, - Throw, } diff --git a/src/data/schema.rs b/src/data/schema.rs index a442c066..7631e968 100644 --- a/src/data/schema.rs +++ b/src/data/schema.rs @@ -18,6 +18,8 @@ pub struct Schema { pub trait ColumnDefExt { fn is_nullable(&self) -> bool; + fn is_unique(&self) -> bool; + #[cfg(feature = "auto-increment")] fn is_auto_incremented(&self) -> bool; @@ -28,7 +30,13 @@ impl ColumnDefExt for ColumnDef { fn is_nullable(&self) -> bool { self.options .iter() - .any(|ColumnOptionDef { option, .. }| option == &ColumnOption::Null) + .any(|ColumnOptionDef { option, .. }| matches!(option, ColumnOption::Null)) + } + + fn is_unique(&self) -> bool { + self.options + .iter() + .any(|ColumnOptionDef { option, .. }| matches!(option, ColumnOption::Unique { .. })) } #[cfg(feature = "auto-increment")] diff --git a/src/data/value/cast.rs b/src/data/value/cast.rs new file mode 100644 index 00000000..89a63132 --- /dev/null +++ b/src/data/value/cast.rs @@ -0,0 +1,251 @@ +use { + super::{Convert, Value, ValueError}, + crate::{Error, Result}, + chrono::{NaiveDate, NaiveDateTime, NaiveTime, ParseError}, + std::convert::TryInto, +}; + +pub trait Cast { + fn cast(self) -> Result; +} +pub trait CastWithRules { + fn cast_with_rule(self, rule: Self) -> Result; +} + +// Cores +impl Cast for Value { + fn cast(self) -> Result { + self.clone().convert().or(Ok(match self { + Value::Bool(value) => value, + Value::I64(value) => match value { + 1 => true, + 0 => false, + _ => return Err(ValueError::ImpossibleCast.into()), + }, + Value::F64(value) => { + if value.eq(&1.0) { + true + } else if value.eq(&0.0) { + false + } else { + return Err(ValueError::ImpossibleCast.into()); + } + } + Value::Str(value) => match value.to_uppercase().as_str() { + "TRUE" => true, + "FALSE" => false, + _ => return Err(ValueError::ImpossibleCast.into()), + }, + Value::Null => return Err(ValueError::ImpossibleCast.into()), + _ => unimplemented!(), + })) + } +} + +impl Cast for Value { + fn cast(self) -> Result { + self.clone().convert().or(Ok(match self { + Value::Bool(value) => { + if value { + 1 + } else { + 0 + } + } + Value::I64(value) => value, + Value::F64(value) => value.trunc() as i64, + Value::Str(value) => value.parse().map_err(|_| ValueError::ImpossibleCast)?, + Value::Null => return Err(ValueError::ImpossibleCast.into()), + _ => unimplemented!(), + })) + } +} + +impl Cast for Value { + fn cast(self) -> Result { + self.clone().convert().or(Ok(match self { + Value::Bool(value) => { + if value { + 1.0 + } else { + 0.0 + } + } + Value::I64(value) => (value as f64).trunc(), + Value::F64(value) => value, + Value::Str(value) => value.parse().map_err(|_| ValueError::ImpossibleCast)?, + Value::Null => return Err(ValueError::ImpossibleCast.into()), + _ => unimplemented!(), + })) + } +} +impl Cast for Value { + fn cast(self) -> Result { + self.clone().convert().or(Ok(match self { + Value::Bool(value) => (if value { "TRUE" } else { "FALSE" }).to_string(), + Value::I64(value) => value.to_string(), + Value::F64(value) => value.to_string(), + Value::Str(value) => value, + Value::Null => String::from("NULL"), + _ => unimplemented!(), + })) + } +} + +// Utilities +impl Cast for Value { + fn cast(self) -> Result { + let int: i64 = self.cast()?; + int.try_into() + .map_err(|_| ValueError::ImpossibleCast.into()) + } +} + +// Non-Core +impl CastWithRules for Value { + fn cast_with_rule(self, rule: Self) -> Result { + match rule { + Value::I64(000) | Value::Bool(true) => self.cast(), + _ => Err(ValueError::InvalidConversionRule.into()), + } + } +} +impl CastWithRules for Value { + fn cast_with_rule(self, rule: Self) -> Result { + match rule { + Value::I64(000) | Value::Bool(true) => self.cast(), + _ => Err(ValueError::InvalidConversionRule.into()), + } + } +} +impl CastWithRules for Value { + fn cast_with_rule(self, rule: Self) -> Result { + match rule { + Value::I64(000) | Value::Bool(true) => self.cast(), + _ => Err(ValueError::InvalidConversionRule.into()), + } + } +} +impl CastWithRules for Value { + fn cast_with_rule(self, rule: Self) -> Result { + match rule { + Value::I64(000) | Value::Bool(true) => self.cast(), + Value::Str(specified) if specified == String::from("DATETIME") => { + Ok(NaiveDateTime::from_timestamp(self.convert()?, 0) + .format("%F %T") + .to_string()) + } + Value::Str(format) if matches!(self, Value::I64(..)) => { + // TODO: TIMESTAMP type + Ok(NaiveDateTime::from_timestamp(self.convert()?, 0) + .format(&format) + .to_string()) + } + _ => Err(ValueError::InvalidConversionRule.into()), + } + } +} + +// Non-SQL +// - DateTime +fn parse_error_into(error: ParseError) -> Error { + ValueError::DateTimeParseError(format!("{:?}", error)).into() +} +impl Cast for Value { + // Default (from Timestamp) + fn cast(self) -> Result { + let timestamp: i64 = self.cast()?; + NaiveDateTime::from_timestamp_opt(timestamp, 0).ok_or(ValueError::ImpossibleCast.into()) + } +} +impl CastWithRules for Value { + fn cast_with_rule(self, rule: Self) -> Result { + fn for_format_datetime(string: Value, format: &str) -> Result { + let string: String = string.cast()?; + let string: &str = string.as_str(); + NaiveDateTime::parse_from_str(string, format).map_err(parse_error_into) + } + fn for_format_date(string: Value, format: &str) -> Result { + let string: String = string.cast()?; + let string: &str = string.as_str(); + Ok(NaiveDate::parse_from_str(string, format) + .map_err(parse_error_into)? + .and_hms(0, 0, 0)) + } + fn for_format_time(string: Value, format: &str) -> Result { + let string: String = string.cast()?; + let string: &str = string.as_str(); + Ok(NaiveDateTime::from_timestamp(0, 0) + .date() + .and_time(NaiveTime::parse_from_str(string, format).map_err(parse_error_into)?)) + } + fn try_rules(try_value: &Value, rules: &[i64]) -> Result { + rules + .iter() + .find_map(|try_rule| try_value.clone().cast_with_rule((*try_rule).into()).ok()) + .ok_or(ValueError::ParseError(try_value.clone(), "TIMESTAMP").into()) + } + const TRY_RULES_TIMESTAMP: [i64; 1] = [000]; + const TRY_RULES_DATETIME: [i64; 7] = [010, 011, 020, 021, 030, 031, 060]; + const TRY_RULES_DATE: [i64; 4] = [022, 032, 033, 061]; + const TRY_RULES_TIME: [i64; 2] = [100, 101]; + + match rule { + Value::Bool(true) => try_rules(&self, &TRY_RULES_TIMESTAMP), + Value::Str(custom) => match custom.as_str() { + "TIMESTAMP" => try_rules(&self, &TRY_RULES_TIMESTAMP), + "DATETIME" => try_rules(&self, &TRY_RULES_DATETIME), + "DATE" => try_rules(&self, &TRY_RULES_DATE), + "TIME" => try_rules(&self, &TRY_RULES_TIME), + custom_format => for_format_datetime(self.clone(), custom_format) + .or(for_format_date(self.clone(), custom_format)) + .or(for_format_time(self, custom_format)), + }, + Value::I64(000) => { + // From Timestamp (Default) + self.cast() + } + // 01* - Statically specifically defined by accepted standards bodies + /*Value::I64(010) => { + // From RFC 3339 format + let datetime_string: String = self.cast()?; + DateTime::parse_from_rfc3339(datetime_string.as_str()).map_err(parse_error_into) + } + Value::I64(011) => { + // From RFC 2822 format + let datetime_string: String = self.cast()?; + DateTime::parse_from_rfc2822(datetime_string.as_str()).map_err(parse_error_into) + }*/ + // 02* - Conventional + // - From Database format (YYYY-MM-DD HH:MM:SS) + Value::I64(020) => for_format_datetime(self, "%F %T"), + // - From Database format, no seconds (YYYY-MM-DD HH:MM) + Value::I64(021) => for_format_datetime(self, "%F %R"), + // - From Database format, no time (YYYY-MM-DD) + Value::I64(022) => for_format_date(self, "%F"), + + // 0(3-4)* - Normal + // - From Database format, grossified time (YYYY-MM-DD HH:MM:SS (AM/PM)) + Value::I64(030) => for_format_datetime(self, "%F %r"), + // - From Database format, grossified time, no seconds (YYYY-MM-DD HH:MM (AM/PM)) + Value::I64(031) => for_format_datetime(self, "%I:%M %p"), + // - From dd-Mon-YYYY + Value::I64(032) => for_format_date(self, "%v"), + // - From dd-Mon-YY + Value::I64(033) => for_format_date(self, "%e-%b-%y"), + + // 0(5-8)* - Locales + // 06* - Australia + Value::I64(060) => for_format_datetime(self, "%d/%m/%Y %H:%M"), + Value::I64(061) => for_format_date(self, "%d/%m/%Y"), + // (TODO(?)) + + // 10* - Time + // - (HH:MM:SS) + Value::I64(100) => for_format_time(self, "%T"), + // - No seconds (HH:MM) + Value::I64(101) => for_format_time(self, "%R"), + _ => Err(ValueError::InvalidConversionRule.into()), + } + } +} diff --git a/src/data/value/convert.rs b/src/data/value/convert.rs new file mode 100644 index 00000000..1a454d3d --- /dev/null +++ b/src/data/value/convert.rs @@ -0,0 +1,68 @@ +use { + super::{Value, ValueError}, + crate::result::Result, + chrono::NaiveDateTime, +}; + +// TODO: No clone versions + +pub trait Convert { + fn convert(self) -> Result; +} + +pub trait ConvertFrom: Sized { + fn convert_from(value: Value) -> Result; +} +impl ConvertFrom for Core +where + Value: Convert + Clone, +{ + fn convert_from(value: Value) -> Result { + value.convert() + } +} + +impl Convert for Value { + fn convert(self) -> Result { + Ok(match self { + Value::Bool(inner) => inner, + other => return Err(ValueError::CannotConvert(other, "BOOLEAN").into()), + }) + } +} + +impl Convert for Value { + fn convert(self) -> Result { + Ok(match self { + Value::I64(inner) => inner, + other => return Err(ValueError::CannotConvert(other, "INTEGER").into()), + }) + } +} + +impl Convert for Value { + fn convert(self) -> Result { + Ok(match self { + Value::F64(inner) => inner, + #[cfg(feature = "implicit_float_conversion")] + Value::I64(inner) => inner as f64, + other => return Err(ValueError::CannotConvert(other, "FLOAT").into()), + }) + } +} + +impl Convert for Value { + fn convert(self) -> Result { + Ok(match self { + Value::Str(inner) => inner, + other => return Err(ValueError::CannotConvert(other, "TEXT").into()), + }) + } +} + +impl Convert for Value { + fn convert(self) -> Result { + let secs = self.convert()?; + Ok(NaiveDateTime::from_timestamp(secs, 0)) + } +} diff --git a/src/data/value/error.rs b/src/data/value/error.rs index 3ddd6c94..9948b5f3 100644 --- a/src/data/value/error.rs +++ b/src/data/value/error.rs @@ -1,4 +1,4 @@ -use {serde::Serialize, std::fmt::Debug, thiserror::Error}; +use {super::Value, chrono::ParseError, serde::Serialize, std::fmt::Debug, thiserror::Error}; #[derive(Error, Serialize, Debug, PartialEq)] pub enum ValueError { @@ -14,53 +14,48 @@ pub enum ValueError { #[error("failed to parse number")] FailedToParseNumber, - #[error("add on non numeric value")] - AddOnNonNumeric, - - #[error("subtract on non numeric value")] - SubtractOnNonNumeric, - - #[error("multiply on non numeric value")] - MultiplyOnNonNumeric, - - #[error("divide on non numeric value")] - DivideOnNonNumeric, - - #[error("floating numbers cannot be grouped by")] - FloatCannotBeGroupedBy, - - #[error("unary plus operation for non numeric value")] - UnaryPlusOnNonNumeric, - - #[error("unary minus operation for non numeric value")] - UnaryMinusOnNonNumeric, - #[error("unreachable failure on parsing number")] UnreachableNumberParsing, #[error("floating columns cannot be set to unique constraint")] ConflictOnFloatWithUniqueConstraint, - // Cast errors from value to value - #[error("impossible cast")] - ImpossibleCast, + #[error( + "number of function parameters not matching (expected: {expected:?}, found: {found:?})" + )] + NumberOfFunctionParamsNotMatching { expected: usize, found: usize }, + #[error("conversion rule is not accepted for this type")] + InvalidConversionRule, + + #[error("impossible cast")] + ImpossibleCast, // Bad error-- phase out + + #[error("date time failed to parse: {0}")] + DateTimeParseError(String), + #[error("failed to parse {0:?} as {1}")] + ParseError(Value, &'static str), + #[error("something went wrong with date math")] + DateError, // Should avoid throwing + + #[error("cannot convert {0:?} into {1}")] + CannotConvert(Value, &'static str), + + #[error("{1} only supports numeric values, found {0:?}")] + OnlySupportsNumeric(Value, &'static str), + #[error("{1} only supports boolean values, found {0:?}")] + OnlySupportsBoolean(Value, &'static str), + #[error("bad input: {0:?}")] + BadInput(Value), + + #[error("unimplemented literal type")] + UnimplementedLiteralType, #[error("unimplemented cast")] UnimplementedCast, - - // Cast errors from literal to value - #[error("literal cast failed from text to integer: {0}")] - LiteralCastFromTextToIntegerFailed(String), - - #[error("literal cast failed from text to float: {0}")] - LiteralCastToFloatFailed(String), - - #[error("literal cast failed to boolean: {0}")] - LiteralCastToBooleanFailed(String), - + #[error("unimplemented convert")] + UnimplementedConvert, #[error("unreachable literal cast from number to integer: {0}")] UnreachableLiteralCastFromNumberToInteger(String), - #[error("unimplemented literal cast: {literal} as {data_type}")] UnimplementedLiteralCast { data_type: String, literal: String }, } diff --git a/src/data/value/group_key.rs b/src/data/value/group_key.rs deleted file mode 100644 index 566a936b..00000000 --- a/src/data/value/group_key.rs +++ /dev/null @@ -1,40 +0,0 @@ -use { - super::{error::ValueError, Value}, - crate::{ - executor::GroupKey, - result::{Error, Result}, - }, - std::convert::TryInto, -}; - -impl TryInto for &Value { - type Error = Error; - - fn try_into(self) -> Result { - use Value::*; - - match self { - Bool(v) => Ok(GroupKey::Bool(*v)), - I64(v) => Ok(GroupKey::I64(*v)), - Str(v) => Ok(GroupKey::Str(v.clone())), - Null => Ok(GroupKey::None), - F64(_) => Err(ValueError::FloatCannotBeGroupedBy.into()), - } - } -} - -impl TryInto for Value { - type Error = Error; - - fn try_into(self) -> Result { - use Value::*; - - match self { - Bool(v) => Ok(GroupKey::Bool(v)), - I64(v) => Ok(GroupKey::I64(v)), - Str(v) => Ok(GroupKey::Str(v)), - Null => Ok(GroupKey::None), - F64(_) => Err(ValueError::FloatCannotBeGroupedBy.into()), - } - } -} diff --git a/src/data/value/into.rs b/src/data/value/into.rs deleted file mode 100644 index 913fafef..00000000 --- a/src/data/value/into.rs +++ /dev/null @@ -1,86 +0,0 @@ -use { - super::{Value, ValueError}, - crate::result::{Error, Result}, - std::convert::TryInto, -}; - -impl From<&Value> for String { - fn from(v: &Value) -> Self { - match v { - Value::Str(value) => value.to_string(), - Value::Bool(value) => (if *value { "TRUE" } else { "FALSE" }).to_string(), - Value::I64(value) => value.to_string(), - Value::F64(value) => value.to_string(), - Value::Null => String::from("NULL"), - } - } -} - -impl TryInto for &Value { - type Error = Error; - fn try_into(self) -> Result { - Ok(match self { - Value::Bool(value) => *value, - Value::I64(value) => match value { - 1 => true, - 0 => false, - _ => return Err(ValueError::ImpossibleCast.into()), - }, - Value::F64(value) => { - if value.eq(&1.0) { - true - } else if value.eq(&0.0) { - false - } else { - return Err(ValueError::ImpossibleCast.into()); - } - } - Value::Str(value) => match value.to_uppercase().as_str() { - "TRUE" => true, - "FALSE" => false, - _ => return Err(ValueError::ImpossibleCast.into()), - }, - Value::Null => return Err(ValueError::ImpossibleCast.into()), - }) - } -} -impl TryInto for &Value { - type Error = Error; - fn try_into(self) -> Result { - Ok(match self { - Value::Bool(value) => { - if *value { - 1 - } else { - 0 - } - } - Value::I64(value) => *value, - Value::F64(value) => value.trunc() as i64, - Value::Str(value) => value - .parse::() - .map_err(|_| ValueError::ImpossibleCast)?, - Value::Null => return Err(ValueError::ImpossibleCast.into()), - }) - } -} -impl TryInto for &Value { - type Error = Error; - fn try_into(self) -> Result { - Ok(match self { - Value::Bool(value) => { - if *value { - 1.0 - } else { - 0.0 - } - } - Value::I64(value) => (*value as f64).trunc(), - Value::F64(value) => *value, - Value::Str(value) => value - .parse::() - .map_err(|_| ValueError::ImpossibleCast)?, - Value::Null => return Err(ValueError::ImpossibleCast.into()), - }) - } -} diff --git a/src/data/value/literal.rs b/src/data/value/literal.rs index 9cca49d4..5dd2e2ab 100644 --- a/src/data/value/literal.rs +++ b/src/data/value/literal.rs @@ -1,184 +1,26 @@ use { super::{error::ValueError, Value}, - crate::{ - data::Literal, - result::{Error, Result}, - Evaluated, - }, - sqlparser::ast::DataType, + crate::result::{Error, Result}, + sqlparser::ast::{DataType, Value as AstValue}, std::{cmp::Ordering, convert::TryFrom}, }; -impl PartialEq> for Value { - fn eq(&self, other: &Literal<'_>) -> bool { - match (self, other) { - (Value::Bool(l), Literal::Boolean(r)) => l == r, - (Value::I64(l), Literal::Number(r)) => match r.parse::() { - Ok(r) => l == &r, - Err(_) => match r.parse::() { - Ok(r) => (*l as f64) == r, - Err(_) => false, - }, - }, - (Value::F64(l), Literal::Number(r)) => match r.parse::() { - Ok(r) => l == &r, - Err(_) => match r.parse::() { - Ok(r) => *l == (r as f64), - Err(_) => false, - }, - }, - (Value::Str(l), Literal::Text(r)) => l == r.as_ref(), - _ => false, - } - } -} - -impl PartialOrd> for Value { - fn partial_cmp(&self, other: &Literal<'_>) -> Option { - match (self, other) { - (Value::I64(l), Literal::Number(r)) => match r.parse::() { - Ok(r) => Some(l.cmp(&r)), - Err(_) => match r.parse::() { - Ok(r) => (*l as f64).partial_cmp(&r), - Err(_) => None, - }, - }, - (Value::F64(l), Literal::Number(r)) => match r.parse::() { - Ok(r) => l.partial_cmp(&r), - Err(_) => match r.parse::() { - Ok(r) => l.partial_cmp(&(r as f64)), - Err(_) => None, - }, - }, - (Value::Str(l), Literal::Text(r)) => Some(l.cmp(r.as_ref())), - _ => None, - } - } -} - -impl TryFrom<&Literal<'_>> for Value { - type Error = Error; - - fn try_from(literal: &Literal<'_>) -> Result { - match literal { - Literal::Number(v) => v - .parse::() - .map_or_else(|_| v.parse::().map(Value::F64), |v| Ok(Value::I64(v))) - .map_err(|_| ValueError::FailedToParseNumber.into()), - Literal::Boolean(v) => Ok(Value::Bool(*v)), - Literal::Text(v) => Ok(Value::Str(v.as_ref().to_owned())), - Literal::Null => Ok(Value::Null), - } - } -} - -impl TryFrom> for Value { +impl<'a> TryFrom<&'a AstValue> for Value { type Error = Error; - fn try_from(literal: Literal<'_>) -> Result { - match literal { - Literal::Number(v) => v - .parse::() - .map_or_else(|_| v.parse::().map(Value::F64), |v| Ok(Value::I64(v))) - .map_err(|_| ValueError::FailedToParseNumber.into()), - Literal::Boolean(v) => Ok(Value::Bool(v)), - Literal::Text(v) => Ok(Value::Str(v.into_owned())), - Literal::Null => Ok(Value::Null), - } - } -} - -pub trait TryFromLiteral { - fn try_from_evaluated(data_type: &DataType, evaluated: Evaluated<'_>) -> Result; - - fn try_from_literal(data_type: &DataType, literal: &Literal<'_>) -> Result; - - fn try_cast_from_literal(data_type: &DataType, literal: &Literal<'_>) -> Result; -} - -impl TryFromLiteral for Value { - fn try_from_evaluated(data_type: &DataType, evaluated: Evaluated<'_>) -> Result { - match evaluated { - Evaluated::Literal(value) => Value::try_from_literal(data_type, &value), - Evaluated::Value(value) => Ok(value.into_owned()), - } - } - - fn try_from_literal(data_type: &DataType, literal: &Literal<'_>) -> Result { - match (data_type, literal) { - (DataType::Boolean, Literal::Boolean(v)) => Ok(Value::Bool(*v)), - (DataType::Int, Literal::Number(v)) => v + fn try_from(ast_value: &'a AstValue) -> Result { + match ast_value { + AstValue::Boolean(value) => Ok(Value::Bool(value.clone())), + AstValue::Number(value, false) => value .parse::() - .map(Value::I64) + .map_or_else( + |_| value.parse::().map(Value::F64), + |value| Ok(Value::I64(value)), + ) .map_err(|_| ValueError::FailedToParseNumber.into()), - (DataType::Float(_), Literal::Number(v)) => v - .parse::() - .map(Value::F64) - .map_err(|_| ValueError::UnreachableNumberParsing.into()), - (DataType::Text, Literal::Text(v)) => Ok(Value::Str(v.to_string())), - (DataType::Boolean, Literal::Null) - | (DataType::Int, Literal::Null) - | (DataType::Float(_), Literal::Null) - | (DataType::Text, Literal::Null) => Ok(Value::Null), - _ => Err(ValueError::IncompatibleLiteralForDataType { - data_type: data_type.to_string(), - literal: format!("{:?}", literal), - } - .into()), - } - } - - fn try_cast_from_literal(data_type: &DataType, literal: &Literal<'_>) -> Result { - match (data_type, literal) { - (DataType::Boolean, Literal::Boolean(v)) => Ok(Value::Bool(*v)), - (DataType::Boolean, Literal::Text(v)) | (DataType::Boolean, Literal::Number(v)) => { - match v.to_uppercase().as_str() { - "TRUE" | "1" => Ok(Value::Bool(true)), - "FALSE" | "0" => Ok(Value::Bool(false)), - _ => Err(ValueError::LiteralCastToBooleanFailed(v.to_string()).into()), - } - } - (DataType::Int, Literal::Text(v)) => v - .parse::() - .map(Value::I64) - .map_err(|_| ValueError::LiteralCastFromTextToIntegerFailed(v.to_string()).into()), - (DataType::Int, Literal::Number(v)) => v - .parse::() - .map_err(|_| { - ValueError::UnreachableLiteralCastFromNumberToInteger(v.to_string()).into() - }) - .map(|v| Value::I64(v.trunc() as i64)), - (DataType::Int, Literal::Boolean(v)) => { - let v = if *v { 1 } else { 0 }; - - Ok(Value::I64(v)) - } - (DataType::Float(_), Literal::Text(v)) | (DataType::Float(_), Literal::Number(v)) => v - .parse::() - .map(Value::F64) - .map_err(|_| ValueError::LiteralCastToFloatFailed(v.to_string()).into()), - (DataType::Float(_), Literal::Boolean(v)) => { - let v = if *v { 1.0 } else { 0.0 }; - - Ok(Value::F64(v)) - } - (DataType::Text, Literal::Number(v)) | (DataType::Text, Literal::Text(v)) => { - Ok(Value::Str(v.to_string())) - } - (DataType::Text, Literal::Boolean(v)) => { - let v = if *v { "TRUE" } else { "FALSE" }; - - Ok(Value::Str(v.to_owned())) - } - (DataType::Boolean, Literal::Null) - | (DataType::Int, Literal::Null) - | (DataType::Float(_), Literal::Null) - | (DataType::Text, Literal::Null) => Ok(Value::Null), - _ => Err(ValueError::UnimplementedLiteralCast { - data_type: data_type.to_string(), - literal: format!("{:?}", literal), - } - .into()), + AstValue::SingleQuotedString(value) => Ok(Value::Str(value.clone())), + AstValue::Null => Ok(Value::Null), + _ => Err(ValueError::UnimplementedLiteralType.into()), } } } diff --git a/src/data/value/methods/aggregate.rs b/src/data/value/methods/aggregate.rs new file mode 100644 index 00000000..f5c1d69f --- /dev/null +++ b/src/data/value/methods/aggregate.rs @@ -0,0 +1,49 @@ +use { + crate::{Convert, Result, Value}, + std::cmp::Ordering, +}; + +// This does not intentionally take into account anything that could variably change data types +// (example: IIF(column = 1, CAST(other AS INTEGER), CAST(other AS TEXT))) +// COUNT is indifferent to types, +// MIN and MAX will just give whatever the MIN/MAX of the first type (partial_cmp would evaulate to None which gives accumulator) +// SUM will, for now, use generic_add which will throw if non-artithmatic. + +impl Value { + pub fn aggregate_count(self, accumulator: Value) -> Result { + Ok(if !matches!(self, Value::Null) { + Value::I64( + accumulator.convert().unwrap_or(0) /*This should only occur for first value: NULL*/ + 1, + ) + } else { + accumulator + }) + } + pub fn aggregate_min(self, accumulator: Value) -> Result { + Ok( + if matches!(self.partial_cmp(&accumulator), Some(Ordering::Less)) + || matches!(accumulator, Value::Null) + { + self + } else { + accumulator + }, + ) + } + pub fn aggregate_max(self, accumulator: Value) -> Result { + Ok( + if matches!(self.partial_cmp(&accumulator), Some(Ordering::Greater)) + || matches!(accumulator, Value::Null) + { + self + } else { + accumulator + }, + ) + } + pub fn aggregate_sum(self, accumulator: Value) -> Result { + accumulator + .if_null(Value::I64(0)) // TODO: Handle lack of implicit i64 -> f64 + .generic_add(self.clone().if_null(Value::I64(0))) + } +} diff --git a/src/data/value/methods/binary.rs b/src/data/value/methods/binary.rs new file mode 100644 index 00000000..b2e677c6 --- /dev/null +++ b/src/data/value/methods/binary.rs @@ -0,0 +1,124 @@ +use { + super::ValueCore, + crate::{Convert, ConvertFrom, Result, Value, ValueError}, +}; + +// These were using references, they now consume their variables. See ::recipe. +macro_rules! natural_binary_op { + ($name: ident, $trait: ident, $op: tt) => { + pub fn $name(self, other: Self) -> Result + where + Core: ValueCore + $trait, + { + let (left, right) = (Core::convert_from(self)?, Core::convert_from(other)?); + let result = left $op right; + Ok(result.into()) + } + }; +} +macro_rules! natural_binary_ops { + ($(($name: ident, $trait: ident, $op: tt, $generic_name: ident)),+) => { + use std::ops::{$($trait),+}; + impl Value { + $( + natural_binary_op!($name, $trait, $op); + generic!($name, $generic_name); + )+ + } + } +} + +macro_rules! boolean_binary_op { + ($name: ident, $op: tt) => { + pub fn $name(self, other: Self) -> Result + { + let (left, right): (bool, bool) = (self.convert()?, other.convert()?); + let result = left $op right; + Ok(result.into()) + } + }; +} +macro_rules! boolean_binary_ops { + ($(($name: ident, $op: tt)),+) => { + impl Value { + $(boolean_binary_op!($name, $op);)+ + } + } +} + +macro_rules! comparative_binary_op { + ($name: ident, $op: tt) => { + pub fn $name(self, other: Self) -> Result { + Ok(Value::Bool(self $op other)) + } + }; +} +macro_rules! comparative_binary_ops { + ($(($name: ident, $op: tt)),+) => { + impl Value { + $(comparative_binary_op!($name, $op);)+ + } + } +} + +macro_rules! generic { + ($name: ident, $generic_name: ident) => { + pub fn $generic_name(self, other: Self) -> Result { + if matches!(self, Value::Null) || matches!(other, Value::Null) { + Ok(Value::Null) + } else if !i64::convert_from(self.clone()).is_err() + && !i64::convert_from(other.clone()).is_err() + { + self.$name::(other) + } else if !f64::convert_from(self.clone()).is_err() + && !f64::convert_from(other.clone()).is_err() + { + self.$name::(other) + } else { + Err(ValueError::OnlySupportsNumeric( + if f64::convert_from(self.clone()).is_err() { + self + } else { + other + }, + stringify!($name), + ) + .into()) + } + } + }; +} + +natural_binary_ops!( + (add, Add, +, generic_add), + (subtract, Sub, -, generic_subtract), + (multiply, Mul, *, generic_multiply), + (divide, Div, /, generic_divide), + (modulus, Rem, %, generic_modulus) +); + +boolean_binary_ops!( + (and, &), + (or, |), + (xor, ^) +); + +comparative_binary_ops!( + (eq, ==), + (not_eq, !=), + (gt, >), + (gt_eq, >=), + (lt, <), + (lt_eq, <=) +); + +impl Value { + pub fn string_concat(self, other: Self) -> Result { + Ok(format!( + "{}{}", + String::convert_from(self)?, + String::convert_from(other)? + ) + .into()) + } +} diff --git a/src/data/value/methods/function.rs b/src/data/value/methods/function.rs new file mode 100644 index 00000000..7b4785c9 --- /dev/null +++ b/src/data/value/methods/function.rs @@ -0,0 +1,160 @@ +use { + crate::{Cast, CastWithRules, Convert, Result, Value, ValueError}, + chrono::NaiveDateTime, + sqlparser::ast::DataType, + std::convert::TryInto, +}; + +macro_rules! expect_arguments { + ($arguments: expr, $expect: expr) => { + match $arguments.len() { + $expect => (), + found => { + return Err(ValueError::NumberOfFunctionParamsNotMatching { + expected: $expect, + found, + } + .into()) + } + } + }; +} + +macro_rules! optional_expect_arguments { + ($arguments: expr, $min: expr, $max: expr) => { + match $arguments.len() { + len if len >= $min && len <= $max => (), + found => { + return Err(ValueError::NumberOfFunctionParamsNotMatching { + expected: $min, + found, + } + .into()) + } + } + }; +} + +impl Value { + pub fn function_if_null(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 2); + Ok(arguments.remove(0).if_null(arguments.remove(0))) + } + pub fn function_null_if(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 2); + arguments.remove(0).null_if(arguments.remove(0)) + } + pub fn function_iif(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 3); + arguments + .remove(0) + .iif(arguments.remove(0), arguments.remove(0)) + } + pub fn function_to_lowercase(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).to_lowercase() + } + pub fn function_to_uppercase(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).to_uppercase() + } + pub fn function_left(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 2); + arguments.remove(0).left(arguments.remove(0)) + } + pub fn function_right(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 2); + arguments.remove(0).right(arguments.remove(0)) + } + pub fn function_length(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).length() + } + + pub fn function_concat(mut arguments: Vec) -> Result { + arguments.remove(0).concat(arguments) + } + + pub fn function_replace(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 3); + arguments + .remove(0) + .replace(arguments.remove(0), arguments.remove(0)) + } + + pub fn function_now(arguments: Vec) -> Result { + expect_arguments!(arguments, 0); + Value::now() + } + pub fn function_year(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).year() + } + pub fn function_month(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).month() + } + pub fn function_day(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).day() + } + pub fn function_hour(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + arguments.remove(0).hour() + } + pub fn function_date_add(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 3); + arguments + .remove(0) + .date_add(arguments.remove(0), arguments.remove(0)) + } + pub fn function_date_from_parts(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 3); + arguments + .remove(0) + .date_from_parts(arguments.remove(0), arguments.remove(0)) + } + + pub fn function_round(mut arguments: Vec) -> Result { + optional_expect_arguments!(arguments, 1, 2); + let value = arguments.remove(0); + let places = if !arguments.is_empty() { + arguments.remove(0) + } else { + Self::I64(0) + }; + value.round(places) + } + pub fn function_pow(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 2); + arguments.remove(0).pow(arguments.remove(0)) + } + + pub fn function_convert(mut arguments: Vec) -> Result { + optional_expect_arguments!(arguments, 2, 3); + let datatype: String = arguments.remove(0).convert()?; + let value = arguments.remove(0); + let rule = if !arguments.is_empty() { + arguments.remove(0) + } else { + Self::I64(0) + }; + Ok(match datatype.to_uppercase().as_str() { + // Unfortunatly we cannot get datatype directly, it needs to be given as string + "BOOLEAN" => Value::Bool(value.cast_with_rule(rule)?), + "INTEGER" => Value::I64(value.cast_with_rule(rule)?), + "FLOAT" => Value::F64(value.cast_with_rule(rule)?), + "TEXT" => Value::Str(value.cast_with_rule(rule)?), + "TIMESTAMP" => { + // Temp, need Value::Timestamp + let datetime: NaiveDateTime = value.cast_with_rule(rule)?; + + Value::I64(datetime.timestamp()) + } + _ => return Err(ValueError::UnimplementedConvert.into()), + }) + } + pub fn function_try_convert(arguments: Vec) -> Result { + Ok(Value::function_convert(arguments).unwrap_or(Value::Null)) + } +} diff --git a/src/data/value/methods/mod.rs b/src/data/value/methods/mod.rs new file mode 100644 index 00000000..8bc3eac7 --- /dev/null +++ b/src/data/value/methods/mod.rs @@ -0,0 +1,16 @@ +mod aggregate; +mod binary; +mod function; +mod unary; +mod utility; + +use { + crate::{ConvertFrom, Value}, + std::convert::Into, +}; + +pub trait ValueCore: Into + ConvertFrom {} +impl ValueCore for bool {} +impl ValueCore for i64 {} +impl ValueCore for f64 {} +impl ValueCore for String {} diff --git a/src/data/value/methods/unary.rs b/src/data/value/methods/unary.rs new file mode 100644 index 00000000..2e632b5e --- /dev/null +++ b/src/data/value/methods/unary.rs @@ -0,0 +1,51 @@ +use { + super::ValueCore, + crate::{Convert, ConvertFrom, Result, Value, ValueError}, + std::ops::Neg, +}; + +macro_rules! generic { + ($name: ident, $generic_name: ident) => { + pub fn $generic_name(self) -> Result { + if !i64::convert_from(self.clone()).is_err() { + // TODO: Improve + self.$name::() + } else if !f64::convert_from(self.clone()).is_err() { + self.$name::() + } else { + Err(ValueError::OnlySupportsNumeric(self, stringify!($name)).into()) + } + } + }; +} + +impl Value { + pub fn unary_plus(self) -> Result + where + Core: ValueCore + Clone, + { + let core = Core::convert_from(self)?; + let result = core.clone(); + Ok(result.into()) + } + pub fn unary_minus(self) -> Result + where + Core: ValueCore + Neg, + { + let core = Core::convert_from(self)?; + let result = -core; + Ok(result.into()) + } + + generic!(unary_plus, generic_unary_plus); + generic!(unary_minus, generic_unary_minus); + + pub fn not(self) -> Result { + let boolean: bool = self.convert()?; + let result = !boolean; + Ok(result.into()) + } + pub fn is_null(self) -> Result { + Ok(Value::Bool(matches!(self, Value::Null))) + } +} diff --git a/src/data/value/methods/utility.rs b/src/data/value/methods/utility.rs new file mode 100644 index 00000000..7443a0ea --- /dev/null +++ b/src/data/value/methods/utility.rs @@ -0,0 +1,278 @@ +use { + crate::{CastWithRules, Convert, Result, Value, ValueError}, + chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike}, + std::{ + cmp::min, + convert::TryInto, + time::{SystemTime, UNIX_EPOCH}, + }, +}; + +macro_rules! protect_null { + ($protect: expr) => { + if matches!($protect, Value::Null) { + return Ok($protect); + } + }; +} + +impl Value { + pub fn if_null(self, alternative: Self) -> Self { + if !matches!(self, Value::Null) { + self + } else { + alternative + } + } + pub fn null_if(self, evaluate: Self) -> Result { + Ok(if self == evaluate { Value::Null } else { self }) + } + pub fn iif(self, case_true: Self, case_false: Self) -> Result { + Ok(if self.convert()? { + case_true + } else { + case_false + }) + } + + pub fn to_uppercase(self) -> Result { + protect_null!(self); + let string: String = self.convert()?; + Ok(string.to_uppercase().into()) + } + pub fn to_lowercase(self) -> Result { + protect_null!(self); + let string: String = self.convert()?; + Ok(string.to_lowercase().into()) + } + pub fn left(self, length: Value) -> Result { + protect_null!(self); + protect_null!(length); + let length: i64 = length.convert()?; + if length < 0 { + return Err(ValueError::BadInput(length.into()).into()); + } + let length: usize = length as usize; + let string: String = self.convert()?; + + let truncated = string + .get(..length) + .map(|result| result.to_string()) + .unwrap_or(string); + Ok(Value::Str(truncated)) + } + pub fn right(self, length: Value) -> Result { + protect_null!(self); + protect_null!(length); + let length: i64 = length.convert()?; + if length < 0 { + return Err(ValueError::BadInput(length.into()).into()); + } + let length: usize = length as usize; + let string: String = self.convert()?; + + let truncated = string + .get(string.len() - min(string.len(), length)..) + .map(|result| result.to_string()) + .unwrap_or(string); + Ok(Value::Str(truncated)) + } + pub fn length(self) -> Result { + let string: String = self.convert()?; + Ok(Value::I64(string.len() as i64)) + } + + pub fn concat(self, strings: Vec) -> Result { + strings + .into_iter() + .try_fold(self, |all, this| all.string_concat(this)) + } + + pub fn replace(self, from: Value, to: Value) -> Result { + protect_null!(self); + let string: String = self.convert()?; + let from: String = from.convert()?; + let to: String = to.convert()?; + + Ok(string.replace(&from, &to).into()) + } + + pub fn now() -> Result { + Ok(Value::I64( + NaiveDateTime::from_timestamp( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as i64, + 0, + ) + .timestamp(), + )) + } + pub fn year(self) -> Result { + let datetime: NaiveDateTime = self.convert()?; + Ok(Value::I64(datetime.year() as i64)) + } + pub fn month(self) -> Result { + let datetime: NaiveDateTime = self.convert()?; + Ok(Value::I64(datetime.month() as i64)) + } + pub fn day(self) -> Result { + let datetime: NaiveDateTime = self.convert()?; + Ok(Value::I64(datetime.day() as i64)) + } + pub fn hour(self) -> Result { + let datetime: NaiveDateTime = self.convert()?; + Ok(Value::I64(datetime.hour() as i64)) + } + pub fn date_add(self, amount: Value, datetime: Value) -> Result { + let datetime: NaiveDateTime = datetime.convert()?; + let amount: i64 = amount.convert()?; + let amount: i32 = amount.try_into().map_err(|_| ValueError::DateError)?; + + match self { + Value::Str(string) if string == "YEAR" => { + let years = datetime.year() + amount as i32; + let calculated = datetime.with_year(years).unwrap_or( + datetime + .with_day(28) + .ok_or(ValueError::DateError) + .unwrap() //? + .with_year(years) + .ok_or(ValueError::DateError) + .unwrap(), //?, + ); + Ok(Value::I64(calculated.timestamp())) + } + Value::Str(string) if string == "MONTH" => { + let month: i32 = datetime + .month() + .try_into() + .map_err(|_| ValueError::DateError)?; + + let months = month + amount; + let month = ((months - 1) % 12) + 1; + + let years = (months - month) / 12; + let month: u32 = month.try_into().map_err(|_| ValueError::DateError).unwrap(); //?; + + let (years, month) = if month == 0 { (-1, 12) } else { (years, month) }; // TEMP-- no support for > -1 yet + + let next_month = if datetime.month() == 12 { + NaiveDate::from_ymd(datetime.year() + 1, 1, 1) + } else { + NaiveDate::from_ymd(datetime.year(), datetime.month() + 1, 1) + }; + let this_month = NaiveDate::from_ymd(datetime.year(), datetime.month(), 1); + + let month_days: u32 = NaiveDate::signed_duration_since(next_month, this_month) + .num_days() + .try_into() + .map_err(|_| ValueError::DateError)?; + + let day = min(datetime.day(), month_days); + let calculated = datetime + .with_day(day) + .ok_or(ValueError::DateError) + .unwrap() //? + .with_month(month) + .ok_or(ValueError::DateError) + .unwrap(); //?; + + let calculated = Value::I64(calculated.timestamp()); + Value::Str(String::from("YEAR")).date_add(Value::I64(years as i64), calculated) + } + Value::Str(string) if string == "DAY" => { + let day: i32 = datetime + .day() + .try_into() + .map_err(|_| ValueError::DateError)?; + let days = day + amount; + + let next_month = if datetime.month() == 12 { + NaiveDate::from_ymd(datetime.year() + 1, 1, 1) + } else { + NaiveDate::from_ymd(datetime.year(), datetime.month() + 1, 1) + }; + let this_month = NaiveDate::from_ymd(datetime.year(), datetime.month(), 1); + + let month_days: i32 = NaiveDate::signed_duration_since(next_month, this_month) + .num_days() + .try_into() + .map_err(|_| ValueError::DateError)?; + + if days > month_days { + let first_day = datetime.with_day(1).ok_or(ValueError::DateError)?; + let next_month = Value::Str(String::from("MONTH")) + .date_add(Value::I64(1), Value::I64(first_day.timestamp()))?; + Value::Str(String::from("DAY")).date_add( + Value::I64( + (days - month_days - 1) + .try_into() + .map_err(|_| ValueError::DateError) + .unwrap(), //?, + ), + next_month, + ) + } else if days <= 0 { + let prev_month = if datetime.month() == 1 { + NaiveDate::from_ymd(datetime.year() - 1, 12, 1) + } else { + NaiveDate::from_ymd(datetime.year(), datetime.month() - 1, 1) + }; + + let prev_month_days: i32 = + NaiveDate::signed_duration_since(this_month, prev_month) + .num_days() + .try_into() + .map_err(|_| ValueError::DateError)?; + + let first_day = datetime.with_day(1).ok_or(ValueError::DateError)?; + let prev_month = Value::Str(String::from("MONTH")) + .date_add(Value::I64(-1), Value::I64(first_day.timestamp()))?; + Value::Str(String::from("DAY")).date_add( + Value::I64( + (days + prev_month_days - 1) + .try_into() + .map_err(|_| ValueError::DateError) + .unwrap(), //?, + ), + prev_month, + ) + } else { + let day: u32 = days.try_into().map_err(|_| ValueError::DateError).unwrap(); //?; + Ok(Value::I64( + datetime + .with_day(day) + .ok_or(ValueError::DateError) + .unwrap() //? + .timestamp(), + )) + } + } + _ => Err(ValueError::BadInput(self).into()), + } + } + pub fn date_from_parts(self, month: Value, day: Value) -> Result { + let (year, month, day): (i64, i64, i64) = + (self.convert()?, month.convert()?, day.convert()?); + let datetime = NaiveDate::from_ymd(year as i32, month as u32, day as u32).and_hms(0, 0, 0); + + Ok(Value::I64(datetime.timestamp())) + } + + pub fn round(self, places: Value) -> Result { + if matches!(self, Value::Null) { + return Ok(self); + } + let value: f64 = self.convert()?; + let places: i64 = places.convert()?; + let raiser: f64 = 10_u32.pow(places as u32).into(); + Ok(Value::F64((value * raiser).round() / raiser)) + } + pub fn pow(self, power: Value) -> Result { + let value: f64 = self.convert()?; + let power: f64 = power.convert()?; + Ok(Value::F64(value.powf(power))) + } +} diff --git a/src/data/value/mod.rs b/src/data/value/mod.rs index 6ad7533d..c069d28f 100644 --- a/src/data/value/mod.rs +++ b/src/data/value/mod.rs @@ -1,86 +1,137 @@ use { - super::Literal, crate::result::Result, regex::Regex, serde::{Deserialize, Serialize}, - sqlparser::ast::{DataType, Expr}, - std::{ - cmp::Ordering, - convert::{TryFrom, TryInto}, - fmt::Debug, - }, + sqlparser::ast::DataType, + std::{cmp::Ordering, fmt::Debug}, }; +mod cast; +mod convert; mod error; -mod group_key; -mod into; mod literal; -mod unique_key; +mod methods; -pub use {error::ValueError, literal::TryFromLiteral}; +pub use { + cast::{Cast, CastWithRules}, + convert::{Convert, ConvertFrom}, + error::ValueError, +}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Value { Bool(bool), + Bytes(Vec), I64(i64), F64(f64), Str(String), Null, } -impl PartialEq for Value { +impl From for Value { + fn from(from: bool) -> Value { + Value::Bool(from) + } +} +impl From for Value { + fn from(from: i64) -> Value { + Value::I64(from) + } +} +impl From for Value { + fn from(from: f64) -> Value { + Value::F64(from) + } +} +impl From for Value { + fn from(from: String) -> Value { + Value::Str(from) + } +} + +impl PartialEq for Value { fn eq(&self, other: &Value) -> bool { match (self, other) { (Value::Bool(l), Value::Bool(r)) => l == r, (Value::I64(l), Value::I64(r)) => l == r, (Value::F64(l), Value::F64(r)) => l == r, (Value::Str(l), Value::Str(r)) => l == r, + (Value::Bytes(l), Value::Bytes(r)) => l == r, + + #[cfg(feature = "implicit_float_conversion")] + (Value::I64(l), Value::F64(r)) => (*l as f64) == *r, + #[cfg(feature = "implicit_float_conversion")] + (Value::F64(l), Value::I64(r)) => *l == (*r as f64), _ => false, } } } -impl PartialOrd for Value { +impl PartialOrd for Value { fn partial_cmp(&self, other: &Value) -> Option { match (self, other) { (Value::Bool(l), Value::Bool(r)) => Some(l.cmp(r)), (Value::I64(l), Value::I64(r)) => Some(l.cmp(r)), - (Value::I64(l), Value::F64(r)) => (*l as f64).partial_cmp(r), - (Value::F64(l), Value::I64(r)) => l.partial_cmp(&(*r as f64)), (Value::F64(l), Value::F64(r)) => l.partial_cmp(r), (Value::Str(l), Value::Str(r)) => Some(l.cmp(r)), + (Value::Bytes(l), Value::Bytes(r)) => Some(l.cmp(r)), + + #[cfg(feature = "implicit_float_conversion")] + (Value::I64(l), Value::F64(r)) => (*l as f64).partial_cmp(r), + + #[cfg(feature = "implicit_float_conversion")] + (Value::F64(l), Value::I64(r)) => l.partial_cmp(&(*r as f64)), + _ => None, } } } -trait BoolToValue: Sized { - fn into_value(self, v1: Value, v2: Value) -> Value; +pub trait NullOrd { + fn null_cmp(&self, other: &Self) -> Option; } -impl BoolToValue for bool { - #[inline] - fn into_value(self, v1: Value, v2: Value) -> Value { - if self { - v1 - } else { - v2 - } +impl NullOrd for Value { + fn null_cmp(&self, other: &Self) -> Option { + self.partial_cmp(other).or(match (self, other) { + (Value::Null, Value::Null) => None, + (Value::Null, _) => Some(Ordering::Less), + (_, Value::Null) => Some(Ordering::Greater), + _ => None, + }) } } impl Value { - pub fn from_expr(data_type: &DataType, nullable: bool, expr: &Expr) -> Result { - let literal = Literal::try_from(expr)?; - let value = Value::try_from_literal(&data_type, &literal)?; + pub fn validate_type(mut self, data_type: &DataType) -> Result { + let mut valid = self.type_is_valid(data_type); - value.validate_null(nullable)?; + if !valid { + let converted = match data_type { + DataType::Float(_) => self.clone().convert().map(Value::F64).ok(), + _ => None, + }; + if let Some(converted) = converted { + if converted.type_is_valid(data_type) { + valid = true; + self = converted; + } + } + } + + if !valid { + return Err(ValueError::IncompatibleDataType { + data_type: data_type.to_string(), + value: format!("{:?}", self), + } + .into()); + } - Ok(value) + Ok(self) } - pub fn validate_type(&self, data_type: &DataType) -> Result<()> { - let valid = matches!( + fn type_is_valid(&self, data_type: &DataType) -> bool { + matches!( (data_type, self), (DataType::Boolean, Value::Bool(_)) | (DataType::Int, Value::I64(_)) @@ -90,17 +141,7 @@ impl Value { | (DataType::Int, Value::Null) | (DataType::Float(_), Value::Null) | (DataType::Text, Value::Null) - ); - - if !valid { - return Err(ValueError::IncompatibleDataType { - data_type: data_type.to_string(), - value: format!("{:?}", self), - } - .into()); - } - - Ok(()) + ) } pub fn validate_null(&self, nullable: bool) -> Result<()> { @@ -111,7 +152,7 @@ impl Value { Ok(()) } - pub fn cast(&self, data_type: &DataType) -> Result { + pub fn cast_datatype(&self, data_type: &DataType) -> Result { match (data_type, self) { (DataType::Boolean, Value::Bool(_)) | (DataType::Int, Value::I64(_)) @@ -119,10 +160,10 @@ impl Value { | (DataType::Text, Value::Str(_)) => Ok(self.clone()), (_, Value::Null) => Ok(Value::Null), - (DataType::Boolean, value) => value.try_into().map(Value::Bool), - (DataType::Int, value) => value.try_into().map(Value::I64), - (DataType::Float(_), value) => value.try_into().map(Value::F64), - (DataType::Text, value) => Ok(Value::Str(value.into())), + (DataType::Boolean, value) => value.clone().cast().map(Value::Bool), + (DataType::Int, value) => value.clone().cast().map(Value::I64), + (DataType::Float(_), value) => value.clone().cast().map(Value::F64), + (DataType::Text, value) => value.clone().cast().map(Value::Str), (DataType::Time, Value::Str(value)) => { let regex = @@ -172,76 +213,59 @@ impl Value { } } - pub fn add(&self, other: &Value) -> Result { - use Value::*; - - match (self, other) { - (I64(a), I64(b)) => Ok(I64(a + b)), - (F64(a), F64(b)) => Ok(F64(a + b)), - (Null, _) | (_, Null) => Ok(Null), - _ => Err(ValueError::AddOnNonNumeric.into()), - } - } - - pub fn subtract(&self, other: &Value) -> Result { - use Value::*; - - match (self, other) { - (I64(a), I64(b)) => Ok(I64(a - b)), - (F64(a), F64(b)) => Ok(F64(a - b)), - (Null, _) | (_, Null) => Ok(Null), - _ => Err(ValueError::SubtractOnNonNumeric.into()), - } - } - - pub fn multiply(&self, other: &Value) -> Result { - use Value::*; - - match (self, other) { - (I64(a), I64(b)) => Ok(I64(a * b)), - (F64(a), F64(b)) => Ok(F64(a * b)), - (Null, _) | (_, Null) => Ok(Null), - _ => Err(ValueError::MultiplyOnNonNumeric.into()), - } - } - - pub fn divide(&self, other: &Value) -> Result { - use Value::*; - - match (self, other) { - (I64(a), I64(b)) => Ok(I64(a / b)), - (F64(a), F64(b)) => Ok(F64(a / b)), - (Null, _) | (_, Null) => Ok(Null), - _ => Err(ValueError::DivideOnNonNumeric.into()), + /*pub fn convert_datatype(&self, data_type: &DataType) -> Result { + match (data_type, self) { + (DataType::Time, Value::Str(value)) => { + let regex = + Regex::new(r"^(\d|[0-1]\d|2[0-3]):([0-5]\d)(:([0-5]\d))? ?([AaPp][Mm])?$"); + if let Ok(regex) = regex { + if let Some(captures) = regex.captures(value) { + let modifier: bool = captures + .iter() + .last() + .map(|capture| { + capture + .map(|capture| { + Regex::new(r"^[Pp][Mm]$") + .ok() + .map(|regex| regex.is_match(capture.into())) + }) + .flatten() + }) + .flatten() + .unwrap_or(false); + let mut items: Vec = captures + .iter() + .skip(1) + .filter_map(|capture| { + capture + .map(|capture| { + let capture: &str = capture.into(); + capture.parse::().ok() + }) + .flatten() + }) + .collect(); + items.resize(3, 0); + let seconds = items.iter().fold(0, |acc, item| (acc * 60) + item) + + if modifier { 12 * 60 * 60 } else { 0 }; + Ok(Value::I64(seconds)) + } else { + Err(()) + } + } else { + Err(()) + } + .map_err(|_| ValueError::ImpossibleCast.into()) + } } - } + }*/ pub fn is_some(&self) -> bool { use Value::*; !matches!(self, Null) } - - pub fn unary_plus(&self) -> Result { - use Value::*; - - match self { - I64(_) | F64(_) => Ok(self.clone()), - Null => Ok(Null), - _ => Err(ValueError::UnaryPlusOnNonNumeric.into()), - } - } - - pub fn unary_minus(&self) -> Result { - use Value::*; - - match self { - I64(a) => Ok(I64(-a)), - F64(a) => Ok(F64(-a)), - Null => Ok(Null), - _ => Err(ValueError::UnaryMinusOnNonNumeric.into()), - } - } } #[cfg(test)] @@ -263,7 +287,7 @@ mod tests { macro_rules! cast { ($input: expr => $data_type: expr, $expected: expr) => { - let found = $input.cast(&$data_type).unwrap(); + let found = $input.cast_datatype(&$data_type).unwrap(); match ($expected, found) { (Null, Null) => {} @@ -296,10 +320,11 @@ mod tests { cast!(Str("11".to_owned()) => Int, I64(11)); cast!(Null => Int, Null); - // Time + /*// Time cast!(Str("11:00".to_owned()) => Time, I64(11*60*60)); cast!(Str("1:00PM".to_owned()) => Time, I64((12+1)*60*60)); cast!(Str("23:35".to_owned()) => Time, I64((23*60*60) + 35*60)); + */ // Float cast!(Bool(true) => Float(None), F64(1.0)); diff --git a/src/data/value/unique_key.rs b/src/data/value/unique_key.rs deleted file mode 100644 index 6f8e5824..00000000 --- a/src/data/value/unique_key.rs +++ /dev/null @@ -1,28 +0,0 @@ -use { - super::{error::ValueError, Value}, - crate::{ - executor::UniqueKey, - result::{Error, Result}, - }, - std::convert::TryInto, -}; - -impl TryInto> for &Value { - type Error = Error; - - fn try_into(self) -> Result> { - use Value::*; - - let unique_key = match self { - Bool(v) => Some(UniqueKey::Bool(*v)), - I64(v) => Some(UniqueKey::I64(*v)), - Str(v) => Some(UniqueKey::Str(v.clone())), - Null => None, - F64(_) => { - return Err(ValueError::ConflictOnFloatWithUniqueConstraint.into()); - } - }; - - Ok(unique_key) - } -} diff --git a/src/executor/aggregate/error.rs b/src/executor/aggregate/error.rs deleted file mode 100644 index e6b6c4f1..00000000 --- a/src/executor/aggregate/error.rs +++ /dev/null @@ -1,24 +0,0 @@ -use serde::Serialize; -use std::fmt::Debug; -use thiserror::Error; - -#[derive(Error, Serialize, Debug, PartialEq)] -pub enum AggregateError { - #[error("unsupported compound identifier: {0}")] - UnsupportedCompoundIdentifier(String), - - #[error("unsupported aggregation: {0}")] - UnsupportedAggregation(String), - - #[error("only identifier is allowed in aggregation")] - OnlyIdentifierAllowed, - - #[error("value not found: {0}")] - ValueNotFound(String), - - #[error("unreachable")] - Unreachable, - - #[error("unreachable named function arg: {0}")] - UnreachableNamedFunctionArg(String), -} diff --git a/src/executor/aggregate/hash.rs b/src/executor/aggregate/hash.rs deleted file mode 100644 index cf69cc41..00000000 --- a/src/executor/aggregate/hash.rs +++ /dev/null @@ -1,24 +0,0 @@ -use std::convert::{TryFrom, TryInto}; - -use crate::data::Value; -use crate::executor::evaluate::Evaluated; -use crate::result::{Error, Result}; - -#[derive(PartialEq, Eq, Hash, Clone, std::fmt::Debug)] -pub enum GroupKey { - I64(i64), - Bool(bool), - Str(String), - None, -} - -impl TryFrom<&Evaluated<'_>> for GroupKey { - type Error = Error; - - fn try_from(evaluated: &Evaluated<'_>) -> Result { - match evaluated { - Evaluated::Literal(l) => Value::try_from(l)?.try_into(), - Evaluated::Value(v) => v.as_ref().try_into(), - } - } -} diff --git a/src/executor/aggregate/mod.rs b/src/executor/aggregate/mod.rs deleted file mode 100644 index 2faa8640..00000000 --- a/src/executor/aggregate/mod.rs +++ /dev/null @@ -1,263 +0,0 @@ -mod error; -mod hash; -mod state; - -use boolinator::Boolinator; -use futures::stream::{self, StreamExt, TryStream, TryStreamExt}; -use std::convert::TryFrom; -use std::fmt::Debug; -use std::pin::Pin; -use std::rc::Rc; - -use sqlparser::ast::{Expr, Function, FunctionArg, SelectItem}; - -use super::context::{AggregateContext, BlendContext, FilterContext}; -use super::evaluate::{evaluate, Evaluated}; -use super::filter::check_expr; -use crate::data::{get_name, Value}; -use crate::result::{Error, Result}; -use crate::store::Store; - -pub use error::AggregateError; -pub use hash::GroupKey; -use state::State; - -pub struct Aggregate<'a, T: 'static + Debug> { - storage: &'a dyn Store, - fields: &'a [SelectItem], - group_by: &'a [Expr], - having: Option<&'a Expr>, - filter_context: Option>>, -} - -type Applied<'a> = dyn TryStream, Error = Error, Item = Result>> - + 'a; - -impl<'a, T: 'static + Debug> Aggregate<'a, T> { - pub fn new( - storage: &'a dyn Store, - fields: &'a [SelectItem], - group_by: &'a [Expr], - having: Option<&'a Expr>, - filter_context: Option>>, - ) -> Self { - Self { - storage, - fields, - group_by, - having, - filter_context, - } - } - - pub async fn apply( - &self, - rows: impl TryStream>, Error = Error> + 'a, - ) -> Result>>> { - if !self.check_aggregate()? { - let rows = rows.map_ok(|blend_context| AggregateContext { - aggregated: None, - next: blend_context, - }); - - return Ok(Box::pin(rows)); - } - - let state = rows - .into_stream() - .enumerate() - .map(|(i, row)| row.map(|row| (i, row))) - .try_fold(State::new(), |state, (index, blend_context)| async move { - let evaluated: Vec> = - stream::iter(self.group_by.iter()) - .then(|expr| { - let filter_context = FilterContext::concat( - self.filter_context.as_ref().map(Rc::clone), - Some(&blend_context).map(Rc::clone), - ); - let filter_context = Some(filter_context).map(Rc::new); - - async move { - evaluate(self.storage, filter_context, None, expr, false).await - } - }) - .try_collect::>() - .await?; - let group = evaluated - .iter() - .map(GroupKey::try_from) - .collect::>>()?; - - let state = state.apply(index, group, Rc::clone(&blend_context)); - let state = self - .fields - .iter() - .try_fold(state, |state, field| match field { - SelectItem::UnnamedExpr(expr) | SelectItem::ExprWithAlias { expr, .. } => { - aggregate(state, &blend_context, &expr) - } - _ => Ok(state), - })?; - - Ok(state) - }) - .await?; - - let storage = self.storage; - let filter_context = self.filter_context.as_ref().map(Rc::clone); - let having = self.having; - - let rows = state - .export() - .into_iter() - .filter_map(|(aggregated, next)| next.map(|next| (aggregated, next))); - let rows = stream::iter(rows) - .filter_map(move |(aggregated, next)| { - let filter_context = filter_context.as_ref().map(Rc::clone); - let aggregated = aggregated.map(Rc::new); - - async move { - match having { - None => Some(Ok((aggregated.as_ref().map(Rc::clone), next))), - Some(having) => { - let filter_context = - FilterContext::concat(filter_context, Some(Rc::clone(&next))); - let filter_context = Some(filter_context).map(Rc::new); - let aggregated = aggregated.as_ref().map(Rc::clone); - - check_expr( - storage, - filter_context, - aggregated.as_ref().map(Rc::clone), - having, - ) - .await - .map(|pass| pass.as_some((aggregated, next))) - .transpose() - } - } - } - }) - .map_ok(|(aggregated, next)| { - // TODO: Remove unwrap! - let aggregated = aggregated.map(|a| Rc::try_unwrap(a).unwrap()); - - AggregateContext { aggregated, next } - }); - - Ok(Box::pin(rows)) - } - - fn check_aggregate(&self) -> Result { - if !self.group_by.is_empty() { - return Ok(true); - } - - self.fields - .iter() - .map(|field| match field { - SelectItem::UnnamedExpr(expr) => check(expr), - SelectItem::ExprWithAlias { expr, .. } => check(expr), - _ => Ok(false), - }) - .collect::>>() - .map(|checked| checked.into_iter().any(|c| c)) - } -} - -fn aggregate<'a>( - state: State<'a>, - context: &BlendContext<'_>, - expr: &'a Expr, -) -> Result> { - let aggr = |state, expr| aggregate(state, context, expr); - let get_value = |expr: &Expr| match expr { - Expr::Identifier(ident) => context - .get_value(&ident.value) - .ok_or_else(|| AggregateError::ValueNotFound(ident.value.to_string())), - Expr::CompoundIdentifier(idents) => { - if idents.len() != 2 { - return Err(AggregateError::UnsupportedCompoundIdentifier( - expr.to_string(), - )); - } - - let table_alias = &idents[0].value; - let column = &idents[1].value; - - context - .get_alias_value(table_alias, column) - .ok_or_else(|| AggregateError::ValueNotFound(column.to_string())) - } - _ => Err(AggregateError::OnlyIdentifierAllowed), - }; - let get_first_arg_expr = - |args: &'a [FunctionArg]| match args.get(0).ok_or(AggregateError::Unreachable)? { - FunctionArg::Unnamed(expr) => Ok(expr), - FunctionArg::Named { name, .. } => Err(AggregateError::UnreachableNamedFunctionArg( - name.to_string(), - )), - }; - let get_first_value = |args: &'a [FunctionArg]| { - let expr = get_first_arg_expr(args)?; - - get_value(expr) - }; - - match expr { - Expr::Between { - expr, low, high, .. - } => [expr, low, high] - .iter() - .try_fold(state, |state, expr| aggr(state, expr)), - Expr::BinaryOp { left, right, .. } => [left, right] - .iter() - .try_fold(state, |state, expr| aggr(state, expr)), - Expr::UnaryOp { expr, .. } => aggr(state, expr), - Expr::Nested(expr) => aggr(state, expr), - Expr::Function(func) => { - let Function { name, args, .. } = func; - - match get_name(name)?.to_uppercase().as_str() { - "COUNT" => { - let expr = get_first_arg_expr(args)?; - let value = Value::I64(match expr { - Expr::Wildcard => 1, - _ => { - if get_value(expr)?.is_some() { - 1 - } else { - 0 - } - } - }); - - state.add(func, &value) - } - "SUM" => state.add(func, get_first_value(args)?), - "MAX" => Ok(state.set_max(func, get_first_value(args)?)), - "MIN" => Ok(state.set_min(func, get_first_value(args)?)), - name => Err(AggregateError::UnsupportedAggregation(name.to_string()).into()), - } - } - _ => Ok(state), - } -} - -fn check(expr: &Expr) -> Result { - let checked = match expr { - Expr::Between { - expr, low, high, .. - } => check(expr)? || check(low)? || check(high)?, - Expr::BinaryOp { left, right, .. } => check(left)? || check(right)?, - Expr::UnaryOp { expr, .. } => check(expr)?, - Expr::Nested(expr) => check(expr)?, - Expr::Function(func) => matches!( - get_name(&func.name)?.to_uppercase().as_str(), - "COUNT" | "SUM" | "MAX" | "MIN" | "AVG" - ), - _ => false, - }; - - Ok(checked) -} diff --git a/src/executor/aggregate/state.rs b/src/executor/aggregate/state.rs deleted file mode 100644 index c7c69578..00000000 --- a/src/executor/aggregate/state.rs +++ /dev/null @@ -1,156 +0,0 @@ -use im_rc::{HashMap, HashSet}; -use itertools::Itertools; -use std::cmp::Ordering; -use std::rc::Rc; - -use sqlparser::ast::Function; - -use crate::utils::{IndexMap, Vector}; - -use super::hash::GroupKey; -use crate::data::Value; -use crate::executor::context::BlendContext; -use crate::result::Result; - -type Group = Rc>; -type ValuesMap<'a> = HashMap<&'a Function, Value>; - -pub struct State<'a> { - index: usize, - group: Group, - values: IndexMap<(Group, &'a Function), (usize, Value)>, - groups: HashSet, - contexts: Vector>>, -} - -impl<'a> State<'a> { - pub fn new() -> Self { - State { - index: 0, - group: Rc::new(vec![GroupKey::None]), - values: IndexMap::new(), - groups: HashSet::new(), - contexts: Vector::new(), - } - } - - pub fn apply(self, index: usize, group: Vec, context: Rc>) -> Self { - let group = Rc::new(group); - let (groups, contexts) = if self.groups.contains(&group) { - (self.groups, self.contexts) - } else { - ( - self.groups.update(Rc::clone(&group)), - self.contexts.push(context), - ) - }; - - Self { - index, - group, - values: self.values, - groups, - contexts, - } - } - - fn update(self, func: &'a Function, value: Value) -> Self { - let key = (Rc::clone(&self.group), func); - let (values, _) = self.values.insert(key, (self.index, value)); - - Self { - index: self.index, - group: self.group, - values, - groups: self.groups, - contexts: self.contexts, - } - } - - fn get(&self, func: &'a Function) -> Option<&(usize, Value)> { - let group = Rc::clone(&self.group); - - self.values.get(&(group, func)) - } - - pub fn export(self) -> Vec<(Option>, Option>>)> { - let size = match self.values.keys().next() { - Some((target, _)) => match self.values.keys().position(|(group, _)| group != target) { - Some(size) => size, - None => self.values.len(), - }, - None => { - return self.contexts.into_iter().map(|c| (None, Some(c))).collect(); - } - }; - - let Self { - values, contexts, .. - } = self; - - values - .into_iter() - .map(|(k, (_, v))| (k, v)) - .chunks(size) - .into_iter() - .enumerate() - .map(|(i, entries)| { - let aggregated = entries - .map(|((_, func), value)| (func, value)) - .collect::>(); - let next = contexts.get(i).map(Rc::clone); - - (Some(aggregated), next) - }) - .collect::>, Option>>)>>() - } - - pub fn add(self, func: &'a Function, target: &Value) -> Result { - let value = match self.get(func) { - Some((index, value)) => { - if &self.index <= index { - return Ok(self); - } - - target.add(value)? - } - None => target.clone(), - }; - - Ok(self.update(func, value)) - } - - pub fn set_max(self, func: &'a Function, target: &Value) -> Self { - if let Some((index, value)) = self.get(func) { - if &self.index <= index { - return self; - } - - match value.partial_cmp(target) { - None | Some(Ordering::Greater) | Some(Ordering::Equal) => { - return self; - } - Some(Ordering::Less) => (), - } - }; - - self.update(func, target.clone()) - } - - pub fn set_min(self, func: &'a Function, target: &Value) -> Self { - if let Some((index, value)) = self.get(func) { - if &self.index <= index { - return self; - } - - match value.partial_cmp(target) { - None | Some(Ordering::Less) => { - return self; - } - Some(Ordering::Equal) | Some(Ordering::Greater) => (), - } - } - - self.update(func, target.clone()) - } -} diff --git a/src/executor/alter/create_table.rs b/src/executor/alter/create_table.rs deleted file mode 100644 index 7b31673e..00000000 --- a/src/executor/alter/create_table.rs +++ /dev/null @@ -1,53 +0,0 @@ -use { - super::{validate, AlterError}, - crate::{ - data::{get_name, Schema}, - result::MutResult, - store::{AlterTable, Store, StoreMut}, - }, - sqlparser::ast::{ColumnDef, ObjectName}, - std::fmt::Debug, -}; - -pub async fn create_table + StoreMut + AlterTable>( - storage: U, - name: &ObjectName, - column_defs: &[ColumnDef], - if_not_exists: bool, -) -> MutResult { - let schema = (|| async { - let schema = Schema { - table_name: get_name(name)?.to_string(), - column_defs: column_defs.to_vec(), - }; - - for column_def in &schema.column_defs { - validate(column_def)?; - } - - match ( - storage.fetch_schema(&schema.table_name).await?, - if_not_exists, - ) { - (None, _) => Ok(Some(schema)), - (Some(_), true) => Ok(None), - (Some(_), false) => { - Err(AlterError::TableAlreadyExists(schema.table_name.to_owned()).into()) - } - } - })() - .await; - - let schema = match schema { - Ok(s) => s, - Err(e) => { - return Err((storage, e)); - } - }; - - if let Some(schema) = schema { - storage.insert_schema(&schema).await - } else { - Ok((storage, ())) - } -} diff --git a/src/executor/alter/drop.rs b/src/executor/alter/drop.rs deleted file mode 100644 index cfb9f380..00000000 --- a/src/executor/alter/drop.rs +++ /dev/null @@ -1,50 +0,0 @@ -use { - super::AlterError, - crate::{ - data::get_name, - result::MutResult, - store::{AlterTable, Store, StoreMut}, - }, - futures::stream::{self, TryStreamExt}, - sqlparser::ast::{ObjectName, ObjectType}, - std::fmt::Debug, -}; - -pub async fn drop + StoreMut + AlterTable>( - storage: U, - object_type: &ObjectType, - names: &[ObjectName], - if_exists: bool, -) -> MutResult { - if object_type != &ObjectType::Table { - return Err(( - storage, - AlterError::DropTypeNotSupported(object_type.to_string()).into(), - )); - } - - stream::iter(names.iter().map(Ok)) - .try_fold((storage, ()), |(storage, _), table_name| async move { - let schema = (|| async { - let table_name = get_name(table_name)?; - let schema = storage.fetch_schema(table_name).await?; - - if !if_exists { - schema.ok_or_else(|| AlterError::TableNotFound(table_name.to_owned()))?; - } - - Ok(table_name) - })() - .await; - - let schema = match schema { - Ok(s) => s, - Err(e) => { - return Err((storage, e)); - } - }; - - storage.delete_schema(schema).await - }) - .await -} diff --git a/src/executor/column_options/auto_increment.rs b/src/executor/alter_row/auto_increment.rs similarity index 57% rename from src/executor/column_options/auto_increment.rs rename to src/executor/alter_row/auto_increment.rs index 74902245..a0a65a5a 100644 --- a/src/executor/column_options/auto_increment.rs +++ b/src/executor/alter_row/auto_increment.rs @@ -1,25 +1,15 @@ #![cfg(feature = "auto-increment")] use { - crate::{ - data::{schema::ColumnDefExt, Row}, - result::MutResult, - store::{AlterTable, AutoIncrement, Store, StoreMut}, - Value, - }, + crate::{data::schema::ColumnDefExt, executor::types::Row, Result, StorageInner, Value}, sqlparser::ast::ColumnDef, - std::fmt::Debug, }; -pub async fn run< - T: 'static + Debug, - Storage: Store + StoreMut + AlterTable + AutoIncrement, ->( - storage: Storage, - rows: Vec, - column_defs: &[ColumnDef], +pub async fn auto_increment( + storage: &mut StorageInner, table_name: &str, -) -> MutResult> { - // FAIL: No-mut + column_defs: &[ColumnDef], + rows: Vec, +) -> Result> { let auto_increment_columns = column_defs .iter() .enumerate() @@ -29,13 +19,13 @@ pub async fn run< index, column_def.name.value.clone(), rows.iter() - .filter(|row| matches!(row.get_value(index), Some(Value::Null))) + .filter(|row| matches!(row.get(index), Some(Value::Null))) .count() as i64, ) }) .collect(); - let (storage, column_values) = storage + let column_values = storage .generate_increment_values(table_name.to_string(), auto_increment_columns) .await?; @@ -43,12 +33,13 @@ pub async fn run< let mut column_values = column_values; for row in &mut rows { for ((index, _name), value) in &mut column_values { - if matches!(row.0[*index], Value::Null) { - row.0[*index] = Value::I64(*value); + let cell = row.get_mut(*index).unwrap(); + if matches!(cell, Value::Null) { + *cell = Value::I64(*value); *value += 1; } } } - Ok((storage, rows)) + Ok(rows) } diff --git a/src/executor/alter_row/insert.rs b/src/executor/alter_row/insert.rs new file mode 100644 index 00000000..e8a4a2b1 --- /dev/null +++ b/src/executor/alter_row/insert.rs @@ -0,0 +1,41 @@ +use { + super::{auto_increment, columns_to_positions, validate, validate_unique}, + crate::{ + data::{get_name, Schema}, + executor::query::query, + ExecuteError, Payload, Result, Row, StorageInner, + }, + sqlparser::ast::{Ident, ObjectName, Query}, +}; + +pub async fn insert( + mut storages: Vec<(String, &mut StorageInner)>, + table_name: &ObjectName, + columns: &Vec, + source: &Box, +) -> Result { + let table_name = get_name(table_name)?; + let Schema { column_defs, .. } = storages[0] + .1 + .fetch_schema(table_name) + .await? + .ok_or(ExecuteError::TableNotExists)?; + + // TODO: Multi storage + let (_, rows) = query(&storages, *source.clone()).await?; + let column_positions = columns_to_positions(&column_defs, columns)?; + + let rows = validate(&column_defs, &column_positions, rows)?; + #[cfg(feature = "auto-increment")] + let rows = auto_increment(storages[0].1, table_name, &column_defs, rows).await?; + validate_unique(storages[0].1, table_name, &column_defs, &rows, None).await?; + let rows: Vec = rows.into_iter().map(Row).collect(); + + let num_rows = rows.len(); + + storages[0] + .1 + .insert_data(table_name, rows) + .await + .map(|_| Payload::Insert(num_rows)) +} diff --git a/src/executor/alter_row/mod.rs b/src/executor/alter_row/mod.rs new file mode 100644 index 00000000..2b3599df --- /dev/null +++ b/src/executor/alter_row/mod.rs @@ -0,0 +1,15 @@ +mod auto_increment; +mod insert; +mod update; +mod validate; +mod validate_unique; + +pub use { + insert::insert, + update::update, + validate::{columns_to_positions, validate, ValidateError}, + validate_unique::validate_unique, +}; + +#[cfg(feature = "auto-increment")] +pub use auto_increment::auto_increment; diff --git a/src/executor/alter_row/update.rs b/src/executor/alter_row/update.rs new file mode 100644 index 00000000..f486d530 --- /dev/null +++ b/src/executor/alter_row/update.rs @@ -0,0 +1,102 @@ +use { + super::{auto_increment, columns_to_positions, validate, validate_unique}, + crate::{ + data::{get_name, Schema}, + executor::types::{ComplexColumnName, ComplexTableName, Row as VecRow}, + ExecuteError, MetaRecipe, Payload, PlannedRecipe, RecipeUtilities, Result, Row, + StorageInner, Value, + }, + sqlparser::ast::{Assignment, ColumnDef, Expr, ObjectName}, +}; + +pub async fn update( + storage: &mut StorageInner, + table_name: &ObjectName, + selection: &Option, + assignments: &Vec, +) -> Result { + let table_name = get_name(table_name)?; + let Schema { column_defs, .. } = storage + .fetch_schema(table_name) + .await? + .ok_or(ExecuteError::TableNotExists)?; + + let columns = column_defs + .clone() + .into_iter() + .map(|column_def| { + let ColumnDef { name, .. } = column_def; + ComplexColumnName::of_name(name.value) + }) + .collect(); + + let filter = selection + .clone() + .map(|selection| PlannedRecipe::new(MetaRecipe::new(selection)?, &columns)) + .unwrap_or(Ok(PlannedRecipe::TRUE))?; + + let assignments = assignments + .into_iter() + .map(|assignment| { + let Assignment { id, value } = assignment; + let column_name = id.value.clone(); + let column_compare = vec![column_name.clone()]; + let index = columns + .iter() + .position(|column| column == &column_compare) + .ok_or(ExecuteError::ColumnNotFound)?; + let recipe = PlannedRecipe::new(MetaRecipe::new(value.clone())?, &columns)?; + Ok((index, recipe)) + }) + .collect::>>()?; + + let keyed_rows = storage + .scan_data(table_name) + .await? + .into_iter() + .filter_map(|row_result| { + let (key, row) = match row_result { + Ok(keyed_row) => keyed_row, + Err(error) => return Some(Err(error)), + }; + + let row = row.0; + + let confirm_constraint = filter.confirm_constraint(&row.clone()); + if let Ok(false) = confirm_constraint { + return None; + } else if let Err(error) = confirm_constraint { + return Some(Err(error)); + } + let row = row + .iter() + .enumerate() + .map(|(index, old_value)| { + assignments + .iter() + .find(|(assignment_index, _)| assignment_index == &index) + .map(|(_, assignment_recipe)| { + assignment_recipe.clone().simplify_by_row(&row)?.confirm() + }) + .unwrap_or(Ok(old_value.clone())) + }) + .collect::>(); + Some(row.map(|row| (key, row))) + }) + .collect::>>()?; + + let column_positions = columns_to_positions(&column_defs, &[])?; + let (keys, rows): (Vec, Vec) = keyed_rows.into_iter().unzip(); + let rows = validate(&column_defs, &column_positions, rows)?; + + let table_name = table_name.as_str(); + #[cfg(feature = "auto-increment")] + let rows = auto_increment(&mut *storage, table_name, &column_defs, rows).await?; + validate_unique(&*storage, table_name, &column_defs, &rows, Some(&keys)).await?; + let keyed_rows: Vec<(Value, Row)> = keys.into_iter().zip(rows.into_iter().map(Row)).collect(); + let num_rows = keyed_rows.len(); + storage + .update_data(keyed_rows) + .await + .map(|_| Payload::Update(num_rows)) +} diff --git a/src/executor/alter_row/validate.rs b/src/executor/alter_row/validate.rs new file mode 100644 index 00000000..689d1f9a --- /dev/null +++ b/src/executor/alter_row/validate.rs @@ -0,0 +1,123 @@ +use { + crate::{ + data::schema::ColumnDefExt, executor::types::Row, Ingredient, Recipe, RecipeUtilities, + Resolve, Result, SimplifyBy, Value, + }, + rayon::prelude::*, + serde::Serialize, + sqlparser::ast::{ColumnDef, DataType, Ident}, + thiserror::Error as ThisError, +}; + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum ValidateError { + #[error("expected value for column which neither accepts NULL nor has a default")] + MissingValue, + #[error("wrong number of values in insert statement")] + WrongNumberOfValues, + #[error("default value failed to be calculated")] + BadDefault, + #[error("column '{0}' not found")] + ColumnNotFound(String), + #[error("found duplicate value on unique field")] + //#[error("column '{0}' is unique but '{1:?}' was attempted to be stored twice")] + DuplicateEntryOnUniqueField, /*(String, Value)*/ + + #[error("this should be impossible, please report")] + UnreachableUniqueValues, +} + +pub fn columns_to_positions(column_defs: &[ColumnDef], columns: &[Ident]) -> Result> { + if columns.is_empty() { + Ok((0..column_defs.len()).collect()) + } else { + columns + .iter() + .map(|stated_column| { + column_defs + .iter() + .position(|column_def| stated_column.value == column_def.name.value) + .ok_or(ValidateError::ColumnNotFound(stated_column.value.clone()).into()) + }) + .collect::>>() + } +} + +pub fn validate( + column_defs: &[ColumnDef], + stated_columns: &[usize], + rows: Vec, +) -> Result> { + if rows.iter().any(|row| row.len() != stated_columns.len()) { + return Err(ValidateError::WrongNumberOfValues.into()); + } + + let column_info = column_defs + .into_iter() + .enumerate() + .map(|(column_def_index, column_def)| { + let ColumnDef { data_type, .. } = column_def; + let index = stated_columns + .iter() + .position(|stated_column| stated_column == &column_def_index); + + let nullable = column_def.is_nullable(); + #[cfg(feature = "auto-increment")] + let nullable = nullable || column_def.is_auto_incremented(); + + let failure_recipe = if let Some(default) = column_def.get_default() { + Some(Recipe::new_without_meta(default.clone())?) + } else if nullable { + Some(Recipe::NULL) + } else { + None + }; + Ok((index, failure_recipe, nullable, data_type)) + }) + .collect::, Option, bool, &DataType)>>>()?; + rows.into_par_iter() + .map(|row| { + column_info + .iter() + .map(|(index, failure_recipe, nullable, data_type)| { + index + .map(|index| { + row.get(index).map(|value| { + let mut value = value.clone(); + if let Err(error) = value.validate_null(nullable.clone()) { + value = if let Some(fallback) = failure_recipe.clone() { + if !matches!( + fallback, + Recipe::Ingredient(Ingredient::Value(Value::Null)) + ) { + fallback + .simplify(SimplifyBy::Basic)? + .as_solution() + .ok_or(ValidateError::BadDefault)? + } else { + return Err(error); + } + } else { + return Err(error); + } + } + value = value.validate_type(data_type)?; + Ok(value) + }) + }) + .flatten() + .unwrap_or({ + if let Some(recipe) = failure_recipe.clone() { + recipe + .simplify(SimplifyBy::Basic)? + .as_solution() + .ok_or(ValidateError::BadDefault.into()) + } else { + Err(ValidateError::MissingValue.into()) + } + }) + }) + .collect::>() + }) + .collect::>>() +} diff --git a/src/executor/alter_row/validate_unique.rs b/src/executor/alter_row/validate_unique.rs new file mode 100644 index 00000000..b4433f12 --- /dev/null +++ b/src/executor/alter_row/validate_unique.rs @@ -0,0 +1,163 @@ +use { + super::ValidateError, + crate::{ + data::schema::ColumnDefExt, executor::types::Row, NullOrd, Result, StorageInner, Value, + }, + sqlparser::ast::ColumnDef, + std::cmp::Ordering, +}; + +macro_rules! some_or_continue { + ($option: expr) => { + match $option { + Some(value) => value, + None => return Some(Ok(())), + } + }; +} +macro_rules! some_or { + ($option: expr, $or: block) => { + match $option { + Some(value) => value, + None => $or, + } + }; +} + +pub async fn validate_unique( + storage: &StorageInner, + table_name: &str, + column_defs: &[ColumnDef], + rows: &[Row], + ignore_keys: Option<&Vec>, +) -> Result<()> { + let unique_columns: Vec = column_defs + .iter() + .enumerate() + .filter_map(|(index, column_def)| { + if column_def.is_unique() { + Some(index) + } else { + None + } + }) + .collect(); + let mut existing_values: Vec> = vec![vec![]; unique_columns.len()]; + + storage + .scan_data(table_name) + .await? + .map(|result| { + let (key, row) = result?; + if let Some(ignore_keys) = ignore_keys { + if ignore_keys.iter().any(|ignore_key| ignore_key == &key) { + return Ok(()); + } + } + let row = row.0; + unique_columns + .iter() + .enumerate() + .map(|(index, row_index)| { + existing_values + .get_mut(index)? + .push(row.get(*row_index)?.clone()); + Some(()) + }) + .collect::>() + .ok_or(ValidateError::UnreachableUniqueValues.into()) + }) + .collect::>()?; + + let mut new_values: Vec> = vec![vec![]; unique_columns.len()]; + rows.into_iter() + .map(|row| { + unique_columns + .iter() + .enumerate() + .map(|(index, row_index)| { + new_values + .get_mut(index)? + .push(row.get(*row_index)?.clone()); + Some(()) + }) + .collect::>() + .ok_or(ValidateError::UnreachableUniqueValues.into()) + }) + .collect::>()?; + let mut existing_values_iter = existing_values.into_iter(); + new_values + .into_iter() + .map(|mut new_values| { + let mut existing_values = existing_values_iter.next()?; + + existing_values.sort_unstable_by(|value_l, value_r| { + value_l.partial_cmp(&value_r).unwrap_or(Ordering::Equal) + }); + new_values.sort_unstable_by(|value_l, value_r| { + value_l.partial_cmp(&value_r).unwrap_or(Ordering::Equal) + }); + + let mut existing_values = existing_values.into_iter(); + let mut new_values = new_values.into_iter(); + + let mut new_value = some_or_continue!(new_values.next()); + let mut existing_value = some_or!(existing_values.next(), { + loop { + let new_new = some_or_continue!(new_values.next()); + if new_new == new_value { + return Some(Err(ValidateError::DuplicateEntryOnUniqueField.into())); + } + new_value = new_new; + } + }); + + loop { + match existing_value.null_cmp(&new_value) { + Some(Ordering::Equal) => { + return Some(Err(ValidateError::DuplicateEntryOnUniqueField.into())) + } + Some(Ordering::Greater) => { + let new_new = some_or_continue!(new_values.next()); + if new_new == new_value { + return Some(Err(ValidateError::DuplicateEntryOnUniqueField.into())); + } + new_value = new_new; + } + Some(Ordering::Less) => { + existing_value = some_or!(existing_values.next(), { + loop { + let new_new = some_or_continue!(new_values.next()); + if new_new == new_value { + return Some(Err( + ValidateError::DuplicateEntryOnUniqueField.into() + )); + } + new_value = new_new; + } + }); + } + None => { + let new_new = some_or_continue!(new_values.next()); + if new_new == new_value { + return Some(Err(ValidateError::DuplicateEntryOnUniqueField.into())); + } + new_value = new_new; + existing_value = some_or!(existing_values.next(), { + loop { + let new_new = some_or_continue!(new_values.next()); + if new_new == new_value { + return Some(Err( + ValidateError::DuplicateEntryOnUniqueField.into() + )); + } + new_value = new_new; + } + }); + } + } + } + }) + .collect::>>() + .ok_or(ValidateError::UnreachableUniqueValues)? +} diff --git a/src/executor/alter/alter_table.rs b/src/executor/alter_table/alter_table.rs similarity index 55% rename from src/executor/alter/alter_table.rs rename to src/executor/alter_table/alter_table.rs index 5c19033e..863256d2 100644 --- a/src/executor/alter/alter_table.rs +++ b/src/executor/alter_table/alter_table.rs @@ -1,37 +1,21 @@ use { super::{validate, AlterError}, - crate::{ - data::get_name, - result::MutResult, - store::{AlterTable, Store, StoreMut}, - }, + crate::{data::get_name, Error, Result, StorageInner}, sqlparser::ast::{AlterTableOperation, ObjectName}, - std::fmt::Debug, }; -macro_rules! try_into { - ($storage: expr, $expr: expr) => { - match $expr { - Err(e) => { - return Err(($storage, e.into())); - } - Ok(v) => v, - } - }; -} - -pub async fn alter_table + StoreMut + AlterTable>( - storage: U, +pub async fn alter_table( + storage: &mut StorageInner, name: &ObjectName, operation: &AlterTableOperation, -) -> MutResult { - let table_name = try_into!(storage, get_name(name)); +) -> Result<()> { + let table_name = get_name(name).map_err(Error::from)?; match operation { AlterTableOperation::RenameTable { table_name: new_table_name, } => { - let new_table_name = try_into!(storage, get_name(new_table_name)); + let new_table_name = get_name(new_table_name).map_err(Error::from)?; storage.rename_schema(table_name, new_table_name).await } @@ -44,7 +28,7 @@ pub async fn alter_table + StoreMut + AlterTa .await } AlterTableOperation::AddColumn { column_def } => { - try_into!(storage, validate(column_def)); + validate(column_def).map_err(Error::from)?; storage.add_column(table_name, column_def).await } @@ -57,9 +41,6 @@ pub async fn alter_table + StoreMut + AlterTa .drop_column(table_name, &column_name.value, *if_exists) .await } - _ => Err(( - storage, - AlterError::UnsupportedAlterTableOperation(operation.to_string()).into(), - )), + _ => Err(AlterError::UnsupportedAlterTableOperation(operation.to_string()).into()), } } diff --git a/src/executor/alter_table/create_table.rs b/src/executor/alter_table/create_table.rs new file mode 100644 index 00000000..0f984168 --- /dev/null +++ b/src/executor/alter_table/create_table.rs @@ -0,0 +1,34 @@ +use { + super::{validate, AlterError}, + crate::{ + data::{get_name, Schema}, + Result, StorageInner, + }, + sqlparser::ast::{ColumnDef, ObjectName}, +}; + +pub async fn create_table( + storage: &mut StorageInner, + name: &ObjectName, + column_defs: &[ColumnDef], + if_not_exists: bool, +) -> Result<()> { + let schema = Schema { + table_name: get_name(name)?.to_string(), + column_defs: column_defs.to_vec(), + }; + + for column_def in &schema.column_defs { + validate(column_def)?; + } + + if let Some(_) = storage.fetch_schema(&schema.table_name).await? { + if !if_not_exists { + Err(AlterError::TableAlreadyExists(schema.table_name.to_owned()).into()) + } else { + Ok(()) + } + } else { + storage.insert_schema(&schema).await + } +} diff --git a/src/executor/alter_table/drop.rs b/src/executor/alter_table/drop.rs new file mode 100644 index 00000000..b358dc10 --- /dev/null +++ b/src/executor/alter_table/drop.rs @@ -0,0 +1,58 @@ +use { + super::AlterError, + crate::{ + data::{get_name, schema::ColumnDefExt}, + Result, StorageInner, + }, + futures::stream::{self, TryStreamExt}, + sqlparser::ast::{ObjectName, ObjectType}, +}; + +pub async fn drop( + storage: &mut StorageInner, + object_type: &ObjectType, + names: &[ObjectName], + if_exists: bool, +) -> Result<()> { + if object_type != &ObjectType::Table { + return Err(AlterError::DropTypeNotSupported(object_type.to_string()).into()); + } + + stream::iter(names.iter().map(Ok)) + .try_fold(storage, |storage, table_name| async move { + let table_name = get_name(table_name)?; + let schema = storage.fetch_schema(table_name).await?; + + if schema.is_none() { + if !if_exists { + return Err(AlterError::TableNotFound(table_name.to_owned()).into()); + } else { + return Ok(storage); + } + } + #[cfg(feature = "auto-increment")] + let result: Result<&mut StorageInner> = + stream::iter(schema.unwrap().column_defs.into_iter().map(Ok)) + .try_fold(storage, |storage, column| async move { + if column.is_auto_incremented() { + storage + .set_increment_value( + table_name, + column.name.value.as_str(), + 1 as i64, + ) + .await?; + } + Ok(storage) + }) + .await; + + #[cfg(feature = "auto-increment")] + let storage = result?; + + storage.delete_schema(table_name).await?; + Ok(storage) + }) + .await + .map(|_| ()) +} diff --git a/src/executor/alter/error.rs b/src/executor/alter_table/error.rs similarity index 100% rename from src/executor/alter/error.rs rename to src/executor/alter_table/error.rs diff --git a/src/executor/alter/mod.rs b/src/executor/alter_table/mod.rs similarity index 100% rename from src/executor/alter/mod.rs rename to src/executor/alter_table/mod.rs diff --git a/src/executor/alter/validate.rs b/src/executor/alter_table/validate.rs similarity index 100% rename from src/executor/alter/validate.rs rename to src/executor/alter_table/validate.rs diff --git a/src/executor/blend.rs b/src/executor/blend.rs deleted file mode 100644 index 0acf0d90..00000000 --- a/src/executor/blend.rs +++ /dev/null @@ -1,86 +0,0 @@ -use futures::stream::{self, StreamExt, TryStreamExt}; -use im_rc::HashMap; -use serde::Serialize; -use std::convert::TryInto; -use std::fmt::Debug; -use std::rc::Rc; -use thiserror::Error as ThisError; - -use sqlparser::ast::{Function, SelectItem}; - -use super::context::{AggregateContext, BlendContext, FilterContext}; -use super::evaluate::evaluate; -use crate::data::{get_name, Row, Value}; -use crate::result::{Error, Result}; -use crate::store::Store; - -#[derive(ThisError, Serialize, Debug, PartialEq)] -pub enum BlendError { - #[error("table alias not found: {0}")] - TableAliasNotFound(String), -} - -pub struct Blend<'a, T: 'static + Debug> { - storage: &'a dyn Store, - fields: &'a [SelectItem], -} - -impl<'a, T: 'static + Debug> Blend<'a, T> { - pub fn new(storage: &'a dyn Store, fields: &'a [SelectItem]) -> Self { - Self { storage, fields } - } - - pub async fn apply(&self, context: Result>) -> Result { - let AggregateContext { aggregated, next } = context?; - let values = self.blend(aggregated, next).await?; - - Ok(Row(values)) - } - - async fn blend( - &self, - aggregated: Option>, - context: Rc>, - ) -> Result> { - let filter_context = FilterContext::concat(None, Some(Rc::clone(&context))); - let filter_context = Some(filter_context).map(Rc::new); - - let aggregated = aggregated.map(Rc::new); - - let values = stream::iter(self.fields.iter()) - .map(Ok::<&'a SelectItem, Error>) - .and_then(|item| { - let context = Rc::clone(&context); - let filter_context = filter_context.as_ref().map(Rc::clone); - let aggregated = aggregated.as_ref().map(Rc::clone); - - async move { - match item { - SelectItem::Wildcard => Ok(context.get_all_values()), - SelectItem::QualifiedWildcard(alias) => { - let table_alias = get_name(alias)?; - - match context.get_alias_values(table_alias) { - Some(values) => Ok(values), - None => { - Err(BlendError::TableAliasNotFound(table_alias.to_string()) - .into()) - } - } - } - SelectItem::UnnamedExpr(expr) | SelectItem::ExprWithAlias { expr, .. } => { - evaluate(self.storage, filter_context, aggregated, expr, true) - .await - .map(|evaluated| evaluated.try_into())? - .map(|v| vec![v]) - } - } - } - }) - .try_collect::>>() - .await? - .concat(); - - Ok(values) - } -} diff --git a/src/executor/column_options/mod.rs b/src/executor/column_options/mod.rs deleted file mode 100644 index 0bbb3f56..00000000 --- a/src/executor/column_options/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -#[cfg(feature = "auto-increment")] -pub mod auto_increment; diff --git a/src/executor/context/aggregate_context.rs b/src/executor/context/aggregate_context.rs deleted file mode 100644 index 6e8cc7da..00000000 --- a/src/executor/context/aggregate_context.rs +++ /dev/null @@ -1,14 +0,0 @@ -use im_rc::HashMap; -use std::fmt::Debug; -use std::rc::Rc; - -use sqlparser::ast::Function; - -use super::BlendContext; -use crate::data::Value; - -#[derive(Debug)] -pub struct AggregateContext<'a> { - pub aggregated: Option>, - pub next: Rc>, -} diff --git a/src/executor/context/blend_context.rs b/src/executor/context/blend_context.rs deleted file mode 100644 index 04c501a8..00000000 --- a/src/executor/context/blend_context.rs +++ /dev/null @@ -1,99 +0,0 @@ -use std::fmt::Debug; -use std::rc::Rc; - -use sqlparser::ast::Ident; - -use crate::data::{Row, Value}; - -#[derive(Debug)] -pub struct BlendContext<'a> { - table_alias: &'a str, - pub columns: Rc<[Ident]>, - pub row: Option, - next: Option>>, -} - -impl<'a> BlendContext<'a> { - pub fn new( - table_alias: &'a str, - columns: Rc<[Ident]>, - row: Option, - next: Option>>, - ) -> Self { - Self { - table_alias, - columns, - row, - next, - } - } - - pub fn get_value(&'a self, target: &str) -> Option<&'a Value> { - let get_value = || { - self.columns - .iter() - .position(|column| column.value == target) - .map(|index| self.row.as_ref().and_then(|row| row.get_value(index))) - }; - - match get_value() { - None => match &self.next { - None => None, - Some(context) => context.get_value(target), - }, - Some(value) => value, - } - } - - pub fn get_alias_value(&'a self, table_alias: &str, target: &str) -> Option<&'a Value> { - let get_value = || { - if self.table_alias != table_alias { - return None; - } - - self.columns - .iter() - .position(|column| column.value == target) - .map(|index| self.row.as_ref().and_then(|row| row.get_value(index))) - }; - - match get_value() { - None => match &self.next { - None => None, - Some(context) => context.get_alias_value(table_alias, target), - }, - Some(value) => value, - } - } - - pub fn get_alias_values(&self, alias: &str) -> Option> { - if self.table_alias == alias { - let values = match &self.row { - Some(Row(values)) => values.clone(), - None => self.columns.iter().map(|_| Value::Null).collect(), - }; - - Some(values) - } else { - self.next - .as_ref() - .and_then(|next| next.get_alias_values(alias)) - } - } - - pub fn get_all_values(&'a self) -> Vec { - let values: Vec = match &self.row { - Some(Row(values)) => values.clone(), - None => self.columns.iter().map(|_| Value::Null).collect(), - }; - - match &self.next { - Some(next) => next - .get_all_values() - .into_iter() - .chain(values.into_iter()) - .collect(), - None => values, - } - } -} diff --git a/src/executor/context/filter_context.rs b/src/executor/context/filter_context.rs deleted file mode 100644 index 386bd13c..00000000 --- a/src/executor/context/filter_context.rs +++ /dev/null @@ -1,111 +0,0 @@ -use std::fmt::Debug; -use std::rc::Rc; - -use sqlparser::ast::Ident; - -use super::BlendContext; -use crate::data::{Row, Value}; - -#[derive(Debug)] -enum Content<'a> { - Some { - table_alias: &'a str, - columns: Rc<[Ident]>, - row: Option<&'a Row>, - }, - None, -} - -#[derive(Debug)] -pub struct FilterContext<'a> { - content: Content<'a>, - next: Option>>, - next2: Option>>, -} - -impl<'a> FilterContext<'a> { - pub fn new( - table_alias: &'a str, - columns: Rc<[Ident]>, - row: Option<&'a Row>, - next: Option>>, - ) -> Self { - Self { - content: Content::Some { - table_alias, - columns, - row, - }, - next, - next2: None, - } - } - - pub fn concat( - filter_context: Option>>, - blend_context: Option>>, - ) -> Self { - Self { - content: Content::None, - next: filter_context, - next2: blend_context, - } - } - - pub fn get_value(&'a self, target: &str) -> Option<&'a Value> { - if let Content::Some { columns, row, .. } = &self.content { - let value = columns - .iter() - .position(|column| column.value == target) - .map(|index| row.and_then(|row| row.get_value(index))); - - if let Some(value) = value { - return value; - } - } - - match (&self.next, &self.next2) { - (None, None) => None, - (Some(fc), None) => fc.get_value(target), - (None, Some(bc)) => bc.get_value(target), - (Some(fc), Some(bc)) => match bc.get_value(target) { - v @ Some(_) => v, - None => fc.get_value(target), - }, - } - } - - pub fn get_alias_value(&'a self, target_alias: &str, target: &str) -> Option<&'a Value> { - if let Content::Some { - table_alias, - columns, - row, - } = &self.content - { - let get_value = || { - if table_alias != &target_alias { - return None; - } - - columns - .iter() - .position(|column| column.value == target) - .map(|index| row.and_then(|row| row.get_value(index))) - }; - - if let Some(value) = get_value() { - return value; - } - } - - match (&self.next, &self.next2) { - (None, None) => None, - (Some(fc), None) => fc.get_alias_value(target_alias, target), - (None, Some(bc)) => bc.get_alias_value(target_alias, target), - (Some(fc), Some(bc)) => match bc.get_alias_value(target_alias, target) { - v @ Some(_) => v, - None => fc.get_alias_value(target_alias, target), - }, - } - } -} diff --git a/src/executor/context/mod.rs b/src/executor/context/mod.rs deleted file mode 100644 index 9c2ca6b1..00000000 --- a/src/executor/context/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -mod aggregate_context; -mod blend_context; -mod filter_context; - -pub use aggregate_context::AggregateContext; -pub use blend_context::BlendContext; -pub use filter_context::FilterContext; diff --git a/src/executor/evaluate/error.rs b/src/executor/evaluate/error.rs deleted file mode 100644 index 34d2547e..00000000 --- a/src/executor/evaluate/error.rs +++ /dev/null @@ -1,44 +0,0 @@ -use serde::Serialize; -use std::fmt::Debug; -use thiserror::Error; - -#[derive(Error, Serialize, Debug, PartialEq)] -pub enum EvaluateError { - #[error("nested select row not found")] - NestedSelectRowNotFound, - - #[error("literal add on non-numeric")] - LiteralAddOnNonNumeric, - - #[error("function is not supported: {0}")] - FunctionNotSupported(String), - - #[error("function requires string value: {0}")] - FunctionRequiresStringValue(String), - - #[error("function requires string value: {0}")] - FunctionRequiresIntegerValue(String), - - #[error("function requires usize value: {0}")] - FunctionRequiresUSizeValue(String), - - #[error( - "number of function parameters not matching (expected: {expected:?}, found: {found:?})" - )] - NumberOfFunctionParamsNotMatching { expected: usize, found: usize }, - - #[error("value not found: {0}")] - ValueNotFound(String), - - #[error("unsupported compound identifier {0}")] - UnsupportedCompoundIdentifier(String), - - #[error("unimplemented")] - Unimplemented, - - #[error("unreachable empty context")] - UnreachableEmptyContext, - - #[error("unreachable named function argument: {0}")] - UnreachableFunctionArg(String), -} diff --git a/src/executor/evaluate/evaluated.rs b/src/executor/evaluate/evaluated.rs deleted file mode 100644 index b8cb140f..00000000 --- a/src/executor/evaluate/evaluated.rs +++ /dev/null @@ -1,128 +0,0 @@ -use { - crate::{ - data::value::TryFromLiteral, - data::{Literal, Value}, - result::{Error, Result}, - }, - sqlparser::ast::DataType, - std::{ - borrow::Cow, - cmp::Ordering, - convert::{TryFrom, TryInto}, - }, -}; - -#[derive(Clone)] -pub enum Evaluated<'a> { - Literal(Literal<'a>), - Value(Cow<'a, Value>), -} - -impl<'a> From for Evaluated<'a> { - fn from(value: Value) -> Self { - Evaluated::Value(Cow::Owned(value)) - } -} - -impl<'a> From<&'a Value> for Evaluated<'a> { - fn from(value: &'a Value) -> Self { - Evaluated::Value(Cow::Borrowed(value)) - } -} - -impl TryInto for Evaluated<'_> { - type Error = Error; - - fn try_into(self) -> Result { - match self { - Evaluated::Literal(v) => Value::try_from(v), - Evaluated::Value(v) => Ok(v.into_owned()), - } - } -} - -impl<'a> PartialEq for Evaluated<'a> { - fn eq(&self, other: &Evaluated<'a>) -> bool { - match (self, other) { - (Evaluated::Literal(a), Evaluated::Literal(b)) => a == b, - (Evaluated::Literal(b), Evaluated::Value(a)) - | (Evaluated::Value(a), Evaluated::Literal(b)) => a.as_ref() == b, - (Evaluated::Value(a), Evaluated::Value(b)) => a == b, - } - } -} - -impl<'a> PartialOrd for Evaluated<'a> { - fn partial_cmp(&self, other: &Evaluated<'a>) -> Option { - match (self, other) { - (Evaluated::Literal(l), Evaluated::Literal(r)) => l.partial_cmp(r), - (Evaluated::Literal(l), Evaluated::Value(r)) => { - r.as_ref().partial_cmp(l).map(|o| o.reverse()) - } - (Evaluated::Value(l), Evaluated::Literal(r)) => l.as_ref().partial_cmp(r), - (Evaluated::Value(l), Evaluated::Value(r)) => l.as_ref().partial_cmp(r.as_ref()), - } - } -} - -macro_rules! binary_op { - ($name:ident, $op:tt) => { - pub fn $name<'b>(&self, other: &Evaluated<'a>) -> Result> { - let value_binary_op = |l: &Value, r: &Value| l.$name(r).map(Evaluated::from); - - match (self, other) { - (Evaluated::Literal(l), Evaluated::Literal(r)) => { - l.$name(r).map(Evaluated::Literal) - } - (Evaluated::Literal(l), Evaluated::Value(r)) => { - value_binary_op(&Value::try_from(l)?, r.as_ref()) - } - (Evaluated::Value(l), Evaluated::Literal(r)) => { - value_binary_op(l.as_ref(), &Value::try_from(r)?) - } - (Evaluated::Value(l), Evaluated::Value(r)) => { - value_binary_op(l.as_ref(), r.as_ref()) - } - } - } - }; -} - -impl<'a> Evaluated<'a> { - binary_op!(add, +); - binary_op!(subtract, -); - binary_op!(multiply, *); - binary_op!(divide, /); - - pub fn unary_plus(&self) -> Result> { - match self { - Evaluated::Literal(v) => v.unary_plus().map(Evaluated::Literal), - Evaluated::Value(v) => v.unary_plus().map(Evaluated::from), - } - } - - pub fn unary_minus(&self) -> Result> { - match self { - Evaluated::Literal(v) => v.unary_minus().map(Evaluated::Literal), - Evaluated::Value(v) => v.unary_minus().map(Evaluated::from), - } - } - - pub fn cast(self, data_type: &DataType) -> Result> { - let cast_literal = |literal: &Literal| Value::try_cast_from_literal(data_type, literal); - let cast_value = |value: &Value| value.cast(data_type); - - match self { - Evaluated::Literal(value) => cast_literal(&value), - Evaluated::Value(value) => cast_value(&value), - } - .map(Evaluated::from) - } - - pub fn is_some(&self) -> bool { - match self { - Evaluated::Value(v) => v.is_some(), - Evaluated::Literal(v) => !matches!(v, &Literal::Null), - } - } -} diff --git a/src/executor/evaluate/mod.rs b/src/executor/evaluate/mod.rs deleted file mode 100644 index b530b3b1..00000000 --- a/src/executor/evaluate/mod.rs +++ /dev/null @@ -1,226 +0,0 @@ -mod error; -mod evaluated; - -use { - super::{context::FilterContext, select::select}, - crate::{ - data::{get_name, Literal, Value}, - result::Result, - store::Store, - }, - async_recursion::async_recursion, - futures::stream::{StreamExt, TryStreamExt}, - im_rc::HashMap, - sqlparser::ast::{BinaryOperator, Expr, Function, FunctionArg, UnaryOperator}, - std::{ - borrow::Cow, - convert::{TryFrom, TryInto}, - fmt::Debug, - rc::Rc, - }, -}; - -pub use {error::EvaluateError, evaluated::Evaluated}; - -#[async_recursion(?Send)] -pub async fn evaluate<'a, T: 'static + Debug>( - storage: &'a dyn Store, - context: Option>>, - aggregated: Option>>, - expr: &'a Expr, - use_empty: bool, -) -> Result> { - let eval = |expr| { - let context = context.as_ref().map(Rc::clone); - let aggregated = aggregated.as_ref().map(Rc::clone); - - evaluate(storage, context, aggregated, expr, use_empty) - }; - - match expr { - Expr::Value(value) => Literal::try_from(value).map(Evaluated::Literal), - Expr::Identifier(ident) => match ident.quote_style { - Some(_) => Ok(Literal::Text(Cow::Borrowed(&ident.value))).map(Evaluated::Literal), - None => { - let context = context.ok_or(EvaluateError::UnreachableEmptyContext)?; - - match (context.get_value(&ident.value), use_empty) { - (Some(value), _) => Ok(value.clone()), - (None, true) => Ok(Value::Null), - (None, false) => { - Err(EvaluateError::ValueNotFound(ident.value.to_string()).into()) - } - } - .map(Evaluated::from) - } - }, - Expr::Nested(expr) => eval(&expr).await, - Expr::CompoundIdentifier(idents) => { - if idents.len() != 2 { - return Err(EvaluateError::UnsupportedCompoundIdentifier(expr.to_string()).into()); - } - - let table_alias = &idents[0].value; - let column = &idents[1].value; - let context = context.ok_or(EvaluateError::UnreachableEmptyContext)?; - - match (context.get_alias_value(table_alias, column), use_empty) { - (Some(value), _) => Ok(value.clone()), - (None, true) => Ok(Value::Null), - (None, false) => Err(EvaluateError::ValueNotFound(column.to_string()).into()), - } - .map(Evaluated::from) - } - Expr::Subquery(query) => select(storage, &query, context.as_ref().map(Rc::clone)) - .await? - .map_ok(|row| row.take_first_value().map(Evaluated::from)) - .take(1) - .collect::>() - .await - .into_iter() - .next() - .unwrap_or_else(|| Err(EvaluateError::NestedSelectRowNotFound.into()))?, - Expr::BinaryOp { op, left, right } => { - let l = eval(left).await?; - let r = eval(right).await?; - - match op { - BinaryOperator::Plus => l.add(&r), - BinaryOperator::Minus => l.subtract(&r), - BinaryOperator::Multiply => l.multiply(&r), - BinaryOperator::Divide => l.divide(&r), - _ => Err(EvaluateError::Unimplemented.into()), - } - } - Expr::UnaryOp { op, expr } => { - let v = eval(expr).await?; - - match op { - UnaryOperator::Plus => v.unary_plus(), - UnaryOperator::Minus => v.unary_minus(), - _ => Err(EvaluateError::Unimplemented.into()), - } - } - Expr::Function(func) => match aggregated.as_ref().map(|aggr| aggr.get(func)).flatten() { - Some(value) => Ok(Evaluated::from(value.clone())), - None => { - let context = context.as_ref().map(Rc::clone); - let aggregated = aggregated.as_ref().map(Rc::clone); - - evaluate_function(storage, context, aggregated, func, use_empty).await - } - }, - Expr::Cast { expr, data_type } => eval(expr).await?.cast(data_type), - _ => Err(EvaluateError::Unimplemented.into()), - } -} - -async fn evaluate_function<'a, T: 'static + Debug>( - storage: &'a dyn Store, - context: Option>>, - aggregated: Option>>, - func: &'a Function, - use_empty: bool, -) -> Result> { - let eval = |expr| { - let context = context.as_ref().map(Rc::clone); - let aggregated = aggregated.as_ref().map(Rc::clone); - - evaluate(storage, context, aggregated, expr, use_empty) - }; - - let get_arg_expr = |arg: &'a FunctionArg| -> Result<&'a Expr> { - match arg { - FunctionArg::Unnamed(expr) => Ok(expr), - FunctionArg::Named { name, .. } => { - Err(EvaluateError::UnreachableFunctionArg(name.to_string()).into()) - } - } - }; - - let Function { name, args, .. } = func; - - match get_name(name)?.to_uppercase().as_str() { - name @ "LOWER" | name @ "UPPER" => { - let convert = |s: String| { - if name == "LOWER" { - s.to_lowercase() - } else { - s.to_uppercase() - } - }; - - let arg = match args.len() { - 1 => &args[0], - found => { - return Err(EvaluateError::NumberOfFunctionParamsNotMatching { - expected: 1, - found, - } - .into()); - } - }; - - let expr = get_arg_expr(arg)?; - let value: Value = match eval(expr).await?.try_into()? { - Value::Str(s) => Value::Str(convert(s)), - Value::Null => Value::Null, - _ => { - return Err(EvaluateError::FunctionRequiresStringValue(name.to_string()).into()); - } - }; - - Ok(Evaluated::from(value)) - } - name @ "LEFT" | name @ "RIGHT" => { - match args.len() { - 2 => (), - found => { - return Err(EvaluateError::NumberOfFunctionParamsNotMatching { - expected: 2, - found, - } - .into()) - } - } - - let string = match eval(get_arg_expr(&args[0])?).await?.try_into()? { - Value::Str(string) => Ok(string), - Value::Null => { - return Ok(Evaluated::from(Value::Null)); - } - _ => Err(EvaluateError::FunctionRequiresStringValue(name.to_string())), - }?; - - let number = match eval(get_arg_expr(&args[1])?).await?.try_into()? { - Value::I64(number) => usize::try_from(number) - .map_err(|_| EvaluateError::FunctionRequiresUSizeValue(name.to_string())), // Unlikely to occur hence the imperfect error - Value::Null => { - return Ok(Evaluated::from(Value::Null)); - } - _ => Err(EvaluateError::FunctionRequiresIntegerValue( - name.to_string(), - )), - }?; - - let converted = { - if name == "LEFT" { - string.get(..number) - } else { - let start_pos = if number > string.len() { - 0 - } else { - string.len() - number - }; - - string.get(start_pos..) - } - .map(|value| value.to_string()) - .unwrap_or(string) - }; - - Ok(Evaluated::from(Value::Str(converted))) - } - name => Err(EvaluateError::FunctionNotSupported(name.to_owned()).into()), - } -} diff --git a/src/executor/execute.rs b/src/executor/execute.rs index c2400e77..352d62aa 100644 --- a/src/executor/execute.rs +++ b/src/executor/execute.rs @@ -1,30 +1,22 @@ use { super::{ - alter::{create_table, drop}, - fetch::{fetch, fetch_columns}, - filter::Filter, - select::select_with_labels, - update::Update, - validate::{validate_unique, ColumnValidation}, + alter_row::{insert, update}, + alter_table::{create_table, drop}, + query::query, + types::ComplexColumnName, }, crate::{ - data::{bulk_build_rows_expr, bulk_build_rows_row, get_name, Row, Schema}, + data::{get_name, Schema}, parse_sql::Query, - result::{MutResult, Result}, - store::{AlterTable, AutoIncrement, Store, StoreMut}, + MetaRecipe, PlannedRecipe, Result, Row, StorageInner, Value, }, - futures::stream::TryStreamExt, serde::Serialize, - sqlparser::ast::{Query as AstQuery, SetExpr, Statement, Values}, - std::{fmt::Debug, rc::Rc}, + sqlparser::ast::{ColumnDef, Statement}, thiserror::Error as ThisError, }; #[cfg(feature = "alter-table")] -use super::alter::alter_table; - -#[cfg(feature = "auto-increment")] -use super::column_options::auto_increment; +use super::alter_table::alter_table; #[derive(ThisError, Serialize, Debug, PartialEq)] pub enum ExecuteError { @@ -36,6 +28,9 @@ pub enum ExecuteError { #[error("table does not exist")] TableNotExists, + + #[error("column could not be found")] + ColumnNotFound, } #[derive(Serialize, Debug, PartialEq)] @@ -54,34 +49,13 @@ pub enum Payload { AlterTable, } -pub async fn execute + StoreMut + AlterTable + AutoIncrement>( - storage: U, - query: &Query, -) -> MutResult { - macro_rules! try_block { - ($storage: expr, $block: block) => {{ - match (|| async { $block })().await { - Err(e) => { - return Err(($storage, e)); - } - Ok(v) => v, - } - }}; - } - macro_rules! try_into { - ($storage: expr, $expr: expr) => { - match $expr { - Err(e) => { - return Err(($storage, e)); - } - Ok(v) => v, - } - }; - } - - let Query(query) = query; +pub async fn execute( + mut storages: Vec<(String, &mut StorageInner)>, + statement: &Query, +) -> Result { + let Query(statement) = statement; - match query { + match statement { //- Modification //-- Tables Statement::CreateTable { @@ -89,21 +63,21 @@ pub async fn execute + StoreMut + AlterTable columns, if_not_exists, .. - } => create_table(storage, name, columns, *if_not_exists) + } => create_table(storages[0].1, name, columns, *if_not_exists) .await - .map(|(storage, _)| (storage, Payload::Create)), + .map(|_| Payload::Create), Statement::Drop { object_type, names, if_exists, .. - } => drop(storage, object_type, names, *if_exists) + } => drop(storages[0].1, object_type, names, *if_exists) .await - .map(|(storage, _)| (storage, Payload::DropTable)), + .map(|_| Payload::DropTable), #[cfg(feature = "alter-table")] - Statement::AlterTable { name, operation } => alter_table(storage, name, operation) + Statement::AlterTable { name, operation } => alter_table(storages[0].1, name, operation) .await - .map(|(storage, _)| (storage, Payload::AlterTable)), + .map(|_| Payload::AlterTable), //-- Rows Statement::Insert { @@ -111,156 +85,73 @@ pub async fn execute + StoreMut + AlterTable columns, source, .. - } => { - #[allow(unused_variables)] - let (rows, column_defs, column_validation, table_name) = try_block!(storage, { - let table_name = get_name(table_name)?; - let Schema { column_defs, .. } = storage - .fetch_schema(table_name) - .await? - .ok_or(ExecuteError::TableNotExists)?; - let column_defs = Rc::from(column_defs); - let column_validation = ColumnValidation::All(Rc::clone(&column_defs)); - - let rows = match &source.body { - SetExpr::Values(Values(values_list)) => { - bulk_build_rows_expr( - &storage, - &column_defs, - columns, - values_list.to_vec(), - true, - true, - ) - .await? - } - SetExpr::Select(select_query) => { - let query = Box::new(AstQuery { - with: None, - body: SetExpr::Select(select_query.clone()), - order_by: vec![], - limit: None, - offset: None, - fetch: None, - }); - let rows = select(&storage, &query).await?.1; - bulk_build_rows_row(&storage, &column_defs, columns, rows, true, true) - .await? - // TODO: Improve efficiency, this should happen much earlier than this. - } - set_expr => { - return Err(ExecuteError::UnreachableUnsupportedInsertValueType( - set_expr.to_string(), - ) - .into()); - } - }; - - Ok((rows, column_defs, column_validation, table_name)) - }); - - #[cfg(feature = "auto-increment")] - let (storage, rows) = - auto_increment::run(storage, rows, &column_defs, table_name).await?; - - try_into!(storage, { - validate_unique(&storage, &table_name, column_validation, rows.iter()).await - }); - - let num_rows = rows.len(); - - storage - .insert_data(table_name, rows) - .await - .map(|(storage, _)| (storage, Payload::Insert(num_rows))) - } + } => insert(storages, table_name, columns, source).await, Statement::Update { table_name, selection, assignments, - } => { - let rows = try_block!(storage, { - let table_name = get_name(table_name)?; - let Schema { column_defs, .. } = storage - .fetch_schema(table_name) - .await? - .ok_or(ExecuteError::TableNotExists)?; - let update = Update::new(&storage, table_name, assignments, &column_defs)?; - let filter = Filter::new(&storage, selection.as_ref(), None, None); - - let all_columns = Rc::from(update.all_columns()); - let columns_to_update = update.columns_to_update(); - let rows = fetch(&storage, table_name, Rc::clone(&all_columns), filter) - .await? - .and_then(|item| { - let update = &update; - let (_, key, row) = item; - async move { - let row = update.apply(row).await?; - Ok((key, row)) - } - }) - .try_collect::>() - .await?; - - let column_validation = - ColumnValidation::SpecifiedColumns(Rc::from(column_defs), columns_to_update); - validate_unique( - &storage, - &table_name, - column_validation, - rows.iter().map(|r| &r.1), - ) - .await?; - - Ok(rows) - }); - let num_rows = rows.len(); - storage - .update_data(rows) - .await - .map(|(storage, _)| (storage, Payload::Update(num_rows))) - } + } => update(storages[0].1, table_name, selection, assignments).await, Statement::Delete { table_name, selection, } => { - let keys = try_block!(storage, { - let table_name = get_name(&table_name)?; - let columns = Rc::from(fetch_columns(&storage, table_name).await?); - let filter = Filter::new(&storage, selection.as_ref(), None, None); - - fetch(&storage, table_name, columns, filter) - .await? - .map_ok(|(_, key, _)| key) - .try_collect::>() - .await - }); + let table_name = get_name(&table_name)?; + let Schema { column_defs, .. } = storages[0] + .1 + .fetch_schema(table_name) + .await? + .ok_or(ExecuteError::TableNotExists)?; + + let columns = column_defs + .clone() + .into_iter() + .map(|column_def| { + let ColumnDef { name, .. } = column_def; + ComplexColumnName::of_name(name.value) + }) + .collect(); + let filter = selection + .clone() + .map(|selection| PlannedRecipe::new(MetaRecipe::new(selection)?, &columns)) + .unwrap_or(Ok(PlannedRecipe::TRUE))?; + + let keys = storages[0] + .1 + .scan_data(table_name) + .await? + .filter_map(|row_result| { + let (key, row) = match row_result { + Ok(keyed_row) => keyed_row, + Err(error) => return Some(Err(error)), + }; + + let row = row.0; + + let confirm_constraint = filter.confirm_constraint(&row.clone()); + match confirm_constraint { + Ok(true) => Some(Ok(key)), + Ok(false) => None, + Err(error) => Some(Err(error)), + } + }) + .collect::>>()?; let num_keys = keys.len(); - storage + storages[0] + .1 .delete_data(keys) .await - .map(|(storage, _)| (storage, Payload::Delete(num_keys))) + .map(|_| Payload::Delete(num_keys)) } - //- Selection - Statement::Query(query) => { - let (labels, rows) = try_into!(storage, { select(&storage, query).await }); - - Ok((storage, Payload::Select { labels, rows })) + Statement::Query(query_value) => { + let result = query(&storages, *query_value.clone()).await?; + let (labels, rows) = result; + let rows = rows.into_iter().map(Row).collect(); // I don't like this. TODO + let payload = Payload::Select { labels, rows }; + Ok(payload) } - _ => Err((storage, ExecuteError::QueryNotSupported.into())), + _ => Err(ExecuteError::QueryNotSupported.into()), } } - -async fn select( - storage: &dyn Store, - query: &AstQuery, -) -> Result<(Vec, Vec)> { - let (labels, rows) = select_with_labels(storage, query, None, true).await?; - let rows = rows.try_collect::>().await?; - - Ok((labels, rows)) -} diff --git a/src/executor/fetch.rs b/src/executor/fetch.rs index 7dc73fe8..bde4e33f 100644 --- a/src/executor/fetch.rs +++ b/src/executor/fetch.rs @@ -1,17 +1,9 @@ -use boolinator::Boolinator; -use futures::stream::{self, TryStream, TryStreamExt}; -use serde::Serialize; -use std::fmt::Debug; -use std::rc::Rc; -use thiserror::Error as ThisError; - -use sqlparser::ast::{ColumnDef, Ident}; - -use super::context::BlendContext; -use super::filter::Filter; -use crate::data::Row; -use crate::result::{Error, Result}; -use crate::store::Store; +use { + crate::{result::Result, StorageInner}, + serde::Serialize, + sqlparser::ast::{ColumnDef, Ident}, + thiserror::Error as ThisError, +}; #[derive(ThisError, Serialize, Debug, PartialEq)] pub enum FetchError { @@ -19,10 +11,7 @@ pub enum FetchError { TableNotFound(String), } -pub async fn fetch_columns( - storage: &dyn Store, - table_name: &str, -) -> Result> { +pub async fn fetch_columns(storage: &StorageInner, table_name: &str) -> Result> { Ok(storage .fetch_schema(table_name) .await? @@ -32,34 +21,3 @@ pub async fn fetch_columns( .map(|ColumnDef { name, .. }| name) .collect::>()) } - -pub async fn fetch<'a, T: 'static + Debug>( - storage: &dyn Store, - table_name: &'a str, - columns: Rc<[Ident]>, - filter: Filter<'a, T>, -) -> Result, T, Row), Error = Error> + 'a> { - let filter = Rc::new(filter); - - let rows = storage - .scan_data(table_name) - .await - .map(stream::iter)? - .try_filter_map(move |(key, row)| { - let columns = Rc::clone(&columns); - let filter = Rc::clone(&filter); - - let context = Rc::new(BlendContext::new(table_name, columns, Some(row), None)); - - // TODO: remove two unwrap() uses. - async move { - filter.check(Rc::clone(&context)).await.map(|pass| { - let context = Rc::try_unwrap(context).unwrap(); - - pass.as_some((context.columns, key, context.row.unwrap())) - }) - } - }); - - Ok(rows) -} diff --git a/src/executor/filter.rs b/src/executor/filter.rs deleted file mode 100644 index d508fb31..00000000 --- a/src/executor/filter.rs +++ /dev/null @@ -1,190 +0,0 @@ -use async_recursion::async_recursion; -use boolinator::Boolinator; -use futures::stream::{self, StreamExt, TryStreamExt}; -use im_rc::HashMap; -use serde::Serialize; -use std::fmt::Debug; -use std::rc::Rc; -use thiserror::Error; - -use sqlparser::ast::{BinaryOperator, Expr, Function, UnaryOperator}; - -use super::context::{BlendContext, FilterContext}; -use super::evaluate::{evaluate, Evaluated}; -use super::select::select; -use crate::data::Value; -use crate::result::Result; -use crate::store::Store; - -#[derive(Error, Serialize, Debug, PartialEq)] -pub enum FilterError { - #[error("unimplemented")] - Unimplemented, -} - -pub struct Filter<'a, T: 'static + Debug> { - storage: &'a dyn Store, - where_clause: Option<&'a Expr>, - context: Option>>, - aggregated: Option>>, -} - -impl<'a, T: 'static + Debug> Filter<'a, T> { - pub fn new( - storage: &'a dyn Store, - where_clause: Option<&'a Expr>, - context: Option>>, - aggregated: Option>>, - ) -> Self { - Self { - storage, - where_clause, - context, - aggregated, - } - } - - pub async fn check(&self, blend_context: Rc>) -> Result { - match self.where_clause { - Some(expr) => { - let context = self.context.as_ref().map(Rc::clone); - let context = FilterContext::concat(context, Some(blend_context)); - let context = Some(context).map(Rc::new); - let aggregated = self.aggregated.as_ref().map(Rc::clone); - - check_expr(self.storage, context, aggregated, expr).await - } - None => Ok(true), - } - } -} - -#[async_recursion(?Send)] -pub async fn check_expr( - storage: &dyn Store, - filter_context: Option>>, - aggregated: Option>>, - expr: &Expr, -) -> Result { - let evaluate = |expr: &'async_recursion Expr| { - let filter_context = filter_context.as_ref().map(Rc::clone); - let aggregated = aggregated.as_ref().map(Rc::clone); - - evaluate(storage, filter_context, aggregated, expr, false) - }; - let check = |expr| { - let filter_context = filter_context.as_ref().map(Rc::clone); - let aggregated = aggregated.as_ref().map(Rc::clone); - - check_expr(storage, filter_context, aggregated, expr) - }; - - match expr { - Expr::BinaryOp { op, left, right } => { - let zip_evaluate = || async move { - let l = evaluate(left).await?; - let r = evaluate(right).await?; - - Ok((l, r)) - }; - let zip_check = || async move { - let l = check(left).await?; - let r = check(right).await?; - - Ok((l, r)) - }; - - match op { - BinaryOperator::Eq => zip_evaluate().await.map(|(l, r)| l == r), - BinaryOperator::NotEq => zip_evaluate().await.map(|(l, r)| l != r), - BinaryOperator::And => zip_check().await.map(|(l, r)| l && r), - BinaryOperator::Or => zip_check().await.map(|(l, r)| l || r), - BinaryOperator::Lt => zip_evaluate().await.map(|(l, r)| l < r), - BinaryOperator::LtEq => zip_evaluate().await.map(|(l, r)| l <= r), - BinaryOperator::Gt => zip_evaluate().await.map(|(l, r)| l > r), - BinaryOperator::GtEq => zip_evaluate().await.map(|(l, r)| l >= r), - _ => Err(FilterError::Unimplemented.into()), - } - } - Expr::UnaryOp { - op: UnaryOperator::Not, - expr, - } => check(&expr).await.map(|v| !v), - Expr::Nested(expr) => check(&expr).await, - Expr::InList { - expr, - list, - negated, - } => { - let negated = *negated; - let target = evaluate(expr).await?; - - stream::iter(list.iter()) - .filter_map(|expr| { - let target = ⌖ - - async move { - evaluate(expr).await.map_or_else( - |error| Some(Err(error)), - |evaluated| (target == &evaluated).as_some(Ok(!negated)), - ) - } - }) - .take(1) - .collect::>() - .await - .into_iter() - .next() - .unwrap_or(Ok(negated)) - } - Expr::InSubquery { - expr, - subquery, - negated, - } => { - let target = evaluate(expr).await?; - - select(storage, &subquery, filter_context) - .await? - .try_filter_map(|row| { - let target = ⌖ - - async move { - let value = row.take_first_value()?; - - (target == &Evaluated::from(&value)) - .as_some(Ok(!negated)) - .transpose() - } - }) - .take(1) - .collect::>() - .await - .into_iter() - .next() - .unwrap_or(Ok(*negated)) - } - Expr::Between { - expr, - negated, - low, - high, - } => { - let negated = *negated; - let target = evaluate(expr).await?; - - Ok(negated ^ (evaluate(low).await? <= target && target <= evaluate(high).await?)) - } - Expr::Exists(query) => Ok(select(storage, query, filter_context) - .await? - .into_stream() - .take(1) - .try_collect::>() - .await? - .get(0) - .is_some()), - Expr::IsNull(expr) => Ok(!evaluate(expr).await?.is_some()), - Expr::IsNotNull(expr) => Ok(evaluate(expr).await?.is_some()), - _ => Err(FilterError::Unimplemented.into()), - } -} diff --git a/src/executor/join.rs b/src/executor/join.rs deleted file mode 100644 index 3b9edb95..00000000 --- a/src/executor/join.rs +++ /dev/null @@ -1,201 +0,0 @@ -use boolinator::Boolinator; -use futures::stream::{self, once, StreamExt, TryStream, TryStreamExt}; -use serde::Serialize; -use std::fmt::Debug; -use std::pin::Pin; -use std::rc::Rc; -use thiserror::Error as ThisError; - -use sqlparser::ast::{Ident, Join as AstJoin, JoinConstraint, JoinOperator}; - -use super::context::{BlendContext, FilterContext}; -use super::filter::Filter; -use crate::data::Table; -use crate::result::{Error, Result}; -use crate::store::Store; -use crate::utils::OrStream; - -#[derive(ThisError, Serialize, Debug, PartialEq)] -pub enum JoinError { - #[error("unimplemented! join not supported")] - JoinTypeNotSupported, - - #[error("unimplemented! using on join not supported")] - UsingOnJoinNotSupported, - - #[error("unimplemented! natural on join not supported")] - NaturalOnJoinNotSupported, - - #[error("umimplemented! failed to get table name")] - FailedToGetTableName, -} - -pub struct Join<'a, T: 'static + Debug> { - storage: &'a dyn Store, - join_clauses: &'a [AstJoin], - filter_context: Option>>, -} - -type JoinItem<'a> = Rc>; -type Joined<'a> = - Pin, Error = Error, Item = Result>> + 'a>>; - -impl<'a, T: 'static + Debug> Join<'a, T> { - pub fn new( - storage: &'a dyn Store, - join_clauses: &'a [AstJoin], - filter_context: Option>>, - ) -> Self { - Self { - storage, - join_clauses, - filter_context, - } - } - - pub async fn apply( - &self, - init_context: Result>, - join_columns: Rc<[Rc<[Ident]>]>, - ) -> Result> { - let init_context = init_context.map(Rc::new); - let init_rows: Joined<'a> = Box::pin(stream::once(async { init_context })); - let filter_context = self.filter_context.as_ref().map(Rc::clone); - - let joins = self - .join_clauses - .iter() - .enumerate() - .map(move |(i, join_clause)| { - let join_columns = Rc::clone(&join_columns[i]); - - Ok::<_, Error>((join_clause, join_columns)) - }); - - let rows = stream::iter(joins) - .try_fold(init_rows, |rows, (join_clause, join_columns)| { - let storage = self.storage; - let filter_context = filter_context.as_ref().map(Rc::clone); - - async move { - let rows = rows - .map(Ok) - .and_then(move |blend_context| { - let columns = Rc::clone(&join_columns); - let filter_context = filter_context.as_ref().map(Rc::clone); - - join(storage, filter_context, join_clause, columns, blend_context) - }) - .try_flatten(); - - Ok::, _>(Box::pin(rows)) - } - }) - .await?; - - Ok(Box::pin(rows)) - } -} - -async fn join<'a, T: 'static + Debug>( - storage: &'a dyn Store, - filter_context: Option>>, - ast_join: &'a AstJoin, - columns: Rc<[Ident]>, - blend_context: Result>>, -) -> Result> { - let AstJoin { - relation, - join_operator, - } = ast_join; - let table = Table::new(relation)?; - let table_name = table.get_name(); - let table_alias = table.get_alias(); - - let blend_context = blend_context?; - let init_context = Rc::new(BlendContext::new( - table.get_alias(), - Rc::clone(&columns), - None, - Some(Rc::clone(&blend_context)), - )); - - let fetch_joined = |constraint: &'a JoinConstraint| { - fetch_joined( - storage, - table_name, - table_alias, - Rc::clone(&columns), - filter_context, - blend_context, - constraint, - ) - }; - - match join_operator { - JoinOperator::Inner(constraint) => fetch_joined(constraint).await.map(|rows| { - let rows: Joined<'a> = Box::pin(rows); - - rows - }), - JoinOperator::LeftOuter(constraint) => fetch_joined(constraint).await.map(|rows| { - let init_rows = once(async { Ok(init_context) }); - let rows: Joined<'a> = Box::pin(OrStream::new(rows, init_rows)); - - rows - }), - _ => Err(JoinError::JoinTypeNotSupported.into()), - } -} - -async fn fetch_joined<'a, T: 'static + Debug>( - storage: &'a dyn Store, - table_name: &'a str, - table_alias: &'a str, - columns: Rc<[Ident]>, - filter_context: Option>>, - blend_context: Rc>, - constraint: &'a JoinConstraint, -) -> Result, Error = Error, Item = Result>> + 'a> { - let where_clause = match constraint { - JoinConstraint::On(where_clause) => Some(where_clause), - JoinConstraint::Using(_) => { - return Err(JoinError::UsingOnJoinNotSupported.into()); - } - JoinConstraint::Natural => { - return Err(JoinError::NaturalOnJoinNotSupported.into()); - } - JoinConstraint::None => None, - }; - - let rows = storage - .scan_data(table_name) - .await - .map(stream::iter)? - .try_filter_map(move |(_, row)| { - let filter_context = FilterContext::concat( - filter_context.as_ref().map(Rc::clone), - Some(&blend_context).map(Rc::clone), - ); - let filter_context = Some(filter_context).map(Rc::new); - let blend_context = Rc::clone(&blend_context); - let columns = Rc::clone(&columns); - - async move { - let filter = Filter::new(storage, where_clause, filter_context, None); - let context = Rc::new(BlendContext::new( - table_alias, - Rc::clone(&columns), - Some(row), - Some(&blend_context).map(Rc::clone), - )); - - filter - .check(Rc::clone(&context)) - .await - .map(|pass| pass.as_some(context)) - } - }); - - Ok(rows) -} diff --git a/src/executor/limit.rs b/src/executor/limit.rs deleted file mode 100644 index 19654e07..00000000 --- a/src/executor/limit.rs +++ /dev/null @@ -1,47 +0,0 @@ -use serde::Serialize; -use std::fmt::Debug; -use thiserror::Error; - -use sqlparser::ast::{Expr, Offset, Value as Literal}; - -use crate::result::Result; - -#[derive(Error, Serialize, Debug, PartialEq)] -pub enum LimitError { - #[error("Unreachable")] - Unreachable, -} - -pub struct Limit { - limit: Option, - offset: Option, -} - -impl Limit { - pub fn new(limit: Option<&Expr>, offset: Option<&Offset>) -> Result { - let parse = |expr: &Expr| -> Result { - match expr { - Expr::Value(Literal::Number(v, false)) => { - v.parse().map_err(|_| LimitError::Unreachable.into()) - } - _ => Err(LimitError::Unreachable.into()), - } - }; - - let limit = limit.map(|value| parse(value)).transpose()?; - let offset = offset - .map(|Offset { value, .. }| parse(value)) - .transpose()?; - - Ok(Self { limit, offset }) - } - - pub fn check(&self, i: usize) -> bool { - match (self.offset, self.limit) { - (Some(offset), Some(limit)) => i >= offset && i < offset + limit, - (Some(offset), None) => i >= offset, - (None, Some(limit)) => i < limit, - (None, None) => true, - } - } -} diff --git a/src/executor/mod.rs b/src/executor/mod.rs index bca25fc7..1f68cce5 100644 --- a/src/executor/mod.rs +++ b/src/executor/mod.rs @@ -1,29 +1,18 @@ -mod aggregate; -mod alter; -mod blend; -mod column_options; -mod context; -mod evaluate; +mod alter_row; +mod alter_table; mod execute; mod fetch; -mod filter; -mod join; -mod limit; -mod select; +mod query; +mod recipe; +mod types; mod update; -mod validate; pub use { - aggregate::{AggregateError, GroupKey}, - alter::AlterError, - blend::BlendError, - evaluate::{evaluate, EvaluateError, Evaluated}, + alter_row::ValidateError, + alter_table::AlterError, execute::{execute, ExecuteError, Payload}, fetch::FetchError, - filter::FilterError, - join::JoinError, - limit::LimitError, - select::SelectError, + query::{JoinError, ManualError, PlanError, QueryError, SelectError}, + recipe::*, update::UpdateError, - validate::{UniqueKey, ValidateError}, }; diff --git a/src/executor/query/mod.rs b/src/executor/query/mod.rs new file mode 100644 index 00000000..1502d8a7 --- /dev/null +++ b/src/executor/query/mod.rs @@ -0,0 +1,117 @@ +mod select; + +pub use select::{join::*, ManualError, PlanError, SelectError}; + +use { + crate::{ + executor::types::LabelsAndRows, macros::warning, result::Result, Cast, Recipe, + RecipeUtilities, StorageInner, Value, + }, + select::select, + serde::Serialize, + sqlparser::ast::{Query, SetExpr}, + thiserror::Error as ThisError, +}; + +const ENSURE_SIZE: bool = true; + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum QueryError { + #[error("query not supported")] + QueryNotSupported, + #[error("values does not support columns, aggregates or subqueries")] + MissingComponentsForValues, + #[error("limit does not support columns, aggregates or subqueries")] + MissingComponentsForLimit, + #[error("offset does not support columns, aggregates or subqueries")] + MissingComponentsForOffset, + #[error("expected values but found none")] + NoValues, +} + +pub async fn query( + storages: &Vec<(String, &mut StorageInner)>, + query: Query, +) -> Result { + let Query { + body, + order_by, + limit, + offset, + // TODO (below) + fetch: _, + with: _, + } = query; + let limit: Option = limit + .map(|expression| { + Recipe::new_without_meta(expression)? + .simplify_by_basic()? + .confirm_or_err(QueryError::MissingComponentsForLimit.into())? + .cast() + }) + .transpose()?; + let offset: Option = offset + .map(|offset| { + Recipe::new_without_meta(offset.value)? + .simplify_by_basic()? + .confirm_or_err(QueryError::MissingComponentsForOffset.into())? + .cast() + }) + .transpose()?; + let (mut labels, mut rows) = match body { + SetExpr::Select(query) => { + let (labels, rows) = select(storages, *query, order_by).await?; + + Ok((labels, rows)) + } + SetExpr::Values(values) => { + if !order_by.is_empty() { + warning!("VALUES does not currently support ordering"); + } + let values = values.0; + values + .into_iter() + .map(|values_row| { + values_row + .into_iter() + .map(|cell| { + Recipe::new_without_meta(cell)? + .simplify_by_basic()? + .confirm_or_err(QueryError::MissingComponentsForValues.into()) + }) + .collect::>>() + }) + .collect::>>>() + .map(|values| { + ( + (0..values.get(0).map(|first_row| first_row.len()).unwrap_or(0)) + .map(|index| format!("unnamed_{}", index)) + .collect(), + values, + ) + }) + } + _ => Err(QueryError::QueryNotSupported.into()), // TODO: Other queries + }?; + + offset.map(|offset| rows.drain(0..offset)); + limit.map(|limit| rows.truncate(limit)); + if ENSURE_SIZE { + let row_width = rows + .iter() + .map(|values_row| values_row.len()) + .max() + .unwrap_or(0); + if row_width > 0 { + rows = rows + .into_iter() + .map(|mut row| { + row.resize(row_width, Value::Null); + row + }) + .collect(); + labels.resize(row_width, String::new()) + }; + } + Ok((labels, rows)) +} diff --git a/src/executor/query/select/join/execute.rs b/src/executor/query/select/join/execute.rs new file mode 100644 index 00000000..82bf81a2 --- /dev/null +++ b/src/executor/query/select/join/execute.rs @@ -0,0 +1,126 @@ +use { + super::{JoinError, JoinMethod, JoinPlan, JoinType}, + crate::{ + executor::types::{ComplexColumnName, Row}, + Ingredient, MetaRecipe, Method, PlannedRecipe, Recipe, Result, StorageInner, Value, + }, +}; + +#[derive(Debug)] +pub struct JoinExecute { + pub database: String, + pub table: String, + pub method: JoinMethod, + pub join_type: JoinType, +} + +impl JoinExecute { + pub fn new(plan: JoinPlan, plane_columns: &Vec) -> Result { + let JoinPlan { + database, + table, + join_type, + constraint, + columns, + .. + } = plan; + let method = decide_method(constraint, columns, plane_columns)?; + Ok(Self { + database, + table, + method, + join_type, + }) + } + pub fn set_first_table(&mut self) { + self.method = JoinMethod::FirstTable; + } + pub async fn get_rows<'a>(&self, storage: &StorageInner) -> Result> { + storage + .scan_data(self.table.as_str()) + .await? + .map(|result| result.map(|(_, row)| row.0)) + .collect::>>() + } + pub async fn execute<'a>( + self, + storages: &Vec<(String, &mut StorageInner)>, + plane_rows: Vec, + ) -> Result> { + let storage = storages + .into_iter() + .find_map(|(name, storage)| { + if name == &self.database { + Some(&**storage) + } else { + None + } + }) + .or(storages.get(0).map(|(_, storage)| &**storage)) + .ok_or(JoinError::Unreachable)?; + + let rows = self.get_rows(storage).await?; + self.method.run(&self.join_type, plane_rows, rows) + } +} + +fn decide_method( + constraint: MetaRecipe, + self_columns: Vec, + plane_columns: &Vec, +) -> Result { + Ok(match &constraint.recipe { + Recipe::Ingredient(Ingredient::Value(Value::Bool(true))) => JoinMethod::All, + Recipe::Method(method) => match **method { + Method::BinaryOperation( + operator, + Recipe::Ingredient(Ingredient::Column(index_l)), + Recipe::Ingredient(Ingredient::Column(index_r)), + ) if operator == Value::eq => { + // TODO: Be more strict, ensure that one column is from plane, and another from self. + let column_l = constraint + .meta + .columns + .get(index_l) + .ok_or(JoinError::Unreachable)?; + let column_r = constraint + .meta + .columns + .get(index_r) + .ok_or(JoinError::Unreachable)?; + + let (self_index, plane_index) = if let Some(self_index) = + self_columns.iter().position(|column| column == column_l) + { + let plane_index = plane_columns + .iter() + .position(|column| column == column_r) + .ok_or(JoinError::Unreachable)?; + (self_index, plane_index) + } else { + let self_index = self_columns + .iter() + .position(|column| column == column_r) + .ok_or(JoinError::Unreachable)?; + let plane_index = plane_columns + .iter() + .position(|column| column == column_l) + .ok_or(JoinError::Unreachable)?; + (self_index, plane_index) + }; + + JoinMethod::ColumnEqColumn { + plane_trust_ordered: false, + plane_index, + self_trust_ordered: false, + self_index, + } + } + // TODO: Methods for: + // (plan)Column = (other)Column AND (plan)Column = (other or otherother)Column + // (plan)Column = (other)Column OR (plan)Column = (other or otherother)Column + _ => JoinMethod::General(PlannedRecipe::new(constraint.clone(), plane_columns)?), + }, + _ => JoinMethod::Ignore, + }) +} diff --git a/src/executor/query/select/join/manual.rs b/src/executor/query/select/join/manual.rs new file mode 100644 index 00000000..f816cbeb --- /dev/null +++ b/src/executor/query/select/join/manual.rs @@ -0,0 +1,76 @@ +use { + super::{JoinError, JoinType}, + crate::{ + executor::{types::ComplexTableName, MetaRecipe}, + Result, + }, + sqlparser::ast::{Join as AstJoin, JoinConstraint, JoinOperator, TableFactor}, +}; + +#[derive(Debug, Clone)] +pub struct JoinManual { + pub table: ComplexTableName, + pub constraint: MetaRecipe, + pub join_type: JoinType, +} + +impl JoinManual { + pub fn new(join: AstJoin) -> Result { + let table = Self::table_identity(join.relation)?; + let (join_type, constraint) = Self::convert_join(join.join_operator)?; + // println!("(join/manual.rs) Constraint: {:?}", constraint); + Ok(Self { + table, + join_type, + constraint, + }) + } + pub fn new_implicit_join(table: TableFactor) -> Result { + let table = Self::table_identity(table)?; + let (join_type, constraint) = (JoinType::CrossJoin, MetaRecipe::TRUE); + Ok(Self { + table, + join_type, + constraint, + }) + } + fn convert_join(from: JoinOperator) -> Result<(JoinType, MetaRecipe)> { + let (join_type, constraint) = match from { + JoinOperator::Inner(constraint) => (JoinType::Inner, Some(constraint)), + JoinOperator::LeftOuter(constraint) => (JoinType::Left, Some(constraint)), + JoinOperator::RightOuter(constraint) => (JoinType::Right, Some(constraint)), + JoinOperator::FullOuter(constraint) => (JoinType::Full, Some(constraint)), + JoinOperator::CrossJoin => (JoinType::CrossJoin, None), + _ => return Err(JoinError::UnimplementedJoinType.into()), + }; + let constraint = match constraint { + Some(JoinConstraint::On(constraint)) => MetaRecipe::new(constraint)?, + Some(JoinConstraint::None) | None => MetaRecipe::TRUE, + _ => return Err(JoinError::UnimplementedJoinConstaint.into()), + }; + Ok((join_type, constraint)) + } + pub fn table_identity(table: TableFactor) -> Result { + match table { + TableFactor::Table { name, alias, .. } => { + let name_parts = name.0.len(); + if name_parts > 2 || name_parts < 1 { + return Err(JoinError::UnimplementedNumberOfComponents.into()); + } + let database = if name_parts == 2 { + name.0.get(0).unwrap().value.clone() + } else { + String::new() + }; + let name = name.0.last().unwrap().value.clone(); + let alias = alias.map(|alias| alias.name.value); + Ok(ComplexTableName { + database, + name, + alias, + }) + } + _ => Err(JoinError::UnimplementedTableType.into()), + } + } +} diff --git a/src/executor/query/select/join/method.rs b/src/executor/query/select/join/method.rs new file mode 100644 index 00000000..72f18d2b --- /dev/null +++ b/src/executor/query/select/join/method.rs @@ -0,0 +1,303 @@ +use { + super::JoinType, + crate::{ + executor::{types::Row, PlannedRecipe}, + macros::try_option, + JoinError, NullOrd, Result, Value, + }, + rayon::prelude::*, + std::{cmp::Ordering, fmt::Debug}, +}; + +macro_rules! unwrap_or_break { + ($unwrap: expr) => { + match $unwrap { + Some(value) => value, + None => { + break; + } + }; + }; +} + +#[derive(Debug)] +pub enum JoinMethod { + General(PlannedRecipe), + ColumnEqColumn { + plane_index: usize, + plane_trust_ordered: bool, + self_index: usize, + self_trust_ordered: bool, + }, + All, + FirstTable, + Ignore, +} + +impl JoinMethod { + pub fn run( + self, + join: &JoinType, + mut plane_rows: Vec, + mut self_rows: Vec, + ) -> Result> { + // Very crucuial to have performant, needs *a lot* of optimisation. + Ok(match self { + JoinMethod::Ignore => plane_rows, + JoinMethod::FirstTable => self_rows, + JoinMethod::All => self_rows + .into_iter() + .fold(vec![], |mut result_rows, self_row| { + let joined_rows = plane_rows.clone().into_iter().map(|mut plane_row| { + plane_row.extend(self_row.clone()); + plane_row + }); + result_rows.extend(joined_rows); + result_rows + }), + JoinMethod::General(recipe) => { + let left_width = plane_rows.get(0).map(|row| row.len()).unwrap_or(0); + let right_width = self_rows.get(0).map(|row| row.len()).unwrap_or(0); + let unfolded_rows: Vec, Vec)>> = plane_rows + .into_par_iter() + .map(|left_row| { + let inner_rows = + self_rows + .iter() + .enumerate() + .filter_map(|(index, right_row)| { + if try_option!( + recipe.confirm_join_constraint(&left_row, &right_row) + ) { + Some(Ok(( + index, + join_parts(left_row.clone(), right_row.clone()), + ))) + } else { + None + } + }) + .collect::>>()?; + Ok(if inner_rows.is_empty() && join.includes_left() { + ( + vec![], + vec![join_parts(left_row.clone(), vec![Value::Null; right_width])], + ) + } else { + inner_rows.into_iter().unzip() + }) + }) + .collect::, Vec)>>>(); + let (mut used_right_indexes, mut rows): (Vec, Vec) = unfolded_rows + .into_iter() + .collect::, Vec)>>>()? + .into_iter() + .reduce( + |mut all: (Vec, Vec), set: (Vec, Vec)| { + all.0.extend(set.0); + all.1.extend(set.1); + all + }, + ) + .unwrap_or((vec![], vec![])); + used_right_indexes.sort_unstable(); + used_right_indexes.dedup(); + self_rows.iter().enumerate().for_each(|(index, row)| { + if !used_right_indexes.iter().any(|used| used == &index) + && join.includes_right() + { + rows.push(join_parts(vec![Value::Null; left_width], row.clone())) + } + }); + rows + } + JoinMethod::ColumnEqColumn { + plane_index, + plane_trust_ordered, + self_index, + self_trust_ordered, + } => { + if !plane_trust_ordered { + plane_rows.sort_unstable_by(|row_l, row_r| { + row_l + .get(plane_index) + .map(|row_l| row_r.get(plane_index).map(|row_r| row_l.null_cmp(&row_r))) + .flatten() + .flatten() + .unwrap_or(Ordering::Equal) + }); + } + + // partition + let mut left_partitions = plane_rows + .into_iter() + .fold( + vec![], + |mut partitions: Vec<(Value, Vec)>, row: Row| { + let value = row.get(plane_index).unwrap().clone(); // TODO: Handle + if let Some(last) = partitions.last_mut() { + if last.0 == value { + last.1.push(row); + } else { + partitions.push((value, vec![row])); + } + partitions + } else { + vec![(value, vec![row])] + } + }, + ) + .into_iter() + .peekable(); + + if !self_trust_ordered { + self_rows.sort_unstable_by(|row_l, row_r| { + row_l + .get(self_index) + .map(|row_l| row_r.get(self_index).map(|row_r| row_l.null_cmp(&row_r))) + .flatten() + .flatten() + .unwrap_or(Ordering::Equal) + }); + } + + // partition + let mut right_partitions = self_rows + .into_iter() + .fold( + vec![], + |mut partitions: Vec<(Value, Vec)>, row: Row| { + let value = row.get(self_index).unwrap().clone(); // TODO: Handle + if let Some(last) = partitions.last_mut() { + if last.0 == value { + last.1.push(row); + } else { + partitions.push((value, vec![row])); + } + partitions + } else { + vec![(value, vec![row])] + } + }, + ) + .into_iter() + .peekable(); + + // For later + // Trust that rows have same len + let left_len = left_partitions + .peek() + .map(|left_partition| left_partition.1.get(0).map(|row| row.len())) + .flatten() + .unwrap_or(0); + let right_len = right_partitions + .peek() + .map(|right_partition| right_partition.1.get(0).map(|row| row.len())) + .flatten() + .unwrap_or(0); + + let mut left_results = vec![]; + let mut inner_results = vec![]; + let mut right_results = vec![]; + + loop { + match unwrap_or_break!(left_partitions.peek()) + .0 + .null_cmp(&unwrap_or_break!(right_partitions.peek()).0) + { + Some(Ordering::Less) => { + left_results + .push(left_partitions.next().ok_or(JoinError::Unreachable)?); + } + Some(Ordering::Equal) => { + inner_results.push(( + left_partitions.next().ok_or(JoinError::Unreachable)?, + right_partitions.next().ok_or(JoinError::Unreachable)?, + )); + } + None => { + left_results + .push(left_partitions.next().ok_or(JoinError::Unreachable)?); + right_results + .push(right_partitions.next().ok_or(JoinError::Unreachable)?); + } + Some(Ordering::Greater) => { + right_results + .push(right_partitions.next().ok_or(JoinError::Unreachable)?); + } + } + } + // In case any remain + left_results.extend(left_partitions); + right_results.extend(right_partitions); + + let left_rows = left_results + .into_iter() + .map(|(_, left_rows)| { + left_rows + .into_iter() + .map(|left| join_parts(left, vec![Value::Null; right_len])) + .collect::>() + }) + .reduce(|mut all, set| { + all.extend(set); + all + }) + .unwrap_or(vec![]); + + let mut inner_rows = inner_results + .into_par_iter() + .map(|((_, left_rows), (_, right_rows))| { + left_rows + .into_iter() + .map(|left| { + right_rows + .clone() + .into_iter() + .map(|right| join_parts(left.clone(), right)) + .collect() + }) + .reduce(|mut all: Vec, set| { + all.extend(set); + all + }) + .unwrap_or(vec![]) + }) + .reduce( + || vec![], + |mut all: Vec, set| { + all.extend(set); + all + }, + ); + + let right_rows = right_results + .into_iter() + .map(|(_, right_rows)| { + right_rows + .into_iter() + .map(|right| join_parts(vec![Value::Null; left_len], right)) + .collect::>() + }) + .reduce(|mut all, set| { + all.extend(set); + all + }) + .unwrap_or(vec![]); + + if join.includes_left() { + inner_rows.extend(left_rows) + }; + if join.includes_right() { + inner_rows.extend(right_rows) + }; + inner_rows + } + }) + } +} + +fn join_parts(mut left: Vec, right: Vec) -> Vec { + left.extend(right); + left +} diff --git a/src/executor/query/select/join/mod.rs b/src/executor/query/select/join/mod.rs new file mode 100644 index 00000000..802e079d --- /dev/null +++ b/src/executor/query/select/join/mod.rs @@ -0,0 +1,49 @@ +mod execute; +mod manual; +mod method; +mod plan; + +pub use {execute::JoinExecute, manual::JoinManual, method::JoinMethod, plan::JoinPlan}; + +use { + crate::executor::types::ComplexTableName, serde::Serialize, std::fmt::Debug, + thiserror::Error as ThisError, +}; + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum JoinError { + #[error("table '{0:?}' could not be found")] + TableNotFound(ComplexTableName), + + #[error("join type not yet implemented")] + UnimplementedJoinType, + #[error("join constraint not yet implemented")] + UnimplementedJoinConstaint, + #[error("table type not yet implemented")] + UnimplementedTableType, + #[error("amount of components in identifier not yet supported")] + UnimplementedNumberOfComponents, + + #[error("this should be impossible, please report")] + UnreachableCellNotFound, + #[error("this should be impossible, please report")] + Unreachable, +} + +#[derive(Ord, Eq, PartialEq, PartialOrd, Debug, Clone)] +pub enum JoinType { + CrossJoin, // All join: NO FILTER + Inner, // Reduces rows so go first ideally -- has bugs for now + Left, + Right, + Full, +} + +impl JoinType { + pub fn includes_left(&self) -> bool { + matches!(self, JoinType::Left | JoinType::Full) + } + pub fn includes_right(&self) -> bool { + matches!(self, JoinType::Right | JoinType::Full) + } +} diff --git a/src/executor/query/select/join/plan.rs b/src/executor/query/select/join/plan.rs new file mode 100644 index 00000000..9fc0eefc --- /dev/null +++ b/src/executor/query/select/join/plan.rs @@ -0,0 +1,110 @@ +use { + super::{JoinManual, JoinType}, + crate::{ + executor::{ + fetch::fetch_columns, + types::{ComplexColumnName, ComplexTableName}, + MetaRecipe, + }, + JoinError, Result, StorageInner, + }, + std::cmp::Ordering, +}; + +#[derive(Debug)] +pub struct JoinPlan { + pub database: String, + pub table: String, + pub columns: Vec, + pub join_type: JoinType, + pub constraint: MetaRecipe, + pub needed_tables: Vec, +} +impl PartialEq for JoinPlan { + fn eq(&self, _other: &Self) -> bool { + false + } +} +impl Eq for JoinPlan {} +impl PartialOrd for JoinPlan { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.join_type.cmp(&other.join_type)) + } +} +impl Ord for JoinPlan { + fn cmp(&self, other: &Self) -> Ordering { + self.join_type.cmp(&other.join_type) + } +} + +impl JoinPlan { + pub async fn new<'a>( + join_manual: JoinManual, + storages: &Vec<(String, &mut StorageInner)>, + ) -> Result { + let JoinManual { + table, + constraint, + join_type, + } = join_manual; + let columns = get_columns(storages, table.clone()).await?; + let ComplexTableName { + database, + name: table, + .. + } = table; + Ok(Self { + database, + table, + join_type, + columns, + constraint, + needed_tables: vec![], + }) + } + pub fn calculate_needed_tables(&mut self, table_columns: &Vec>) { + self.needed_tables = table_columns + .iter() + .enumerate() + .filter_map(|(index, columns)| { + if columns.iter().any(|table_column| { + self.constraint + .meta + .columns + .iter() + .any(|constraint_column| table_column == constraint_column) + }) { + Some(index) + } else { + None + } + }) + .collect() + } +} + +async fn get_columns( + storages: &Vec<(String, &mut StorageInner)>, + table: ComplexTableName, +) -> Result> { + let storage = storages + .into_iter() + .find_map(|(name, storage)| { + if name == &table.database { + Some(&**storage) + } else { + None + } + }) + .or(storages.get(0).map(|(_, storage)| &**storage)) + .ok_or(JoinError::TableNotFound(table.clone()))?; + + Ok(fetch_columns(storage, table.name.as_str()) + .await? + .into_iter() + .map(|name| ComplexColumnName { + table: table.clone(), + name: name.value, + }) + .collect::>()) +} diff --git a/src/executor/query/select/manual/mod.rs b/src/executor/query/select/manual/mod.rs new file mode 100644 index 00000000..e21dc19e --- /dev/null +++ b/src/executor/query/select/manual/mod.rs @@ -0,0 +1,155 @@ +use { + super::join::JoinManual, + crate::{ + executor::{ + types::{Alias, ObjectName}, + MetaRecipe, + }, + Result, + }, + serde::Serialize, + sqlparser::ast::{Expr, Ident, Select, SelectItem as SelectItemAst}, + std::fmt::Debug, + thiserror::Error as ThisError, +}; + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum ManualError { + #[error("subqueries are not yet supported")] + UnimplementedSubquery, + + #[error("this should be impossible, please report")] + Unreachable, +} + +pub struct Manual { + pub joins: Vec, + pub select_items: Vec, + pub constraint: MetaRecipe, + pub group_constraint: MetaRecipe, + pub groups: Vec, +} +pub enum SelectItem { + Recipe(MetaRecipe, Alias), + Wildcard(Option), +} + +impl Manual { + pub fn new(select: Select) -> Result { + let Select { + projection, + from, + selection, + group_by, + having, + // TODO (below) + distinct: _, + top: _, + lateral_views: _, + cluster_by: _, + distribute_by: _, + sort_by: _, + } = select; + + let constraint = selection + .map(|selection| MetaRecipe::new(selection)) + .unwrap_or(Ok(MetaRecipe::TRUE))?; + + let group_constraint = having + .map(|having| MetaRecipe::new(having)) + .unwrap_or(Ok(MetaRecipe::TRUE))?; + + let groups = group_by + .into_iter() + .map(|expression| MetaRecipe::new(expression)) + .collect::>>()?; + + let (select_items, mut subqueries): (Vec, Vec>) = projection + .into_iter() + .map(convert_select_item) + .collect::)>>>()? + .into_iter() + .unzip(); + + subqueries.push(constraint.meta.subqueries.clone()); + + let subqueries = subqueries + .into_iter() + .reduce(|mut all_subqueries, subqueries| { + all_subqueries.extend(subqueries); + all_subqueries + }) + .ok_or(ManualError::Unreachable)?; + // Subqueries TODO + // Issues: + // - Current method can expand plane on multiple match + // - No plane isolation (ambiguous columns because subquery columns and plane columns are treated the same) + if !subqueries.is_empty() { + return Err(ManualError::UnimplementedSubquery.into()); + } + + let /*mut*/ joins = from + .into_iter() + .map(|from| { + let main = JoinManual::new_implicit_join(from.relation)?; + let mut joins = from + .joins + .into_iter() + .map(|join| JoinManual::new(join)) + .collect::>>()?; + joins.push(main); + Ok(joins) + }) + .collect::>>>()? + .into_iter() + .reduce(|mut all_joins, joins| { + all_joins.extend(joins); + all_joins + }) + .ok_or(ManualError::Unreachable)?; + //joins.extend(subqueries); + //let joins = joins; + + Ok(Manual { + joins, + select_items, + constraint, + group_constraint, + groups, + }) + } +} + +fn identifier_into_object_name(identifier: Vec) -> ObjectName { + identifier + .into_iter() + .map(|identifier| identifier.value) + .collect() +} + +fn convert_select_item(select_item: SelectItemAst) -> Result<(SelectItem, Vec)> { + Ok(match select_item { + SelectItemAst::UnnamedExpr(_) | SelectItemAst::ExprWithAlias { .. } => { + let (expression, alias) = match select_item { + SelectItemAst::UnnamedExpr(expression) => { + let alias = if let Expr::Identifier(identifier) = expression.clone() { + Some(identifier.value) + } else { + None + }; + (expression, alias) + } + SelectItemAst::ExprWithAlias { expr, alias } => (expr, Some(alias.value)), + _ => unreachable!(), + }; + let recipe = MetaRecipe::new(expression)?; + let subqueries = recipe.meta.subqueries.clone(); + (SelectItem::Recipe(recipe, alias), subqueries) + } + SelectItemAst::Wildcard => (SelectItem::Wildcard(None), vec![]), + SelectItemAst::QualifiedWildcard(qualifier) => ( + SelectItem::Wildcard(Some(identifier_into_object_name(qualifier.0))), + vec![], + ), + }) +} diff --git a/src/executor/query/select/mod.rs b/src/executor/query/select/mod.rs new file mode 100644 index 00000000..55cddd20 --- /dev/null +++ b/src/executor/query/select/mod.rs @@ -0,0 +1,211 @@ +pub mod join; +mod manual; +mod order; +mod plan; + +pub use { + manual::{Manual, ManualError, SelectItem}, + order::Order, + plan::{Plan, PlanError}, +}; + +use { + crate::{ + executor::{ + types::{LabelsAndRows, Row}, + PlannedRecipe, + }, + macros::try_option, + NullOrd, RecipeUtilities, Result, StorageInner, Value, + }, + futures::stream::{self, StreamExt, TryStreamExt}, + rayon::prelude::*, + serde::Serialize, + sqlparser::ast::{OrderByExpr, Select}, + std::cmp::Ordering, + thiserror::Error as ThisError, +}; + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum SelectError { + #[error("aggregate groups not supported")] + GrouperMayNotContainAggregate, + + #[error("an aggregate was probably used where not allowed")] + FinalSolveFailure, + + #[error("HAVING does not yet support aggregates")] + UnimplementedAggregateHaving, + + #[error("this should be impossible, please report")] + UnreachableFinalSolveFailure, + #[error("this should be impossible, please report")] + Unreachable, +} + +pub async fn select( + storages: &Vec<(String, &mut StorageInner)>, + query: Select, + order_by: Vec, +) -> Result { + let Plan { + joins, + select_items, + constraint, + group_constraint, + groups, + order_by, + labels, + } = Plan::new(storages, query, order_by).await?; + + let rows = stream::iter(joins) + .map(Ok) + .try_fold(vec![], |rows, join| async { + join.execute(storages, rows).await + }) + .await?; + + let rows = order_by.execute(rows)?; // TODO: This should be done after filtering + + let selected_rows = rows + .iter() + .filter_map(|row| match constraint.confirm_constraint(row) { + Ok(true) => Some( + select_items + .iter() + .map(|selection| selection.clone().simplify_by_row(row)) + .collect::>>() + .map(|selection| (selection, row.clone())), + ), + Ok(false) => None, + Err(error) => Some(Err(error)), + }) + .collect::, Row)>>>()?; + let do_group = !groups.is_empty() + || select_items + .iter() + .any(|select_item| !select_item.aggregates.is_empty()); + + let final_rows = if do_group { + let groups = if groups.is_empty() { + vec![PlannedRecipe::TRUE] + } else { + groups + }; + let mut ungrouped_groupers = selected_rows + .into_par_iter() + .filter_map(|(selected_row, row)| { + let group_constraint = try_option!(group_constraint.clone().simplify_by_row(&row)); + let group_constraint = match group_constraint.as_solution() { + Some(Value::Bool(true)) => None, + Some(Value::Bool(false)) => return None, + Some(_) => unreachable!(), // TODO: Handle + None => Some(group_constraint), + }; + let groupers = try_option!(groups + .iter() + .map(|group| { + group + .clone() + .simplify_by_row(&row)? + .confirm_or_err(SelectError::GrouperMayNotContainAggregate.into()) + }) + .collect::>>()); + Some(Ok((group_constraint, groupers, selected_row))) + }) + .collect::, Vec, Vec)>>>()?; + + ungrouped_groupers.sort_unstable_by(|groupers_a, groupers_b| { + groupers_a + .1 + .iter() + .zip(&groupers_b.1) + .find_map(|(grouper_a, grouper_b)| { + match grouper_a.null_cmp(grouper_b).unwrap_or(Ordering::Equal) { + Ordering::Equal => None, + other => Some(other), + } + }) + .unwrap_or(Ordering::Equal) + }); + let groups = ungrouped_groupers.into_iter().fold( + vec![], + |mut groups: Vec<(Vec, Vec<(Option, Vec)>)>, + grouper: (Option, Vec, Vec)| { + let value = &grouper.1; + if let Some(last) = groups.last_mut() { + if &last.0 == value { + last.1.push((grouper.0, grouper.2)); + } else { + groups.push((value.clone(), vec![(grouper.0, grouper.2)])); + } + groups + } else { + vec![(value.clone(), vec![(grouper.0, grouper.2)])] + } + }, + ); + let groups: Vec, Vec)>> = + groups.into_iter().map(|(_, group)| group).collect(); + + groups + .into_par_iter() + .filter_map(|group: Vec<(Option, Vec)>| { + // TODO: Improve + let first_row = + try_option!(group.get(0).ok_or(SelectError::Unreachable.into())).clone(); + let group_constraint = first_row.0; + if group_constraint.is_some() { + let group_constraint_accumulated = try_option!(group + .clone() + .into_iter() + .try_fold(vec![], |accumulators, (group_constraint, _)| { + group_constraint.unwrap().aggregate(accumulators) + })); + if matches!( + try_option!(group_constraint + .unwrap() + .solve_by_aggregate(group_constraint_accumulated)), + Value::Bool(false) + ) { + return None; + } + } + + let selections = first_row.1; + let accumulator_size = selections.len(); + let initial_accumulator = vec![vec![]; accumulator_size]; + let accumulated = try_option!(group.into_iter().try_fold( + initial_accumulator, + |accumulators, selection| { + selection + .1 + .into_iter() + .zip(accumulators) + .map(|(recipe, accumulators)| recipe.aggregate(accumulators)) + .collect::>>() + }, + )); + let result = selections + .clone() + .into_iter() + .zip(accumulated) + .map(|(selection, accumulated)| selection.solve_by_aggregate(accumulated)) + .collect::>(); + Some(result) + }) + .collect::>>()? + } else { + selected_rows + .into_iter() + .map(|(selection, _)| { + selection + .into_iter() + .map(|selected| selected.confirm()) + .collect::>() + }) + .collect::>>()? + }; + + Ok((labels, final_rows)) +} diff --git a/src/executor/query/select/order.rs b/src/executor/query/select/order.rs new file mode 100644 index 00000000..3be032b1 --- /dev/null +++ b/src/executor/query/select/order.rs @@ -0,0 +1,112 @@ +use { + crate::{ + executor::types::{ComplexColumnName, Row}, + MetaRecipe, PlannedRecipe, RecipeUtilities, Result, Value, + }, + sqlparser::ast::OrderByExpr, + std::cmp::Ordering, +}; + +pub struct Order(Vec); +impl Order { + pub fn new(order_by: Vec, columns: &Vec) -> Result { + let order_items = order_by + .into_iter() + .map(|order_by_item| PlannedOrderItem::new(order_by_item, columns)) + .collect::>>()?; + Ok(Order(order_items)) + } + pub fn execute(self, rows: Vec) -> Result> { + let (order_terms, order_item_recipes): (Vec, Vec) = self + .0 + .into_iter() + .map(|planned_order_item| { + let PlannedOrderItem(order_term, recipe) = planned_order_item; + (order_term, recipe) + }) + .unzip(); + let order_terms = OrderTerms(order_terms); + + let mut order_rows = rows + .into_iter() + .map(|row| { + let order_row = order_item_recipes + .clone() + .into_iter() + .map(|recipe| recipe.simplify_by_row(&row)?.confirm()) + .collect::>>(); + order_row.map(|order_row| (row, order_row)) + }) + .collect::)>>>()?; + + order_rows.sort_unstable_by(|(_, order_row_a), (_, order_row_b)| { + order_terms.sort(order_row_a, order_row_b) + }); + Ok(order_rows.into_iter().map(|(row, _)| row).collect()) + } +} + +struct PlannedOrderItem(OrderTerm, PlannedRecipe); +impl PlannedOrderItem { + pub fn new(order_by_item: OrderByExpr, columns: &Vec) -> Result { + let OrderByExpr { + expr, + asc, + nulls_first, + } = order_by_item; + let recipe = PlannedRecipe::new(MetaRecipe::new(expr)?.simplify_by_basic()?, columns)?; + let is_asc = asc.unwrap_or(true); + let prefer_nulls = nulls_first.unwrap_or(false); + + Ok(PlannedOrderItem( + OrderTerm { + is_asc, + prefer_nulls, + }, + recipe, + )) + } +} + +#[derive(Clone)] +struct OrderTerm { + pub is_asc: bool, + pub prefer_nulls: bool, +} +impl OrderTerm { + pub fn sort(&self, order_item_a: &Value, order_item_b: &Value) -> Option { + let order = match (order_item_a, order_item_b) { + (Value::Null, Value::Null) => Ordering::Equal, + (Value::Null, _) | (_, Value::Null) => { + if self.prefer_nulls { + Ordering::Greater + } else { + Ordering::Less + } + } + (other_a, other_b) => other_a.partial_cmp(other_b).unwrap_or(Ordering::Equal), + }; + if order == Ordering::Equal { + None + } else if self.is_asc { + Some(order) + } else { + Some(order.reverse()) + } + } +} + +struct OrderTerms(Vec); + +impl OrderTerms { + pub fn sort(&self, order_items_a: &Vec, order_items_b: &Vec) -> Ordering { + order_items_a + .iter() + .zip(order_items_b) + .zip(self.0.clone()) + .find_map(|((order_item_a, order_item_b), order_term)| { + order_term.sort(order_item_a, order_item_b) + }) + .unwrap_or(Ordering::Equal) + } +} diff --git a/src/executor/query/select/plan/mod.rs b/src/executor/query/select/plan/mod.rs new file mode 100644 index 00000000..652f1596 --- /dev/null +++ b/src/executor/query/select/plan/mod.rs @@ -0,0 +1,204 @@ +use { + super::{ + join::{JoinExecute, JoinPlan}, + Manual, Order, SelectItem, + }, + crate::{ + executor::{types::ComplexColumnName, PlannedRecipe}, + Result, StorageInner, + }, + futures::future::join_all, + serde::Serialize, + sqlparser::ast::{OrderByExpr, Select}, + thiserror::Error as ThisError, +}; + +pub struct Plan { + pub joins: Vec, + pub select_items: Vec, + pub constraint: PlannedRecipe, + pub groups: Vec, + pub group_constraint: PlannedRecipe, + pub order_by: Order, + pub labels: Vec, +} + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum PlanError { + #[error("this should be impossible, please report")] + UnreachableNoColumns, + #[error("this should be impossible, please report")] + UnreachableNoSelectItems, + #[error("this should be impossible, please report")] + Unreachable, +} + +impl Plan { + pub async fn new( + storages: &Vec<(String, &mut StorageInner)>, + select: Select, + order_by: Vec, + ) -> Result { + let Manual { + joins, + select_items, + constraint, + group_constraint, + groups, + } = Manual::new(select)?; + + let mut joins: Vec = join_all( + joins + .into_iter() + .map(|join| JoinPlan::new(join, storages)) + .collect::>(), + ) + .await + .into_iter() + .collect::>>()?; + + joins.sort_unstable(); + let table_columns = joins.iter().map(|join| join.columns.clone()).collect(); + let joins = joins + .into_iter() + .map(|mut join| { + join.calculate_needed_tables(&table_columns); + join + }) + .enumerate() + .collect(); + + let mut needed_joins: Vec<(usize, JoinPlan)> = joins; + let mut requested_joins: Vec<(usize, JoinPlan)> = vec![]; + let mut len_last: usize; + let mut len = 0; + loop { + len_last = len; + len = needed_joins.len(); + if needed_joins.is_empty() { + break; + } + let needed_joins_iter = needed_joins.into_iter(); + needed_joins = vec![]; + needed_joins_iter.for_each(|(needed_index, join)| { + if !join.needed_tables.iter().any(|needed_table_index| { + !(&needed_index == needed_table_index + || requested_joins + .iter() + .any(|(requested_index, _)| needed_table_index == requested_index)) + }) { + requested_joins.push((needed_index, join)) + } else { + if len == len_last { + // TODO + panic!( + "Impossible Join, table not present or tables require eachother: {:?}", + join + ) + // TODO: Handle + } + needed_joins.push((needed_index, join)) + } + }); + } + let columns = requested_joins + .iter() + .fold(vec![], |mut columns, (index, _)| { + columns.extend( + table_columns + .get(*index) + .expect("Something went very wrong") + .clone(), + ); + columns + }); + + let mut joins = requested_joins + .into_iter() + .map(|(_, join)| JoinExecute::new(join, &columns)) + .collect::>>()?; + + if let Some(first) = joins.first_mut() { + first.set_first_table() + } + + let include_table = joins.len() != 1; + let select_items = select_items + .into_iter() + .enumerate() + .map(|(index, select_item)| { + Ok(match select_item { + SelectItem::Recipe(meta_recipe, alias) => { + let recipe = PlannedRecipe::new(meta_recipe, &columns)?; + let label = + alias.unwrap_or(recipe.get_label(index, include_table, &columns)); + vec![(recipe, label)] + } + SelectItem::Wildcard(specifier) => { + let specified_table = specifier + .map(|specifier| specifier.get(0).map(|result| result.clone())) + .flatten(); + let matches_table = |column: &ComplexColumnName| { + specified_table + .clone() + .map(|specified_table| { + column.table.name == specified_table + || column + .table + .alias + .clone() + .map(|alias| alias == specified_table) + .unwrap_or(false) + }) + .unwrap_or(true) + }; + columns + .iter() + .enumerate() + .filter_map(|(index, column)| { + if matches_table(column) { + Some(( + PlannedRecipe::of_index(index), + if include_table { + format!("{}.{}", column.table.name, column.name) + } else { + column.name.clone() + }, + )) + } else { + None + } + }) + .collect() + } + }) + }) + .collect::>>>()? // TODO: Don't do this + .into_iter() + .reduce(|mut select_items, select_item_set| { + select_items.extend(select_item_set); + select_items + }) + .ok_or(PlanError::UnreachableNoSelectItems)?; + + let (select_items, labels) = select_items.into_iter().unzip(); + + let constraint = PlannedRecipe::new(constraint, &columns)?; + let group_constraint = PlannedRecipe::new(group_constraint, &columns)?; + let groups = groups + .into_iter() + .map(|group| PlannedRecipe::new(group, &columns)) + .collect::>>()?; + let order_by = Order::new(order_by, &columns)?; + + Ok(Plan { + joins, + select_items, + constraint, + group_constraint, + groups, + order_by, + labels, + }) + } +} diff --git a/src/executor/recipe/from.rs b/src/executor/recipe/from.rs new file mode 100644 index 00000000..b425d4e0 --- /dev/null +++ b/src/executor/recipe/from.rs @@ -0,0 +1,104 @@ +use { + super::{AggregateOperator, BinaryOperator, FunctionOperator, RecipeError, UnaryOperator}, + crate::{Result, Value}, + sqlparser::ast::{BinaryOperator as AstBinaryOperator, UnaryOperator as AstUnaryOperator}, +}; + +pub trait TryIntoMethod { + fn into_method(self) -> Result; +} + +impl TryIntoMethod for String { + fn into_method(self) -> Result { + match self.to_uppercase().as_str() { + "CONVERT" => Ok(Value::function_convert), + "TRY_CONVERT" => Ok(Value::function_try_convert), + + "UPPER" => Ok(Value::function_to_uppercase), + "LOWER" => Ok(Value::function_to_lowercase), + + "LEFT" => Ok(Value::function_left), + "RIGHT" => Ok(Value::function_right), + + "LEN" => Ok(Value::function_length), + "CONCAT" => Ok(Value::function_concat), + "REPLACE" => Ok(Value::function_replace), + + "NOW" => Ok(Value::function_now), + "YEAR" => Ok(Value::function_year), + "MONTH" => Ok(Value::function_month), + "DAY" => Ok(Value::function_day), + "HOUR" => Ok(Value::function_hour), + "DATEADD" => Ok(Value::function_date_add), + "DATEFROMPARTS" => Ok(Value::function_date_from_parts), + + "ROUND" => Ok(Value::function_round), + "POW" => Ok(Value::function_pow), + + "IIF" => Ok(Value::function_iif), + "IFNULL" => Ok(Value::function_if_null), + "NULLIF" => Ok(Value::function_null_if), + + unimplemented => { + Err(RecipeError::UnimplementedMethod(String::from(unimplemented)).into()) + } + } + } +} + +impl TryIntoMethod for String { + fn into_method(self) -> Result { + match self.to_uppercase().as_str() { + "COUNT" => Ok(Value::aggregate_count), + "MIN" => Ok(Value::aggregate_min), + "MAX" => Ok(Value::aggregate_max), + "SUM" => Ok(Value::aggregate_sum), + + unimplemented => { + Err(RecipeError::UnimplementedMethod(String::from(unimplemented)).into()) + } + } + } +} + +impl TryIntoMethod for AstUnaryOperator { + fn into_method(self) -> Result { + match self { + AstUnaryOperator::Plus => Ok(Value::generic_unary_plus), + AstUnaryOperator::Minus => Ok(Value::generic_unary_minus), + AstUnaryOperator::Not => Ok(Value::not), + + unimplemented => { + Err(RecipeError::UnimplementedMethod(format!("{:?}", unimplemented)).into()) + } + } + } +} + +impl TryIntoMethod for AstBinaryOperator { + fn into_method(self) -> Result { + match self { + AstBinaryOperator::Plus => Ok(Value::generic_add), + AstBinaryOperator::Minus => Ok(Value::generic_subtract), + AstBinaryOperator::Multiply => Ok(Value::generic_multiply), + AstBinaryOperator::Divide => Ok(Value::generic_divide), + AstBinaryOperator::Modulus => Ok(Value::generic_modulus), + + AstBinaryOperator::And => Ok(Value::and), + AstBinaryOperator::Or => Ok(Value::or), + + AstBinaryOperator::Eq => Ok(Value::eq), + AstBinaryOperator::NotEq => Ok(Value::not_eq), + AstBinaryOperator::Gt => Ok(Value::gt), + AstBinaryOperator::GtEq => Ok(Value::gt_eq), + AstBinaryOperator::Lt => Ok(Value::lt), + AstBinaryOperator::LtEq => Ok(Value::lt_eq), + + AstBinaryOperator::StringConcat => Ok(Value::string_concat), + + unimplemented => { + Err(RecipeError::UnimplementedMethod(format!("{:?}", unimplemented)).into()) + } + } + } +} diff --git a/src/executor/recipe/mod.rs b/src/executor/recipe/mod.rs new file mode 100644 index 00000000..7dd6e165 --- /dev/null +++ b/src/executor/recipe/mod.rs @@ -0,0 +1,151 @@ +mod from; +mod new; +mod planned; +mod resolve; + +pub use { + from::TryIntoMethod, + new::MetaRecipe, + planned::PlannedRecipe, + resolve::{Resolve, SimplifyBy}, +}; + +use { + crate::{executor::types::ObjectName, Error, Result, Value}, + serde::Serialize, + sqlparser::ast::{DataType, Expr}, + std::fmt::Debug, + thiserror::Error as ThisError, +}; + +#[derive(ThisError, Serialize, Debug, PartialEq)] +pub enum RecipeError { + #[error("recipe missing components")] + MissingComponents, + + #[error("{0} is either invalid or unimplemented")] + InvalidQuery(String), + #[error("{0} is invalid or unimplemented")] + InvalidExpression(Expr), + #[error("a function is either invalid or unimplemented")] + InvalidFunction, + + #[error("column '{0:?}' could not be found")] + MissingColumn(ObjectName), + #[error("column '{0:?}' could mean various different columns, please be more specific with (table).(column)")] + AmbiguousColumn(ObjectName), + + #[error("{0} is either invalid or unimplemented")] + UnimplementedQuery(String), + #[error("{0} is either invalid or unimplemented")] + UnimplementedMethod(String), + #[error("{0} is unimplemented")] + UnimplementedExpression(Expr), + + #[error("other failure occurred: {0}")] + Failed(String), + + #[error("this should be impossible, please report")] + UnreachableAggregatationFailed, + #[error("this should be impossible, please report")] + UnreachableAggregateFailed, + #[error("this should be impossible, please report, failure: {0}")] + UnreachableNotMethod(String), + #[error("this should be impossible, please report, failure: {0}")] + UnreachableNotAggregate(String), + #[error("this should be impossible, please report")] + UnreachableNoRow, + #[error("this should be impossible, please report")] + Unreachable, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Recipe { + Ingredient(Ingredient), + Method(Box), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Ingredient { + Value(Value), + Column(usize), + Aggregate(usize), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Method { + Value(Value), // Only occurs backwards for eval! Should never be returned outside of a recursive simplification! + Aggregate(AggregateOperator, Recipe), // Only occurs inside Ingredient::Aggregate. Perhaps this should not be a Method. + + UnaryOperation(UnaryOperator, Recipe), + BinaryOperation(BinaryOperator, Recipe, Recipe), + Function(FunctionOperator, Vec), + + Cast(DataType, Recipe), + + Case { + operand: Option, + cases: Vec<(Recipe, Recipe)>, + else_result: Option, + }, +} + +// Cannot derive Debug for references. Perhaps these shouldn't consume their operators. TODO. +pub type UnaryOperator = fn(Value) -> Result; +pub type BinaryOperator = fn(Value, Value) -> Result; +pub type FunctionOperator = fn(Vec) -> Result; +pub type AggregateOperator = fn(Value, Value) -> Result; + +pub trait RecipeUtilities +where + Self: Sized, +{ + fn as_solution(&self) -> Option; + + fn confirm_or_err(self, error: Error) -> Result { + self.as_solution().ok_or(error) + } + + fn confirm(self) -> Result { + self.confirm_or_err(RecipeError::MissingComponents.into()) + } + + fn simplify_by_basic(self) -> Result; +} +impl RecipeUtilities for Recipe { + fn as_solution(&self) -> Option { + if let Recipe::Ingredient(Ingredient::Value(value)) = self { + Some(value.clone()) + } else { + //println!("Remaining recipe: {:?}", self); + None + } + } + fn simplify_by_basic(self) -> Result { + self.simplify(SimplifyBy::Basic) + } +} +impl RecipeUtilities for MetaRecipe { + fn as_solution(&self) -> Option { + self.recipe.as_solution() + } + fn simplify_by_basic(mut self) -> Result { + self.recipe = self.recipe.simplify(SimplifyBy::Basic)?; + Ok(self) + } +} +impl RecipeUtilities for PlannedRecipe { + fn as_solution(&self) -> Option { + self.recipe.as_solution() + } + fn simplify_by_basic(mut self) -> Result { + self.recipe = self.recipe.simplify(SimplifyBy::Basic)?; + Ok(self) + } +} + +impl Recipe { + pub const NULL: Recipe = Recipe::Ingredient(Ingredient::Value(Value::Null)); + pub const TRUE: Recipe = Recipe::Ingredient(Ingredient::Value(Value::Bool(true))); + pub const SINGLE_COLUMN: Recipe = Recipe::Ingredient(Ingredient::Column(0)); +} diff --git a/src/executor/recipe/new.rs b/src/executor/recipe/new.rs new file mode 100644 index 00000000..ae066420 --- /dev/null +++ b/src/executor/recipe/new.rs @@ -0,0 +1,311 @@ +use { + super::{Ingredient, Method, Recipe, RecipeError, TryIntoMethod}, + crate::{ + executor::{ + query::{JoinManual, JoinType}, + types::{ComplexTableName, ObjectName}, + }, + Result, Value, + }, + sqlparser::ast::{Expr, FunctionArg, Ident, SelectItem, SetExpr}, + std::convert::TryFrom, +}; + +#[derive(Debug, Clone)] +pub struct MetaRecipe { + pub recipe: Recipe, + pub meta: RecipeMeta, +} +impl MetaRecipe { + pub fn new(expression: Expr) -> Result { + let (recipe, meta) = Recipe::new_with_meta(expression)?; + Ok(Self { recipe, meta }) + } +} +impl MetaRecipe { + pub const NULL: Self = MetaRecipe { + recipe: Recipe::Ingredient(Ingredient::Value(Value::Null)), + meta: RecipeMeta::NEW, + }; + pub const TRUE: Self = MetaRecipe { + recipe: Recipe::Ingredient(Ingredient::Value(Value::Bool(true))), + meta: RecipeMeta::NEW, + }; +} + +#[derive(Debug, Clone)] +pub struct RecipeMeta { + pub columns: Vec, + pub aggregates: Vec, + pub subqueries: Vec, +} +impl RecipeMeta { + pub const NEW: Self = Self { + columns: vec![], + aggregates: vec![], + subqueries: vec![], + }; + fn append_column(&mut self, column: ObjectName) { + self.columns.push(column); + } + fn append_aggregate(&mut self, aggregate: Recipe) { + self.aggregates.push(aggregate); + } + fn append_subquery(&mut self, subquery: JoinManual) { + self.subqueries.push(subquery); + } + fn find_column(&self, column: &ObjectName) -> Option { + self.columns + .iter() + .position(|search_column| search_column == column) + } + pub fn find_or_append_column(&mut self, column: ObjectName) -> usize { + self.find_column(&column).unwrap_or({ + self.append_column(column); + self.columns.len() - 1 + }) + } + pub fn aggregate(&mut self, aggregate: Recipe) -> Recipe { + self.append_aggregate(aggregate); + let index = self.aggregates.len() - 1; + Recipe::Ingredient(Ingredient::Aggregate(index)) + } + pub fn subquery(&mut self, subquery: Subquery) -> Result { + let result = subquery.column; + let table = subquery.table; + let join_type = JoinType::Left; + let constraint = subquery + .constraint + .map(MetaRecipe::new) + .unwrap_or(Ok(MetaRecipe::NULL))?; + let subquery = JoinManual { + table, + join_type, + constraint, + }; + self.append_subquery(subquery); + Ok(result) + } + pub fn aggregate_average(&mut self, argument: Recipe) -> Recipe { + Recipe::Method(Box::new(Method::BinaryOperation( + Value::generic_divide, + self.aggregate(Recipe::Method(Box::new(Method::Aggregate( + Value::aggregate_sum, + argument.clone(), + )))), + self.aggregate(Recipe::Method(Box::new(Method::Aggregate( + Value::aggregate_count, + argument, + )))), + ))) + } +} + +pub struct Subquery { + pub table: ComplexTableName, + pub column: Recipe, + pub constraint: Option, +} + +impl Recipe { + pub fn new_without_meta(expression: Expr) -> Result { + Self::new_with_meta(expression).map(|(new, _)| new) + } + fn new_with_meta(expression: Expr) -> Result<(Self, RecipeMeta)> { + let mut meta = RecipeMeta::NEW; + Ok((Self::with_meta(expression, &mut meta)?, meta)) + } + fn with_meta(expression: Expr, meta: &mut RecipeMeta) -> Result { + let error_expression_clone = expression.clone(); + match expression { + Expr::Identifier(identifier) => { + #[cfg(feature = "double_quote_strings")] + if identifier.quote_style == Some('"') { + Ok(Recipe::Ingredient(Ingredient::Value(Value::Str( + identifier.value, + )))) + } else { + Ok(Self::from_column( + identifier_into_object_name(vec![identifier]), + meta, + )) + } + #[cfg(not(feature = "double_quote_strings"))] + Ok(Self::from_column( + identifier_into_object_name(vec![identifier]), + meta, + )) + } + Expr::CompoundIdentifier(identifier) => Ok(Self::from_column( + identifier_into_object_name(identifier), + meta, + )), + Expr::Value(value) => Ok(Recipe::Ingredient(Ingredient::Value(Value::try_from( + &value, + )?))), + Expr::IsNull(expression) => Ok(Recipe::Method(Box::new(Method::UnaryOperation( + Value::is_null, + Self::with_meta(*expression, meta)?, + )))), + Expr::IsNotNull(expression) => Ok(Recipe::Method(Box::new(Method::UnaryOperation( + Value::not, + Recipe::Method(Box::new(Method::UnaryOperation( + Value::is_null, + Self::with_meta(*expression, meta)?, + ))), + )))), + Expr::UnaryOp { op, expr } => Ok(Recipe::Method(Box::new(Method::UnaryOperation( + op.into_method()?, + Self::with_meta(*expr, meta)?, + )))), + Expr::BinaryOp { op, left, right } => { + Ok(Recipe::Method(Box::new(Method::BinaryOperation( + op.into_method()?, + Self::with_meta(*left, meta)?, + Self::with_meta(*right, meta)?, + )))) + } + Expr::Function(function) => { + let name = function.name.0[0].value.clone(); + if name == "AVG" { + let argument = function + .args + .get(0) + .ok_or(RecipeError::InvalidExpression(error_expression_clone))? + .clone(); + let argument = Recipe::from_argument(argument, meta)?; + + Ok(meta.aggregate_average(argument)) + } else if let Ok(function_operator) = name.clone().into_method() { + let arguments = function + .args + .into_iter() + .map(|argument| Recipe::from_argument(argument, meta)) + .collect::>>()?; + Ok(Recipe::Method(Box::new(Method::Function( + function_operator, + arguments, + )))) + } else { + let argument = function + .args + .get(0) + .ok_or(RecipeError::InvalidExpression(error_expression_clone))? + .clone(); + let argument = Recipe::from_argument(argument, meta)?; + + Ok(meta.aggregate(Recipe::Method(Box::new(Method::Aggregate( + name.into_method()?, + argument, + ))))) + } + } + Expr::Case { + operand, + conditions, + results, + else_result, + } => Ok(Recipe::Method(Box::new(Method::Case { + operand: operand + .map(|operand| Self::with_meta(*operand, meta)) + .transpose()?, + cases: conditions + .into_iter() + .zip(results) + .map(|(condition, result)| { + Ok(( + Self::with_meta(condition, meta)?, + Self::with_meta(result, meta)?, + )) + }) + .collect::>>()?, + else_result: else_result + .map(|else_result| Self::with_meta(*else_result, meta)) + .transpose()?, + }))), + Expr::Cast { data_type, expr } => Ok(Recipe::Method(Box::new(Method::Cast( + data_type, + Self::with_meta(*expr, meta)?, + )))), + Expr::Between { + negated, + expr, + low, + high, + } => { + let body = Method::BinaryOperation( + Value::and, + Recipe::Method(Box::new(Method::BinaryOperation( + Value::gt_eq, + Self::with_meta(*expr.clone(), meta)?, + Self::with_meta(*low, meta)?, + ))), + Recipe::Method(Box::new(Method::BinaryOperation( + Value::lt_eq, + Self::with_meta(*expr, meta)?, + Self::with_meta(*high, meta)?, + ))), + ); + let body = if negated { + Method::UnaryOperation(Value::not, Recipe::Method(Box::new(body))) + } else { + body + }; + Ok(Recipe::Method(Box::new(body))) + } + Expr::Subquery(query) => { + if let SetExpr::Select(statement) = query.body { + let table = statement + .from + .get(0) + .ok_or(RecipeError::InvalidQuery(format!("{:?}", statement)))? + .relation + .clone(); + let table = JoinManual::table_identity(table)?; + + let column = statement + .projection + .get(0) + .map(|item| { + if let SelectItem::UnnamedExpr(expression) = item { + Some(Self::with_meta(expression.clone(), meta)) + } else { + None + } + }) + .flatten() + .ok_or(RecipeError::InvalidQuery(format!("{:?}", statement)))??; + + let constraint = statement.selection; + + Ok(meta.subquery(Subquery { + table, + column, + constraint, + })?) + } else { + Err(RecipeError::UnimplementedQuery(format!("{:?}", query)).into()) + } + } + Expr::Nested(expression) => Self::with_meta(*expression, meta), + unimplemented => Err(RecipeError::UnimplementedExpression(unimplemented).into()), + } + } + fn from_argument(argument: FunctionArg, meta: &mut RecipeMeta) -> Result { + match argument { + FunctionArg::Named { arg, .. } | FunctionArg::Unnamed(arg) => { + Self::with_meta(arg, meta) + } + } + } + fn from_column(column: ObjectName, meta: &mut RecipeMeta) -> Recipe { + Recipe::Ingredient(Ingredient::Column(meta.find_or_append_column(column))) + } +} + +fn identifier_into_object_name(identifier: Vec) -> ObjectName { + identifier + .into_iter() + .map(|identifier| identifier.value) + .collect() +} diff --git a/src/executor/recipe/planned.rs b/src/executor/recipe/planned.rs new file mode 100644 index 00000000..ef37a17a --- /dev/null +++ b/src/executor/recipe/planned.rs @@ -0,0 +1,182 @@ +use { + super::{ + Ingredient, MetaRecipe, Method, Recipe, RecipeError, RecipeUtilities, Resolve, SimplifyBy, + }, + crate::{ + executor::types::{ComplexColumnName, Row}, + Result, Value, + }, +}; + +#[derive(Debug, Clone)] +pub struct PlannedRecipe { + pub recipe: Recipe, + pub needed_column_indexes: Vec, + pub aggregates: Vec, +} + +impl PlannedRecipe { + pub const TRUE: Self = Self { + recipe: Recipe::TRUE, + needed_column_indexes: vec![], + aggregates: vec![], + }; + pub fn new(meta_recipe: MetaRecipe, columns: &Vec) -> Result { + let MetaRecipe { recipe, meta } = meta_recipe; + let aggregates = meta.aggregates; + let needed_column_indexes = meta + .columns + .into_iter() + .map(|needed_column| { + let needed_column_index_options: Vec = columns + .iter() + .enumerate() + .filter_map(|(index, column)| { + if column == &needed_column { + Some(index.clone()) + } else { + None + } + }) + .collect(); + match needed_column_index_options.len() { + 0 => Err(RecipeError::MissingColumn(needed_column).into()), + 1 => Ok(needed_column_index_options[0]), + _ => Err(RecipeError::AmbiguousColumn(needed_column).into()), + } + }) + .collect::>>()?; + + Ok(Self { + recipe, + needed_column_indexes, + aggregates, + }) + } + pub fn of_index(index: usize) -> Self { + Self { + recipe: Recipe::SINGLE_COLUMN, + needed_column_indexes: vec![index], + aggregates: vec![], + } + } + pub fn confirm_join_constraint(&self, plane_row: &Row, self_row: &Row) -> Result { + // Very crucuial to have performant, needs *a lot* of optimisation. + // This is currently not good enough. + // For a join such as: + /* + SELECT + * + FROM + big_table + LEFT JOIN bigger_table + ON big_table.a = LEFT(bigger_table.b, 3) + LEFT JOIN biggest_table + ON big_table.c = (biggest_table.d + 1) + */ + /* + Where: + (a) big_table rows = 1 000, + (b) bigger_table rows = 10 000, + (c) biggest_table rows = 100 000, + */ + // This will run a * b * c times (1 000 000 000 000 (1e+12)(one trillion) times). + // This isn't a particularly unusual query for a big database to run. + // Note that the number of times this runs can, will and should be optimised by reducing the number of rows that need to be compared with good planning scenarios. + // All of the above (obviously) applies to all functions used in this function. + let mut plane_row = plane_row.clone(); + plane_row.extend(self_row.clone()); + + self.confirm_constraint(&plane_row) + } + pub fn confirm_constraint(&self, row: &Row) -> Result { + let solution = self + .clone() + .simplify_by_row_simple(row)? + .confirm_or_err(RecipeError::MissingComponents.into())?; + Ok(matches!(solution, Value::Bool(true))) + } + fn simplify_by_row_simple(self, row: &Row) -> Result { + let row = self.condense_row(row)?; + self.recipe.simplify(SimplifyBy::Row(&row)) + } + fn condense_row(&self, row: &Row) -> Result { + Ok(self + .needed_column_indexes + .iter() + .map(|index| { + row.get(*index) + .map(|value| value.clone()) + .unwrap_or(Value::Null) // Maybe this is problematic + }) + .collect::>()) + } + pub fn simplify_by_row(self, row: &Row) -> Result { + let row = self.condense_row(row)?; + let recipe = self.recipe.simplify(SimplifyBy::Row(&row))?; + let aggregates = self + .aggregates + .into_iter() + .map(|aggregate| aggregate.simplify(SimplifyBy::Row(&row))) + .collect::>>()?; + let needed_column_indexes = self.needed_column_indexes; + Ok(Self { + recipe, + aggregates, + needed_column_indexes, + }) + } + pub fn aggregate(&self, accumulated: Vec) -> Result> { + let accumulated = if accumulated.is_empty() { + vec![Value::Null; self.aggregates.len()] + } else { + accumulated + }; + self.aggregates + .clone() + .into_iter() + .zip(accumulated) + .map(|(aggregate, accumulated)| { + if let Recipe::Method(aggregate) = aggregate { + if let Method::Aggregate(operator, recipe) = *aggregate { + let value = recipe + .confirm_or_err(RecipeError::UnreachableAggregatationFailed.into())?; + operator(value, accumulated) + } else { + Err(RecipeError::UnreachableNotAggregate(format!("{:?}", aggregate)).into()) + } + } else { + Err(RecipeError::UnreachableNotMethod(format!("{:?}", aggregate)).into()) + } + }) + .collect::>>() + } + pub fn solve_by_aggregate(self, accumulated: Vec) -> Result { + self.recipe + .simplify(SimplifyBy::CompletedAggregate(accumulated))? + .confirm_or_err(RecipeError::UnreachableAggregateFailed.into()) + } + pub fn get_label( + &self, + selection_index: usize, + include_table: bool, + columns: &Vec, + ) -> String { + if let Recipe::Ingredient(Ingredient::Column(_)) = self.recipe { + self.needed_column_indexes + .get(0) + .map(|index| columns.get(index.clone())) + .flatten() + .map(|column| { + if include_table { + format!("{}.{}", column.table.name, column.name) + } else { + column.name.clone() + } + }) + } else { + None + } + .unwrap_or(format!("unnamed_{}", selection_index)) + } +} diff --git a/src/executor/recipe/resolve.rs b/src/executor/recipe/resolve.rs new file mode 100644 index 00000000..b20f4308 --- /dev/null +++ b/src/executor/recipe/resolve.rs @@ -0,0 +1,211 @@ +use { + super::{Ingredient, Method, Recipe, RecipeError, RecipeUtilities}, + crate::{executor::types::Row, Result, Value}, +}; + +#[derive(Clone)] +pub enum SimplifyBy<'a> { + Basic, + Row(&'a Row), + CompletedAggregate(Vec), +} + +pub trait Resolve +where + Self: Sized, +{ + fn simplify(self, component: SimplifyBy) -> Result; +} + +impl Resolve for Recipe { + fn simplify(self, component: SimplifyBy) -> Result { + match self { + Recipe::Ingredient(ingredient) => { + ingredient.simplify(component).map(Recipe::Ingredient) + } + Recipe::Method(method) => method.simplify(component).map(|method| { + if let Method::Value(value) = method { + Recipe::Ingredient(Ingredient::Value(value)) + } else { + Recipe::Method(Box::new(method)) + } + }), + } + } +} + +impl Resolve for Ingredient { + fn simplify(self, component: SimplifyBy) -> Result { + Ok(match self { + Ingredient::Column(index) => { + if let SimplifyBy::Row(row) = component { + Ingredient::Value(row.get(index).ok_or(RecipeError::UnreachableNoRow)?.clone()) + } else { + self + } + } + Ingredient::Aggregate(index) => { + if let SimplifyBy::CompletedAggregate(values) = component { + Ingredient::Value(values.get(index).ok_or(RecipeError::Unreachable)?.clone()) + } else { + self + } + } + Ingredient::Value(..) => self, // Already simple! + }) + } +} + +impl Resolve for Method { + fn simplify(self, component: SimplifyBy) -> Result { + Ok(match self { + Method::UnaryOperation(operator, recipe) => { + let recipe = recipe.simplify(component)?; + if let Some(value) = recipe.as_solution() { + Method::Value(operator(value)?) + } else { + Method::UnaryOperation(operator, recipe) + } + } + Method::BinaryOperation(operator, left, right) => { + let left = left.simplify(component.clone())?; + + if let Some(Value::Bool(value)) = left.as_solution() { + // Optimisation -- is this a good idea? + if !value { + if operator == Value::and { + return Ok(Method::Value(Value::Bool(false))); + } + } else { + if operator == Value::or { + return Ok(Method::Value(Value::Bool(true))); + } + } + } + + let right = right.simplify(component)?; + + if let (Some(left), Some(right)) = (left.as_solution(), right.as_solution()) { + Method::Value(operator(left, right)?) + } else { + Method::BinaryOperation(operator, left, right) + } + } + Method::Function(function, arguments) => { + let arguments = arguments + .into_iter() + .map(|argument| argument.simplify(component.clone())) + .collect::>>()?; + if let Some(arguments) = arguments + .iter() + .map(|argument| argument.as_solution()) + .collect::>>() + { + Method::Value(function(arguments)?) + } else { + Method::Function(function, arguments) + } + } + Method::Cast(data_type, recipe) => { + let recipe = recipe.simplify(component)?; + if let Some(value) = recipe.as_solution() { + Method::Value(value.cast_datatype(&data_type)?) + } else { + Method::Cast(data_type, recipe) + } + } + + Method::Case { + operand, + cases, + else_result, + } => { + let operand = operand + .map(|operand| operand.simplify(component.clone())) + .transpose()?; + let else_result = else_result + .map(|else_result| else_result.simplify(component.clone())) + .transpose()?; + let cases = cases + .into_iter() + .map(|(condition, result)| { + Ok(( + condition.simplify(component.clone())?, + result.simplify(component.clone())?, + )) + }) + .collect::>>()?; + + if let Some(None) = operand.clone().map(|operand| operand.as_solution()) { + Method::Case { + operand, + cases, + else_result, + } + } else if let Some(None) = else_result + .clone() + .map(|else_result| else_result.as_solution()) + { + Method::Case { + operand, + cases, + else_result, + } + } else if let Some(cases) = cases + .iter() + .map(|(condition, result)| { + Some((condition.as_solution()?, result.as_solution()?)) + }) + .collect::>>() + { + let operand = operand.map(|operand| operand.as_solution()); + let else_result = else_result + .map(|else_result| else_result.as_solution()) + .unwrap_or(Some(Value::Null)) + .unwrap(); + if let Some(operand) = operand { + let operand = operand.unwrap(); + Method::Value( + cases + .into_iter() + .find_map(|(condition, result)| { + if operand == condition { + Some(result) + } else { + None + } + }) + .unwrap_or(else_result), + ) + } else { + Method::Value( + cases + .into_iter() + .find_map(|(condition, result)| { + if matches!(condition, Value::Bool(true)) { + Some(result) + } else { + None + } + }) + .unwrap_or(else_result), + ) + } + } else { + Method::Case { + operand, + cases, + else_result, + } + } + } + + Method::Value(..) => return Err(RecipeError::Unreachable.into()), + + // This will only occur for a special aggregate simplify + Method::Aggregate(operator, recipe) => { + Method::Aggregate(operator, recipe.simplify(component)?) + } + }) + } +} diff --git a/src/executor/select.rs b/src/executor/select.rs deleted file mode 100644 index 65912454..00000000 --- a/src/executor/select.rs +++ /dev/null @@ -1,260 +0,0 @@ -use boolinator::Boolinator; -use futures::stream::{self, Stream, StreamExt, TryStream, TryStreamExt}; -use iter_enum::Iterator; -use serde::Serialize; -use std::fmt::Debug; -use std::iter::once; -use std::rc::Rc; -use thiserror::Error as ThisError; - -use sqlparser::ast::{Expr, Ident, Query, SelectItem, SetExpr, TableWithJoins}; - -use super::aggregate::Aggregate; -use super::blend::Blend; -use super::context::{BlendContext, FilterContext}; -use super::fetch::fetch_columns; -use super::filter::Filter; -use super::join::Join; -use super::limit::Limit; -use crate::data::{get_name, Row, Table}; -use crate::result::{Error, Result}; -use crate::store::Store; - -#[derive(ThisError, Serialize, Debug, PartialEq)] -pub enum SelectError { - #[error("unimplemented! select on two or more than tables are not supported")] - TooManyTables, - - #[error("table alias not found: {0}")] - TableAliasNotFound(String), - - #[error("unreachable!")] - Unreachable, -} - -async fn fetch_blended<'a, T: 'static + Debug>( - storage: &dyn Store, - table: Table<'a>, - columns: Rc<[Ident]>, -) -> Result>> + 'a> { - let rows = storage.scan_data(table.get_name()).await?.map(move |data| { - let (_, row) = data?; - let row = Some(row); - let columns = Rc::clone(&columns); - - Ok(BlendContext::new(table.get_alias(), columns, row, None)) - }); - - Ok(stream::iter(rows)) -} - -fn get_labels<'a>( - projection: &[SelectItem], - table_alias: &str, - columns: &'a [Ident], - join_columns: &'a [(&String, Vec)], -) -> Result> { - #[derive(Iterator)] - enum Labeled { - Err(I1), - Wildcard(I2), - QualifiedWildcard(I3), - Once(I4), - } - - let err = |e| Labeled::Err(once(Err(e))); - - macro_rules! try_into { - ($v: expr) => { - match $v { - Ok(v) => v, - Err(e) => { - return err(e); - } - } - }; - } - - let to_labels = |columns: &'a [Ident]| columns.iter().map(|ident| ident.value.to_string()); - - projection - .iter() - .flat_map(|item| match item { - SelectItem::Wildcard => { - let labels = to_labels(columns); - let join_labels = join_columns - .iter() - .flat_map(|(_, columns)| to_labels(columns)); - let labels = labels.chain(join_labels).map(Ok); - - Labeled::Wildcard(labels) - } - SelectItem::QualifiedWildcard(target) => { - let target_table_alias = try_into!(get_name(target)); - - if table_alias == target_table_alias { - return Labeled::QualifiedWildcard(to_labels(columns).map(Ok)); - } - - let columns = join_columns - .iter() - .find(|(table_alias, _)| table_alias == &target_table_alias) - .map(|(_, columns)| columns) - .ok_or_else(|| { - SelectError::TableAliasNotFound(target_table_alias.to_string()).into() - }); - let columns = try_into!(columns); - let labels = to_labels(columns).map(Ok); - - Labeled::QualifiedWildcard(labels) - } - SelectItem::UnnamedExpr(expr) => { - let label = match expr { - Expr::CompoundIdentifier(idents) => try_into!(idents - .last() - .map(|ident| ident.value.to_string()) - .ok_or_else(|| SelectError::Unreachable.into())), - _ => expr.to_string(), - }; - - Labeled::Once(once(Ok(label))) - } - SelectItem::ExprWithAlias { alias, .. } => { - Labeled::Once(once(Ok(alias.value.to_string()))) - } - }) - .collect::>() -} - -pub async fn select_with_labels<'a, T: 'static + Debug>( - storage: &'a dyn Store, - query: &'a Query, - filter_context: Option>>, - with_labels: bool, -) -> Result<(Vec, impl TryStream + 'a)> { - macro_rules! err { - ($err: expr) => {{ - return Err($err.into()); - }}; - } - - let (table_with_joins, where_clause, projection, group_by, having) = match &query.body { - SetExpr::Select(statement) => { - let tables = &statement.from; - let table_with_joins = match tables.len() { - 1 => &tables[0], - 0 => err!(SelectError::Unreachable), - _ => err!(SelectError::TooManyTables), - }; - - ( - table_with_joins, - statement.selection.as_ref(), - statement.projection.as_ref(), - &statement.group_by, - statement.having.as_ref(), - ) - } - _ => err!(SelectError::Unreachable), - }; - - let TableWithJoins { relation, joins } = &table_with_joins; - let table = Table::new(relation)?; - - let columns = fetch_columns(storage, table.get_name()).await?; - let join_columns = stream::iter(joins.iter()) - .map(Ok::<_, Error>) - .and_then(|join| { - let table = Table::new(&join.relation); - - async move { - let table = table?; - let table_alias = table.get_alias(); - let table_name = table.get_name(); - - let columns = fetch_columns(storage, table_name).await?; - - Ok((table_alias, columns)) - } - }) - .try_collect::>() - .await?; - - let labels = if with_labels { - get_labels(&projection, table.get_alias(), &columns, &join_columns)? - } else { - vec![] - }; - - let columns = Rc::from(columns); - let join_columns = join_columns - .into_iter() - .map(|(_, columns)| columns) - .map(Rc::from) - .collect::>(); - let join_columns = Rc::from(join_columns); - - let join = Rc::new(Join::new( - storage, - joins, - filter_context.as_ref().map(Rc::clone), - )); - let aggregate = Aggregate::new( - storage, - projection, - group_by, - having, - filter_context.as_ref().map(Rc::clone), - ); - let blend = Rc::new(Blend::new(storage, projection)); - let filter = Rc::new(Filter::new(storage, where_clause, filter_context, None)); - let limit = Rc::new(Limit::new(query.limit.as_ref(), query.offset.as_ref())?); - - let rows = fetch_blended(storage, table, columns) - .await? - .then(move |blend_context| { - let join_columns = Rc::clone(&join_columns); - let join = Rc::clone(&join); - - async move { join.apply(blend_context, join_columns).await } - }) - .try_flatten() - .try_filter_map(move |blend_context| { - let filter = Rc::clone(&filter); - - async move { - filter - .check(Rc::clone(&blend_context)) - .await - .map(|pass| pass.as_some(blend_context)) - } - }) - .enumerate() - .filter_map(move |(i, item)| { - let limit = Rc::clone(&limit); - - async move { limit.check(i).as_some(item) } - }); - - let rows = aggregate - .apply(rows) - .await? - .into_stream() - .and_then(move |aggregate_context| { - let blend = Rc::clone(&blend); - - async move { blend.apply(Ok(aggregate_context)).await } - }); - - Ok((labels, rows)) -} - -pub async fn select<'a, T: 'static + Debug>( - storage: &'a dyn Store, - query: &'a Query, - filter_context: Option>>, -) -> Result + 'a> { - select_with_labels(storage, query, filter_context, false) - .await - .map(|(_, rows)| rows) -} diff --git a/src/executor/types.rs b/src/executor/types.rs new file mode 100644 index 00000000..caa8ba15 --- /dev/null +++ b/src/executor/types.rs @@ -0,0 +1,58 @@ +use {crate::Value, serde::Serialize, std::fmt::Debug}; + +pub type Table = String; +pub type TableWithAlias = (Alias, Table); +pub type Alias = Option; +pub type Label = String; +pub type Row = Vec; +pub type LabelsAndRows = (Vec