diff --git a/.gitignore b/.gitignore index 7d06363c..9f3df2d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,30 +1,5 @@ -# GlueSQL project files /data/ - -# Vim -*.swp - -# Visual Studio Code -.vscode - -#Clion -.idea - -# Generated by Cargo -# will have compiled files and executables /target/ - -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock - -# These are backup files generated by rustfmt +*.sublime-workspace **/*.rs.bk - - -#Added by cargo -# -#already existing elements are commented out - -/target -#**/*.rs.bk diff --git a/Cargo.toml b/Cargo.toml index 62dbaaa3..a6740462 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,6 @@ "alter-table", "auto-increment", # Data - "double_quote_strings", "implicit_float_conversion", # API "expanded-api", @@ -62,6 +61,7 @@ fstrings = "0.2.3" regex = "1" chrono = { version = "0.4.19", features = ["serde", "unstable-locales"] } + concat-idents = "1.1.2" # OPTIONAL DEPENDENCIES # Multiple diff --git a/benches/sled_benchmark.rs b/benches/sled_benchmark.rs deleted file mode 100644 index 17c59899..00000000 --- a/benches/sled_benchmark.rs +++ /dev/null @@ -1,216 +0,0 @@ -/*use criterion::{criterion_group, criterion_main, Criterion}; -use multisql::{parse, Glue, SledStorage}; -use std::convert::TryFrom; - -const ITEM_SIZE: u32 = 5000; - -// Generate benchmark tests -pub fn bench_insert(c: &mut Criterion) { - // Generate a new database - let path = format!("data/bench_insert"); - - match std::fs::remove_dir_all(&path) { - Ok(()) => (), - // Silently ignore, 99% of the time this will already be removed. - Err(_) => (), - } - - let config = sled::Config::default() - .path(path) - .temporary(true) - .mode(sled::Mode::HighThroughput); - - let storage = SledStorage::try_from(config).unwrap(); - let mut glue = Glue::new(storage); - // Create a dummy table - let sqls = " - CREATE TABLE Testing ( - id INTEGER, - field_one TEXT, - field_two TEXT, - field_three TEXT - ); - "; - - for query in parse(sqls).unwrap() { - glue.execute(&query).unwrap(); - } - - // Prepare query out of scope, and copy it at the beginning - let mut id = 0; - - c.bench_function("insert_one", |b| { - b.iter(|| { - let query_str = format!( - "INSERT INTO Testing \ - VALUES ({:#}, \"Testing 1\", \"Testing 2\", \"Testing 3\");", - &id - ); - id += 1; - for query in parse(&query_str).unwrap() { - glue.execute(&query).unwrap(); - } - }) - }); -} - -pub fn bench_select(c: &mut Criterion) { - // Generate a new database - let path = format!("data/bench_select"); - - match std::fs::remove_dir_all(&path) { - Ok(()) => (), - // Silently ignore, 99% of the time this will already be removed. - Err(_) => (), - } - - let config = sled::Config::default() - .path(path) - .temporary(true) - .mode(sled::Mode::HighThroughput); - - let storage = SledStorage::try_from(config).unwrap(); - let mut glue = Glue::new(storage); - // Create a dummy table - { - let mut sqls: String = " - CREATE TABLE Testing ( - id INTEGER, - field_one TEXT, - field_two TEXT, - field_three TEXT - );" - .to_string(); - - for i in 0..ITEM_SIZE { - sqls += &*format!( - "INSERT INTO Testing \ - VALUES ({:#}, \"Testing 1\", \"Testing 2\", \"Testing 3\");", - &i - ); - } - - for query in parse(&sqls).unwrap() { - glue.execute(&query).unwrap(); - } - } - - // Prepare query out of scope, and copy it at the beginning - let mut id = 0; - - c.bench_function("select_one", |b| { - b.iter(|| { - let query_str = format!("SELECT * FROM Testing WHERE id = {}", id); - id += 1; - if id >= ITEM_SIZE { - id = 1; - } - for query in parse(&query_str).unwrap() { - glue.execute(&query).unwrap(); - } - }) - }); - c.bench_function("select_many", |b| { - b.iter(|| { - let query_str = format!( - "SELECT * FROM Testing WHERE id > {} AND id < {}", - id, - id + 50 - ); - id += 1; - if id >= ITEM_SIZE { - id = 1; - } - for query in parse(&query_str).unwrap() { - glue.execute(&query).unwrap(); - } - }) - }); -} - -pub fn bench_select_tainted(c: &mut Criterion) { - // Generate a new database - let path = format!("data/bench_select_tainted"); - - match std::fs::remove_dir_all(&path) { - Ok(()) => (), - // Silently ignore, 99% of the time this will already be removed. - Err(_) => (), - } - - let config = sled::Config::default() - .path(path) - .temporary(true) - .mode(sled::Mode::HighThroughput); - - let storage = SledStorage::try_from(config).unwrap(); - let mut glue = Glue::new(storage); - // Create a dummy table - { - let mut sqls: String = " - CREATE TABLE Testing ( - id INTEGER, - field_one TEXT, - field_two TEXT, - field_three TEXT - ); - CREATE TABLE TestingTainted ( - id INTEGER, - field_one TEXT, - field_two TEXT, - field_three TEXT - ); - " - .to_string(); - - for i in 0..ITEM_SIZE { - sqls += &*format!( - "INSERT INTO Testing \ - VALUES ({0:#}, \"Testing 1\", \"Testing 2\", \"Testing 3\");\ - INSERT INTO TestingTainted \ - VALUES ({0:#}, \"Testing_tainted 1\", \"Testing_tainted 2\", \"Testing_tainted 3\");", - &i - ); - } - - for query in parse(&sqls).unwrap() { - glue.execute(&query).unwrap(); - } - } - - // Prepare query out of scope, and copy it at the beginning - let mut id = 0; - - c.bench_function("select_one_tainted", |b| { - b.iter(|| { - let query_str = format!("SELECT * FROM Testing WHERE id = {}", id); - id += 1; - if id >= ITEM_SIZE { - id = 1; - } - for query in parse(&query_str).unwrap() { - glue.execute(&query).unwrap(); - } - }) - }); - c.bench_function("select_many_tainted", |b| { - b.iter(|| { - let query_str = format!( - "SELECT * FROM Testing WHERE id > {} AND id < {}", - id, - id + 50 - ); - id += 1; - if id >= ITEM_SIZE { - id = 1; - } - for query in parse(&query_str).unwrap() { - glue.execute(&query).unwrap(); - } - }) - }); -} - -criterion_group!(benches, bench_insert, bench_select, bench_select_tainted); -criterion_main!(benches); -*/ diff --git a/dprint.json b/dprint.json new file mode 100644 index 00000000..345fb401 --- /dev/null +++ b/dprint.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://dprint.dev/schemas/v0.json", + "projectType": "openSource", + "incremental": true, + "useTabs": true, + "lineWidth": 100, + "rustfmt": { + "imports_layout": "vertical", + "version": "Two" + }, + "includes": ["**/*"], + "excludes": [ + "**/book/**", + "**/target/**", + "**/*-lock.json" + ], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.45.0.wasm", + "https://plugins.dprint.dev/json-0.10.2.wasm", + "https://plugins.dprint.dev/markdown-0.7.1.wasm", + "https://plugins.dprint.dev/rustfmt-0.3.0.wasm", + "https://plugins.dprint.dev/prettier-0.2.2.exe-plugin@63b06beba3acd51e6d23379c47db342a1a24f3d88f3c52a775e2db3426124582", + "https://github.com/thomaseizinger/dprint-plugin-cargo-toml/releases/download/0.1.0/cargo-toml-0.1.0.wasm" + ] +} diff --git a/examples/api_usage.rs b/examples/api_usage.rs deleted file mode 100644 index ab342939..00000000 --- a/examples/api_usage.rs +++ /dev/null @@ -1,48 +0,0 @@ -/* -#[cfg(feature = "sled-storage")] -use futures::executor::block_on; -#[cfg(feature = "sled-storage")] -use multisql::{execute, parse, Glue, SledStorage}; - -#[cfg(feature = "sled-storage")] -fn immutable_api() { - let storage = SledStorage::new("data/immutable-api").unwrap(); - - let sqls = " - CREATE TABLE Glue (id INTEGER); - INSERT INTO Glue VALUES (100); - INSERT INTO Glue VALUES (200); - DROP TABLE Glue; - "; - - parse(sqls).unwrap().iter().fold(storage, |storage, query| { - let (storage, _) = block_on(execute(storage, query)).unwrap(); - - storage - }); -} - -#[cfg(feature = "sled-storage")] -fn mutable_api() { - let storage = SledStorage::new("data/mutable-api").unwrap(); - let mut glue = Glue::new(storage); - - let sqls = " - CREATE TABLE Glue (id INTEGER); - INSERT INTO Glue VALUES (100); - INSERT INTO Glue VALUES (200); - DROP TABLE Glue; - "; - - for query in parse(sqls).unwrap() { - glue.execute(&query).unwrap(); - } -}*/ - -fn main() { - #[cfg(feature = "sled-storage")] - { - /*mutable_api(); - immutable_api();*/ - } -} diff --git a/examples/hello_world.rs b/examples/hello_world.rs deleted file mode 100644 index 57f9eb7e..00000000 --- a/examples/hello_world.rs +++ /dev/null @@ -1,71 +0,0 @@ -/*#[cfg(feature = "sled-storage")] -mod hello_world { - use multisql::{parse, Glue, Payload, SledStorage, Value}; - - pub fn run() { - /* - Initiate a connection - */ - /* - Open a Sled database, this will create one if one does not yet exist - */ - let storage = SledStorage::new("/tmp/multisql/hello_world").expect("Something went wrong!"); - /* - Wrap the Sled database with Glue - */ - let mut glue = Glue::new(storage); - - /* - Create table then insert a row - - Write queries as a string - */ - let queries = " - CREATE TABLE greet (name TEXT); - INSERT INTO greet VALUES (\"World\"); - "; - - let parsed_queries = parse(queries).expect("Parsing failed"); - for query in parsed_queries { - glue.execute(&query).expect("Execution failed"); - } - - /* - Select inserted row - */ - let queries = " - SELECT name FROM greet - "; - - let parsed_query = &parse(queries).expect("Failed to parse query")[0]; - - let result = glue.execute(&parsed_query).expect("Failed to execute"); - - /* - Query results are wrapped into a payload enum, on the basis of the query type - */ - let rows = match result { - Payload::Select { labels: _, rows } => rows, - _ => panic!("Unexpected result: {:?}", result), - }; - - let first_row = &rows[0]; - let first_row_unwrapped = &first_row.0; - let first_value = &first_row_unwrapped[0]; - - /* - Row values are wrapped into a value enum, on the basis of the result type - */ - let to_greet = match first_value { - Value::Str(to_greet) => to_greet, - value => panic!("Unexpected type: {:?}", value), - }; - - println!("Hello {}!", to_greet); // Will always output "Hello World!" - } -} -*/ -fn main() { - /*#[cfg(feature = "sled-storage")] - hello_world::run();*/ -} diff --git a/examples/sled_multi_threaded.rs b/examples/sled_multi_threaded.rs deleted file mode 100644 index 99941c45..00000000 --- a/examples/sled_multi_threaded.rs +++ /dev/null @@ -1,81 +0,0 @@ -/* -#[cfg(feature = "sled-storage")] -mod sled_multi_threaded { - use { - multisql::{parse, Glue, Payload, SledStorage, Value}, - std::thread, - }; - - pub fn run() { - let storage = SledStorage::new("/tmp/multisql/hello_world").expect("Something went wrong!"); - let mut glue = Glue::new(storage.clone()); - let queries = " - CREATE TABLE IF NOT EXISTS greet (name TEXT); - DELETE FROM greet; - "; - - let parsed_queries = parse(queries).expect("Parsing failed"); - for query in parsed_queries { - glue.execute(&query).expect("Execution failed"); - } - /* - SledStorage supports cloning, using this we can create copies of the storage for new threads; - all we need to do is wrap it in glue again. - */ - let foo_storage = storage.clone(); - let foo_thread = thread::spawn(move || { - let mut glue = Glue::new(foo_storage); - let queries = "INSERT INTO greet (name) VALUES (\"Foo\")"; - let parsed_queries = parse(queries).expect("Parsing failed"); - for query in parsed_queries { - glue.execute(&query).expect("Execution failed"); - } - }); - - let world_storage = storage.clone(); - let world_thread = thread::spawn(move || { - let mut glue = Glue::new(world_storage); - let queries = "INSERT INTO greet (name) VALUES (\"World\")"; - let parsed_queries = parse(queries).expect("Parsing failed"); - for query in parsed_queries { - glue.execute(&query).expect("Execution failed"); - } - }); - - world_thread - .join() - .expect("Something went wrong in the world thread"); - - foo_thread - .join() - .expect("Something went wrong in the foo thread"); - - let queries = " - SELECT name FROM greet - "; - - let parsed_query = &parse(queries).expect("Failed to parse query")[0]; - - let result = glue.execute(&parsed_query).expect("Failed to execute"); - - let rows = match result { - Payload::Select { labels: _, rows } => rows, - _ => panic!("Unexpected result: {:?}", result), - }; - - let first_row = &rows[0]; - let first_row_unwrapped = &first_row.0; - let first_value = &first_row_unwrapped[0]; - let to_greet = match first_value { - Value::Str(to_greet) => to_greet, - value => panic!("Unexpected type: {:?}", value), - }; - - 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();*/ -} diff --git a/examples/using_config.rs b/examples/using_config.rs deleted file mode 100644 index 034ea1fe..00000000 --- a/examples/using_config.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* -#[cfg(feature = "sled-storage")] -use std::convert::TryFrom; - -#[cfg(feature = "sled-storage")] -use multisql::{parse, sled, Glue, SledStorage}; -*/ - -#[cfg(feature = "sled-storage")] -fn main() { - /*let config = sled::Config::default() - .path("data/using_config") - .temporary(true) - .mode(sled::Mode::HighThroughput); - - let storage = SledStorage::try_from(config).unwrap(); - - let mut glue = Glue::new(storage); - - let sqls = " - CREATE TABLE Glue (id INTEGER); - INSERT INTO Glue VALUES (100); - INSERT INTO Glue VALUES (200); - DROP TABLE Glue; - "; - - for query in parse(sqls).unwrap() { - glue.execute(&query).unwrap(); - }*/ -} - -#[cfg(not(feature = "sled-storage"))] -fn main() {} diff --git a/multisql.sublime-project b/multisql.sublime-project new file mode 100644 index 00000000..84c39544 --- /dev/null +++ b/multisql.sublime-project @@ -0,0 +1,14 @@ +{ + "settings": { + "detect_indentation": true, + "ensure_newline_at_eof_on_save": true, + "tab_size": 2, + "translate_tabs_to_spaces": false + }, + "folders": [ + { + "path": "./", + "folder_exclude_patterns": ["target", "data", ".github"] + } + ] +} diff --git a/src/data/value/cast.rs b/src/data/value/cast.rs index 69c2aa64..9c2ae636 100644 --- a/src/data/value/cast.rs +++ b/src/data/value/cast.rs @@ -187,7 +187,7 @@ impl CastWithRules for Value { } 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_DATE: [i64; 4] = [022, 033, 032, 061]; // 033 should go before 032 const TRY_RULES_TIME: [i64; 2] = [100, 101]; match rule { diff --git a/src/data/value/error.rs b/src/data/value/error.rs index d579da8f..72dfc95b 100644 --- a/src/data/value/error.rs +++ b/src/data/value/error.rs @@ -37,6 +37,8 @@ pub enum ValueError { ParseError(Value, &'static str), #[error("something went wrong with date math")] DateError, // Should avoid throwing + #[error("timestamp error: {0}")] + SpecifiedTimestampError(String), // Should avoid throwing #[error("cannot convert {0:?} into {1}")] CannotConvert(Value, &'static str), diff --git a/src/data/value/methods/function.rs b/src/data/value/methods/function.rs index ea3d60a6..a4017cbe 100644 --- a/src/data/value/methods/function.rs +++ b/src/data/value/methods/function.rs @@ -80,39 +80,6 @@ impl Value { .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); diff --git a/src/data/value/methods/mod.rs b/src/data/value/methods/mod.rs index 4238a104..8e544fa9 100644 --- a/src/data/value/methods/mod.rs +++ b/src/data/value/methods/mod.rs @@ -1,6 +1,7 @@ mod aggregate; mod binary; mod function; +mod timestamp; mod unary; mod utility; diff --git a/src/data/value/methods/timestamp.rs b/src/data/value/methods/timestamp.rs new file mode 100644 index 00000000..92fba13c --- /dev/null +++ b/src/data/value/methods/timestamp.rs @@ -0,0 +1,331 @@ +use { + crate::{Convert, Result, Value, ValueError}, + chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike}, + fstrings::*, + std::{ + cmp::min, + convert::TryInto, + panic, + time::{SystemTime, UNIX_EPOCH}, + }, +}; + +macro_rules! protect_null { + ($protect: expr) => { + match $protect { + Value::Null => return Ok(Value::Null), + other => other, + } + }; +} + +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_now(arguments: Vec) -> Result { + expect_arguments!(arguments, 0); + Value::now() + } + pub fn function_year(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + protect_null!(arguments.remove(0)).year() + } + pub fn function_month(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + protect_null!(arguments.remove(0)).month() + } + pub fn function_day(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + protect_null!(arguments.remove(0)).day() + } + pub fn function_hour(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + protect_null!(arguments.remove(0)).hour() + } + pub fn function_minute(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + protect_null!(arguments.remove(0)).minute() + } + pub fn function_second(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 1); + protect_null!(arguments.remove(0)).second() + } + + pub fn function_timestamp_add(mut arguments: Vec) -> Result { + expect_arguments!(arguments, 3); + arguments.remove(0).date_add( + protect_null!(arguments.remove(0)), + protect_null!(arguments.remove(0)), + ) + } + pub fn function_timestamp_from_parts(arguments: Vec) -> Result { + optional_expect_arguments!(arguments, 1, 6); + protect_null!(arguments + .get(0) + .map(|value| value.clone()) + .unwrap_or(Value::I64(1))) + .date_from_parts( + protect_null!(arguments + .get(1) + .map(|value| value.clone()) + .unwrap_or(Value::I64(1))), + protect_null!(arguments + .get(2) + .map(|value| value.clone()) + .unwrap_or(Value::I64(1))), + protect_null!(arguments + .get(3) + .map(|value| value.clone()) + .unwrap_or(Value::I64(0))), + protect_null!(arguments + .get(4) + .map(|value| value.clone()) + .unwrap_or(Value::I64(0))), + protect_null!(arguments + .get(5) + .map(|value| value.clone()) + .unwrap_or(Value::I64(0))), + ) + } +} + +// System +impl Value { + pub fn now() -> Result { + Ok(Value::I64( + NaiveDateTime::from_timestamp( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as i64, + 0, + ) + .timestamp(), + )) + } +} + +// Parts +impl Value { + 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 minute(self) -> Result { + let datetime: NaiveDateTime = self.convert()?; + Ok(Value::I64(datetime.minute() as i64)) + } + pub fn second(self) -> Result { + let datetime: NaiveDateTime = self.convert()?; + Ok(Value::I64(datetime.second() as i64)) + } +} + +// Math +impl Value { + 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)?; + if amount > 100_000 { + panic!("Looks like you put the amount and timestamp the wrong way around. This will be fixed in future by using different datatypes"); + } + + 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)?; + Ok(Value::I64( + datetime + .with_day(day) + .ok_or(ValueError::DateError)? + .timestamp(), + )) + } + } + _ => Err(ValueError::BadInput(self).into()), + } + } + pub fn date_from_parts( + self, + month: Value, + day: Value, + hour: Value, + minute: Value, + second: Value, + ) -> Result { + let (year, month, day, hour, minute, second): (i64, i64, i64, i64, i64, i64) = ( + self.convert()?, + month.convert()?, + day.convert()?, + hour.convert()?, + minute.convert()?, + second.convert()?, + ); + let (year, month, day, hour, minute, second): (i32, u32, u32, u32, u32, u32) = ( + year.try_into().map_err(|_| ValueError::DateError)?, + month.try_into().map_err(|_| ValueError::DateError)?, + day.try_into().map_err(|_| ValueError::DateError)?, + hour.try_into().map_err(|_| ValueError::DateError)?, + minute.try_into().map_err(|_| ValueError::DateError)?, + second.try_into().map_err(|_| ValueError::DateError)?, + ); + let datetime = panic::catch_unwind(|| { + NaiveDate::from_ymd(year, month, day).and_hms(hour, minute, second) + }) + .map_err(|panic| { + ValueError::SpecifiedTimestampError(f!( + "{year=}, {month=}, {day=},\n{hour=}, {minute=}, {second=}\n{panic=:?}" + )) + })?; + + Ok(Value::I64(datetime.timestamp())) + } +} diff --git a/src/data/value/methods/utility.rs b/src/data/value/methods/utility.rs index 1f451671..d104f798 100644 --- a/src/data/value/methods/utility.rs +++ b/src/data/value/methods/utility.rs @@ -1,11 +1,6 @@ use { crate::{Convert, Result, Value, ValueError}, - chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike}, - std::{ - cmp::min, - convert::TryInto, - time::{SystemTime, UNIX_EPOCH}, - }, + std::cmp::min, }; macro_rules! protect_null { @@ -97,170 +92,6 @@ impl Value { 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); diff --git a/src/executor/alter_row/insert.rs b/src/executor/alter_row/insert.rs index bef0a283..1e000687 100644 --- a/src/executor/alter_row/insert.rs +++ b/src/executor/alter_row/insert.rs @@ -9,11 +9,12 @@ use { }; pub async fn insert( - mut storages: Vec<(String, &mut StorageInner)>, - context: &Context, + storages: &mut Vec<(String, &mut StorageInner)>, + context: &mut Context, table_name: &ObjectName, columns: &Vec, source: &Box, + expect_data: bool, ) -> Result { let table_name = get_name(table_name)?; let Schema { column_defs, .. } = storages[0] @@ -23,7 +24,7 @@ pub async fn insert( .ok_or(ExecuteError::TableNotExists)?; // TODO: Multi storage - let (_, rows) = query(&storages, context, *source.clone()).await?; + let (labels, rows) = query(storages, context, *source.clone()).await?; let column_positions = columns_to_positions(&column_defs, columns)?; let rows = validate(&column_defs, &column_positions, rows)?; @@ -34,9 +35,13 @@ pub async fn insert( let num_rows = rows.len(); - storages[0] - .1 - .insert_data(table_name, rows) - .await - .map(|_| Payload::Insert(num_rows)) + let result = storages[0].1.insert_data(table_name, rows.clone()).await; + + result.map(|_| { + if expect_data { + Payload::Select { labels, rows } + } else { + Payload::Insert(num_rows) + } + }) } diff --git a/src/executor/alter_row/update.rs b/src/executor/alter_row/update.rs index fddb87b7..775e2626 100644 --- a/src/executor/alter_row/update.rs +++ b/src/executor/alter_row/update.rs @@ -3,7 +3,7 @@ use { crate::{ data::{get_name, Schema}, executor::types::{ComplexColumnName, Row as VecRow}, - ExecuteError, MetaRecipe, Payload, PlannedRecipe, RecipeUtilities, Result, Row, + Context, ExecuteError, MetaRecipe, Payload, PlannedRecipe, RecipeUtilities, Result, Row, StorageInner, Value, }, sqlparser::ast::{Assignment, ColumnDef, Expr, ObjectName}, @@ -11,6 +11,7 @@ use { pub async fn update( storage: &mut StorageInner, + context: &Context, table_name: &ObjectName, selection: &Option, assignments: &Vec, @@ -32,7 +33,12 @@ pub async fn update( let filter = selection .clone() - .map(|selection| PlannedRecipe::new(MetaRecipe::new(selection)?, &columns)) + .map(|selection| { + PlannedRecipe::new( + MetaRecipe::new(selection)?.simplify_by_context(context)?, + &columns, + ) + }) .unwrap_or(Ok(PlannedRecipe::TRUE))?; let assignments = assignments @@ -45,7 +51,10 @@ pub async fn update( .iter() .position(|column| column == &column_compare) .ok_or(ExecuteError::ColumnNotFound)?; - let recipe = PlannedRecipe::new(MetaRecipe::new(value.clone())?, &columns)?; + let recipe = PlannedRecipe::new( + MetaRecipe::new(value.clone())?.simplify_by_context(context)?, + &columns, + )?; Ok((index, recipe)) }) .collect::>>()?; diff --git a/src/executor/alter_table/mod.rs b/src/executor/alter_table/mod.rs index 1b694910..dde5afdc 100644 --- a/src/executor/alter_table/mod.rs +++ b/src/executor/alter_table/mod.rs @@ -3,6 +3,7 @@ mod alter_table; mod create_table; mod drop; mod error; +mod truncate; mod validate; use validate::validate; @@ -12,3 +13,4 @@ pub use alter_table::alter_table; pub use create_table::create_table; pub use drop::drop; pub use error::AlterError; +pub use truncate::truncate; diff --git a/src/executor/alter_table/truncate.rs b/src/executor/alter_table/truncate.rs new file mode 100644 index 00000000..18229af3 --- /dev/null +++ b/src/executor/alter_table/truncate.rs @@ -0,0 +1,39 @@ +use { + super::AlterError, + crate::{ + data::{get_name, schema::ColumnDefExt}, + Result, StorageInner, + }, + futures::stream::{self, TryStreamExt}, + sqlparser::ast::ObjectName, +}; + +pub async fn truncate(storage: &mut StorageInner, table_name: &ObjectName) -> Result<()> { + let table_name = get_name(table_name)?; + let schema = storage.fetch_schema(table_name).await?; + + if let Some(schema) = schema { + // TODO: We should be deleting the entry + #[cfg(feature = "auto-increment")] + let result: Result<&mut StorageInner> = stream::iter(schema.column_defs.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?; + + // TODO: Maybe individual "truncate" operation + storage.delete_schema(table_name).await?; + storage.insert_schema(&schema).await?; + Ok(()) + } else { + Err(AlterError::TableNotFound(table_name.to_owned()).into()) + } +} diff --git a/src/executor/alter_table/validate.rs b/src/executor/alter_table/validate.rs index 0832b1e8..ec36bda6 100644 --- a/src/executor/alter_table/validate.rs +++ b/src/executor/alter_table/validate.rs @@ -1,7 +1,14 @@ use { super::AlterError, - crate::{data::schema::ColumnOptionExt, result::Result}, - sqlparser::ast::{ColumnDef, ColumnOption, ColumnOptionDef, DataType}, + crate::{ + data::schema::ColumnOptionExt, + result::Result, + }, + sqlparser::ast::{ + ColumnDef, + ColumnOptionDef, + DataType, + }, }; pub fn validate(column_def: &ColumnDef) -> Result<()> { @@ -12,7 +19,6 @@ pub fn validate(column_def: &ColumnDef) -> Result<()> { .. } = column_def; - // data type if !matches!( data_type, DataType::Boolean | DataType::Int | DataType::Float(_) | DataType::Text @@ -20,32 +26,6 @@ pub fn validate(column_def: &ColumnDef) -> Result<()> { return Err(AlterError::UnsupportedDataType(data_type.to_string()).into()); } - // column option - if let Some(option) = options.iter().find(|ColumnOptionDef { option, .. }| { - !matches!( - option, - ColumnOption::Null - | ColumnOption::NotNull - | ColumnOption::Default(_) - | ColumnOption::Unique { .. } - ) && !option.is_auto_increment() - }) { - return Err(AlterError::UnsupportedColumnOption(option.to_string()).into()); - } - - // unique + data type - if matches!(data_type, DataType::Float(_)) - && options - .iter() - .any(|ColumnOptionDef { option, .. }| matches!(option, ColumnOption::Unique { .. })) - { - return Err(AlterError::UnsupportedDataTypeForUniqueColumn( - name.to_string(), - data_type.to_string(), - ) - .into()); - } - #[cfg(feature = "auto-increment")] if !matches!(data_type, DataType::Int) && options diff --git a/src/executor/execute.rs b/src/executor/execute.rs index 8306fd4d..83d70a41 100644 --- a/src/executor/execute.rs +++ b/src/executor/execute.rs @@ -1,7 +1,7 @@ use { super::{ alter_row::{insert, update}, - alter_table::{create_table, drop}, + alter_table::{create_table, drop, truncate}, query::query, types::ComplexColumnName, }, @@ -11,7 +11,6 @@ use { parse_sql::Query, MetaRecipe, PlannedRecipe, Result, Row, StorageInner, Value, }, - fstrings::*, serde::Serialize, sqlparser::ast::{ColumnDef, SetVariableValue, Statement}, std::convert::TryInto, @@ -51,9 +50,9 @@ pub enum Payload { Delete(usize), Update(usize), DropTable, - #[cfg(feature = "alter-table")] AlterTable, + TruncateTable, } pub async fn execute( @@ -86,6 +85,9 @@ pub async fn execute( Statement::AlterTable { name, operation } => alter_table(storages[0].1, name, operation) .await .map(|_| Payload::AlterTable), + Statement::Truncate { table_name, .. } => truncate(storages[0].1, table_name) + .await + .map(|_| Payload::TruncateTable), //-- Rows Statement::Insert { @@ -93,12 +95,12 @@ pub async fn execute( columns, source, .. - } => insert(storages, &context, table_name, columns, source).await, + } => insert(&mut storages, context, table_name, columns, source, false).await, Statement::Update { table_name, selection, assignments, - } => update(storages[0].1, table_name, selection, assignments).await, + } => update(storages[0].1, &context, table_name, selection, assignments).await, Statement::Delete { table_name, selection, @@ -120,7 +122,12 @@ pub async fn execute( .collect(); let filter = selection .clone() - .map(|selection| PlannedRecipe::new(MetaRecipe::new(selection)?, &columns)) + .map(|selection| { + PlannedRecipe::new( + MetaRecipe::new(selection)?.simplify_by_context(context)?, + &columns, + ) + }) .unwrap_or(Ok(PlannedRecipe::TRUE))?; let keys = storages[0] @@ -155,7 +162,7 @@ pub async fn execute( //- Selection Statement::Query(query_value) => { - let result = query(&storages, &context, *query_value.clone()).await?; + let result = query(&mut storages, context, *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 }; @@ -166,7 +173,6 @@ pub async fn execute( Statement::SetVariable { variable, value, .. } => { - println_f!("{variable=:?} {value=:?}"); let first_value = value.get(0).unwrap(); // Why might one want anything else? let value: Value = match first_value { SetVariableValue::Ident(..) => unimplemented!(), diff --git a/src/executor/query/mod.rs b/src/executor/query/mod.rs index 9811d2ab..eb14c8ed 100644 --- a/src/executor/query/mod.rs +++ b/src/executor/query/mod.rs @@ -4,12 +4,15 @@ pub use select::{join::*, ManualError, PlanError, SelectError}; use { crate::{ - executor::types::LabelsAndRows, macros::warning, result::Result, Cast, Context, MetaRecipe, - RecipeUtilities, StorageInner, Value, + executor::{alter_row::insert, types::LabelsAndRows}, + macros::warning, + result::Result, + Cast, Context, MetaRecipe, Payload, RecipeUtilities, StorageInner, Value, }, + async_recursion::async_recursion, select::select, serde::Serialize, - sqlparser::ast::{Query, SetExpr}, + sqlparser::ast::{Cte, Query, SetExpr, Statement, TableAlias, With}, thiserror::Error as ThisError, }; @@ -29,9 +32,10 @@ pub enum QueryError { NoValues, } +#[async_recursion(?Send)] pub async fn query( - storages: &Vec<(String, &mut StorageInner)>, - context: &Context, + storages: &mut Vec<(String, &mut StorageInner)>, + context: &mut Context, query: Query, ) -> Result { let Query { @@ -39,9 +43,9 @@ pub async fn query( order_by, limit, offset, + with, // TODO (below) fetch: _, - with: _, } = query; let limit: Option = limit .map(|expression| { @@ -59,10 +63,33 @@ pub async fn query( .cast() }) .transpose()?; + + let mut context = context.clone(); + let context = &mut context; // We don't actually want to pass on any changes from here + if let Some(with) = with { + let With { + recursive: _, // Recursive not currently supported + cte_tables, + } = with; + for cte in cte_tables.into_iter() { + let Cte { + alias, + query, + from: _, // What is `from` for? + } = cte; + let TableAlias { + name, + columns: _, // TODO: Columns - Check that number is same and then rename labels + } = alias; + let name = name.value; + let data = self::query(storages, context, query).await?; + context.set_table(name, data); + } + } + let (mut labels, mut rows) = match body { SetExpr::Select(query) => { - let (labels, rows) = select(storages, context, *query, order_by).await?; - + let (labels, rows) = select(&storages, &context, *query, order_by).await?; Ok((labels, rows)) } SetExpr::Values(values) => { @@ -92,6 +119,19 @@ pub async fn query( ) }) } + SetExpr::Insert(Statement::Insert { + table_name, + columns, + source, + .. + }) => { + let inserted = insert(storages, context, &table_name, &columns, &source, true).await?; + if let Payload::Select { labels, rows } = inserted { + Ok((labels, rows.into_iter().map(|row| row.0).collect())) + } else { + unreachable!(); // TODO: Handle + } + } _ => Err(QueryError::QueryNotSupported.into()), // TODO: Other queries }?; diff --git a/src/executor/query/select/join/execute.rs b/src/executor/query/select/join/execute.rs index 71cf876c..47229e4d 100644 --- a/src/executor/query/select/join/execute.rs +++ b/src/executor/query/select/join/execute.rs @@ -2,7 +2,8 @@ use { super::{JoinError, JoinMethod, JoinPlan, JoinType}, crate::{ executor::types::{ComplexColumnName, Row}, - Ingredient, MetaRecipe, Method, PlannedRecipe, Recipe, Result, StorageInner, Value, + Context, Ingredient, MetaRecipe, Method, PlannedRecipe, Recipe, Result, StorageInner, + Value, }, }; @@ -12,6 +13,7 @@ pub struct JoinExecute { pub table: String, pub method: JoinMethod, pub join_type: JoinType, + pub widths: (usize, usize), } impl JoinExecute { @@ -24,12 +26,14 @@ impl JoinExecute { columns, .. } = plan; + let widths = (plane_columns.len(), columns.len()); let method = decide_method(constraint, columns, plane_columns)?; Ok(Self { database, table, method, join_type, + widths, }) } pub fn set_first_table(&mut self) { @@ -45,22 +49,33 @@ impl JoinExecute { pub async fn execute<'a>( self, storages: &Vec<(String, &mut StorageInner)>, + context: &Context, 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 = if let Some((.., context_table_rows)) = context.tables.get(&self.table) { + Ok(context_table_rows.clone()) + } else { + 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) + self.get_rows(storage).await + }?; + self.method.run( + &self.join_type, + self.widths.0, + self.widths.1, + plane_rows, + rows, + ) } } diff --git a/src/executor/query/select/join/manual.rs b/src/executor/query/select/join/manual.rs index 789eef5f..45730009 100644 --- a/src/executor/query/select/join/manual.rs +++ b/src/executor/query/select/join/manual.rs @@ -2,7 +2,7 @@ use { super::{JoinError, JoinType}, crate::{ executor::{types::ComplexTableName, MetaRecipe}, - Result, + Context, Result, }, sqlparser::ast::{Join as AstJoin, JoinConstraint, JoinOperator, TableFactor}, }; @@ -15,10 +15,10 @@ pub struct JoinManual { } impl JoinManual { - pub fn new(join: AstJoin) -> Result { + pub fn new(join: AstJoin, context: &Context) -> Result { let table = Self::table_identity(join.relation)?; let (join_type, constraint) = Self::convert_join(join.join_operator)?; - // println!("(join/manual.rs) Constraint: {:?}", constraint); + let constraint = constraint.simplify_by_context(context)?; Ok(Self { table, join_type, diff --git a/src/executor/query/select/join/method.rs b/src/executor/query/select/join/method.rs index 355fbb16..b91d8041 100644 --- a/src/executor/query/select/join/method.rs +++ b/src/executor/query/select/join/method.rs @@ -38,6 +38,8 @@ impl JoinMethod { pub fn run( self, join: &JoinType, + left_width: usize, + right_width: usize, mut plane_rows: Vec, mut self_rows: Vec, ) -> Result> { @@ -56,8 +58,6 @@ impl JoinMethod { 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| { @@ -116,7 +116,7 @@ impl JoinMethod { self_trust_ordered, } => { if !plane_trust_ordered { - plane_rows.sort_unstable_by(|row_l, row_r| { + plane_rows.par_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))) @@ -149,7 +149,7 @@ impl JoinMethod { .peekable(); if !self_trust_ordered { - self_rows.sort_unstable_by(|row_l, row_r| { + self_rows.par_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))) @@ -181,19 +181,6 @@ impl JoinMethod { .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![]; @@ -234,7 +221,7 @@ impl JoinMethod { .map(|(_, left_rows)| { left_rows .into_iter() - .map(|left| join_parts(left, vec![Value::Null; right_len])) + .map(|left| join_parts(left, vec![Value::Null; right_width])) .collect::>() }) .reduce(|mut all, set| { @@ -274,7 +261,7 @@ impl JoinMethod { .map(|(_, right_rows)| { right_rows .into_iter() - .map(|right| join_parts(vec![Value::Null; left_len], right)) + .map(|right| join_parts(vec![Value::Null; left_width], right)) .collect::>() }) .reduce(|mut all, set| { diff --git a/src/executor/query/select/join/plan.rs b/src/executor/query/select/join/plan.rs index f3db2b5f..972143f1 100644 --- a/src/executor/query/select/join/plan.rs +++ b/src/executor/query/select/join/plan.rs @@ -6,7 +6,7 @@ use { types::{ComplexColumnName, ComplexTableName}, MetaRecipe, }, - JoinError, Result, StorageInner, + Context, JoinError, Result, StorageInner, }, std::cmp::Ordering, }; @@ -41,13 +41,14 @@ impl JoinPlan { pub async fn new<'a>( join_manual: JoinManual, storages: &Vec<(String, &mut StorageInner)>, + context: &Context, ) -> Result { let JoinManual { table, constraint, join_type, } = join_manual; - let columns = get_columns(storages, table.clone()).await?; + let columns = get_columns(storages, table.clone(), context).await?; let ComplexTableName { database, name: table, @@ -91,25 +92,36 @@ impl JoinPlan { async fn get_columns( storages: &Vec<(String, &mut StorageInner)>, table: ComplexTableName, + context: &Context, ) -> 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()))?; + if let Some((context_table_labels, ..)) = context.tables.get(&table.name) { + Ok(context_table_labels + .iter() + .map(|name| ComplexColumnName { + table: table.clone(), + name: name.clone(), + }) + .collect::>()) + } else { + 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::>()) + 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 index 1f4e531d..0b08b919 100644 --- a/src/executor/query/select/manual/mod.rs +++ b/src/executor/query/select/manual/mod.rs @@ -95,7 +95,7 @@ impl Manual { let mut joins = from .joins .into_iter() - .map(|join| JoinManual::new(join)) + .map(|join| JoinManual::new(join, context)) .collect::>>()?; joins.push(main); Ok(joins) diff --git a/src/executor/query/select/mod.rs b/src/executor/query/select/mod.rs index efc46cca..5bf4e5ac 100644 --- a/src/executor/query/select/mod.rs +++ b/src/executor/query/select/mod.rs @@ -62,7 +62,7 @@ pub async fn select( let rows = stream::iter(joins) .map(Ok) .try_fold(vec![], |rows, join| async { - join.execute(storages, rows).await + join.execute(storages, context, rows).await }) .await?; diff --git a/src/executor/query/select/plan/mod.rs b/src/executor/query/select/plan/mod.rs index 8ecb38e1..9bfbfa14 100644 --- a/src/executor/query/select/plan/mod.rs +++ b/src/executor/query/select/plan/mod.rs @@ -51,7 +51,7 @@ impl Plan { let mut joins: Vec = join_all( joins .into_iter() - .map(|join| JoinPlan::new(join, storages)) + .map(|join| JoinPlan::new(join, storages, context)) .collect::>(), ) .await diff --git a/src/executor/recipe/from.rs b/src/executor/recipe/from.rs index d9eaa46a..b898991f 100644 --- a/src/executor/recipe/from.rs +++ b/src/executor/recipe/from.rs @@ -25,12 +25,16 @@ impl TryIntoMethod for String { "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), + "MINUTE" => Ok(Value::function_hour), + "SECOND" => Ok(Value::function_hour), + + "DATEADD" => Ok(Value::function_timestamp_add), + "DATEFROMPARTS" => Ok(Value::function_timestamp_from_parts), "ROUND" => Ok(Value::function_round), "POW" => Ok(Value::function_pow), diff --git a/src/executor/recipe/mod.rs b/src/executor/recipe/mod.rs index dd3a325a..cb44af1c 100644 --- a/src/executor/recipe/mod.rs +++ b/src/executor/recipe/mod.rs @@ -117,7 +117,6 @@ impl RecipeUtilities for Recipe { if let Recipe::Ingredient(Ingredient::Value(value)) = self { Some(value.clone()) } else { - //println!("Remaining recipe: {:?}", self); None } } diff --git a/src/executor/recipe/planned.rs b/src/executor/recipe/planned.rs index ce37e726..e618dffa 100644 --- a/src/executor/recipe/planned.rs +++ b/src/executor/recipe/planned.rs @@ -6,6 +6,7 @@ use { executor::types::{ComplexColumnName, Row}, Result, Value, }, + fstrings::*, }; #[derive(Debug, Clone)] @@ -65,7 +66,7 @@ impl PlannedRecipe { } } pub fn confirm_join_constraint(&self, plane_row: &Row, self_row: &Row) -> Result { - // Very crucuial to have performant, needs *a lot* of optimisation. + // Very crucial to have performant, needs *a lot* of optimisation. // This is currently not good enough. // For a join such as: /* @@ -112,7 +113,12 @@ impl PlannedRecipe { .map(|index| { Ok(row .get(index) - .ok_or(RecipeError::MissingColumn(Vec::new() /*unreachable*/))? + .ok_or_else(|| { + RecipeError::MissingColumn(vec![ + String::from("Unreachable"), + f!("{row_len=:?} {index=:?}", row_len = row.len()), + ]) + })? .clone()) }) .unwrap_or(Ok(Value::Null)) diff --git a/src/glue/mod.rs b/src/glue/mod.rs index 6ba4169f..a4da3499 100644 --- a/src/glue/mod.rs +++ b/src/glue/mod.rs @@ -1,28 +1,52 @@ #![cfg(feature = "sled-storage")] use { crate::{ - execute, parse, parse_single, Cast, ExecuteError, Payload, Query, Result, Row, Storage, - StorageInner, Value, WIPError, + execute, + parse, + parse_single, + Payload, + Query, + Result, + Row, + Storage, + StorageInner, + Value, + WIPError, }, futures::executor::block_on, - serde_json::{json, value::Value as JSONValue}, sqlparser::ast::{ - Expr, Ident, ObjectName, Query as AstQuery, SetExpr, Statement, Value as AstValue, Values, + Expr, + Ident, + ObjectName, + Query as AstQuery, + SetExpr, + Statement, + Value as AstValue, + Values, + }, + std::{ + collections::HashMap, + fmt::Debug, }, - std::collections::HashMap, }; +mod select; mod value; pub(crate) type Variables = HashMap; -#[derive(Default)] + +#[derive(Default, Debug, Clone)] pub struct Context { pub variables: Variables, + pub tables: HashMap, Vec>)>, } impl Context { pub fn set_variable(&mut self, name: String, value: Value) { self.variables.insert(name, value); } + pub fn set_table(&mut self, name: String, data: (Vec, Vec>)) { + self.tables.insert(name, data); + } } pub struct Glue { @@ -30,6 +54,7 @@ pub struct Glue { context: Option, } +// New impl Glue { pub fn new_multi(storages: Vec<(String, Storage)>) -> Self { let context = Some(Context::default()); @@ -47,7 +72,25 @@ impl Glue { pub fn new(name: String, storage: Storage) -> Self { Self::new_multi(vec![(name, storage)]) } +} +// Modify +impl Glue { + pub fn take_context(&mut self) -> Context { + self.context + .take() + .expect("Unreachable: Context wasn't replaced!") + } + pub fn replace_context(&mut self, context: Context) { + self.context.replace(context); + } + pub fn set_context(&mut self, context: Context) { + self.context = Some(context); + } +} + +// Execute +impl Glue { pub fn execute_parsed(&mut self, query: Query) -> Result { let mut storages: Vec<(String, Box)> = self .storages @@ -59,10 +102,7 @@ impl Glue { .map(|(name, storage)| (name.clone(), &mut **storage)) .collect(); - let mut context = self - .context - .take() - .expect("Unreachable: Context wasn't replaced!"); + let mut context = self.take_context(); let result = block_on(execute(give_storages, &mut context, &query)); @@ -71,7 +111,7 @@ impl Glue { .zip(storages) .for_each(|((_name, storage), (_name_2, taken))| storage.replace(taken)); - self.context.replace(context); + self.replace_context(context); result } @@ -93,87 +133,6 @@ impl Glue { parse(query).map_err(|error| WIPError::Debug(format!("{:?}", error)).into()) } - #[cfg(feature = "expanded-api")] - pub fn select_as_string(&mut self, query: &str) -> Result>> { - // TODO: Make this more efficient and not affect database - if let Payload::Select { labels, rows } = self.execute(query)? { - Ok(vec![labels] - .into_iter() - .chain( - rows.into_iter() - .map(|row| { - row.0 - .into_iter() - .map(|value| value.cast()) - .collect::>>() - }) - .collect::>>>()?, - ) - .collect()) - } else { - Err(ExecuteError::QueryNotSupported.into()) - } - } - - #[cfg(feature = "expanded-api")] - pub fn select_as_json(&mut self, query: &str) -> Result { - // TODO: Make this more efficient and not affect database if not select by converting earlier - if let Payload::Select { labels, rows } = self.execute(query)? { - let array = JSONValue::Array( - rows.into_iter() - .map(|row| { - JSONValue::Object( - row.0 - .into_iter() - .enumerate() - .map(|(index, cell)| (labels[index].clone(), cell.into())) - .collect::>(), - ) - }) - .collect(), - ); - Ok(array.to_string()) - } else { - Err(ExecuteError::QueryNotSupported.into()) - } - } - #[cfg(feature = "expanded-api")] - pub fn select_as_json_with_headers(&mut self, query: &str) -> String { - // TODO: Make this more efficient and not affect database if not select by converting earlier - let mut result = || -> Result<_> { - if let Payload::Select { labels, rows } = self.execute(query)? { - let array = JSONValue::Array( - rows.into_iter() - .map(|row| { - JSONValue::Object( - row.0 - .into_iter() - .enumerate() - .map(|(index, cell)| (labels[index].clone(), cell.into())) - .collect::>(), - ) - }) - .collect(), - ); - Ok(json!({ - "labels": JSONValue::from(labels), - "data": array - })) - } else { - Err(ExecuteError::QueryNotSupported.into()) - } - }; - match result() { - Ok(result) => result, - Err(error) => { - println!("{:?}", error); - json!({"error": error.to_string()}) - } - } - .to_string() - } - - #[cfg(feature = "expanded-api")] pub fn insert_vec( &mut self, table_name: String, diff --git a/src/glue/select.rs b/src/glue/select.rs new file mode 100644 index 00000000..9fd4b59a --- /dev/null +++ b/src/glue/select.rs @@ -0,0 +1,114 @@ +use { + super::Glue, + crate::{ + Cast, + ExecuteError, + Payload, + Result, + }, + serde_json::{ + json, + value::Value as JSONValue, + }, +}; + +impl Glue { + pub fn select_as_json(&mut self, query: &str) -> Result { + // TODO: Make this more efficient and not affect database if not select by converting earlier + if let Payload::Select { labels, rows } = self.execute(query)? { + let array = JSONValue::Array( + rows.into_iter() + .map(|row| { + JSONValue::Object( + row.0 + .into_iter() + .enumerate() + .map(|(index, cell)| (labels[index].clone(), cell.into())) + .collect::>(), + ) + }) + .collect(), + ); + Ok(array.to_string()) + } else { + Err(ExecuteError::QueryNotSupported.into()) + } + } + + pub fn select_as_json_with_headers(&mut self, query: &str) -> String { + // TODO: Make this more efficient and not affect database if not select by converting earlier + let mut result = || -> Result<_> { + if let Payload::Select { labels, rows } = self.execute(query)? { + let array = JSONValue::Array( + rows.into_iter() + .map(|row| { + JSONValue::Object( + row.0 + .into_iter() + .enumerate() + .map(|(index, cell)| (labels[index].clone(), cell.into())) + .collect::>(), + ) + }) + .collect(), + ); + Ok(json!({ + "labels": JSONValue::from(labels), + "data": array + })) + } else { + Err(ExecuteError::QueryNotSupported.into()) + } + }; + match result() { + Ok(result) => result, + Err(error) => json!({"error": error.to_string()}), + } + .to_string() + } + + pub fn select_as_string(&mut self, query: &str) -> Result>> { + // TODO: Make this more efficient and not affect database + if let Payload::Select { labels, rows } = self.execute(query)? { + Ok(vec![labels] + .into_iter() + .chain( + rows.into_iter() + .map(|row| { + row.0 + .into_iter() + .map(|value| value.cast()) + .collect::>>() + }) + .collect::>>>()?, + ) + .collect()) + } else { + Err(ExecuteError::QueryNotSupported.into()) + } + } + + pub fn select_as_csv(&mut self, query: &str) -> Result { + // TODO: Don't use `unwrap()` + if let Payload::Select { labels, rows } = self.execute(query)? { + { + let mut writer = csv::Writer::from_writer(vec![]); + writer.write_record(labels).unwrap(); + for row in rows.into_iter() { + for field in row.0.into_iter() { + let string: String = field.cast()?; + writer.write_field(string).unwrap(); + } + writer.write_record(None::<&[u8]>).unwrap(); + } + let bytes = writer.into_inner().unwrap(); + let string = String::from_utf8(bytes).unwrap(); + Some(string) + } + .map(Ok) + .unwrap() + } else { + Err(ExecuteError::QueryNotSupported.into()) + } + } +} diff --git a/src/utils/indexmap.rs b/src/utils/indexmap.rs deleted file mode 100644 index 702e0a30..00000000 --- a/src/utils/indexmap.rs +++ /dev/null @@ -1,47 +0,0 @@ -use indexmap::map::{IntoIter, Keys}; -use std::cmp::Eq; -use std::hash::Hash; - -/// HashMap which provides -/// 1. Immutable APIs -/// 2. Preserving insertion order -pub struct IndexMap(indexmap::IndexMap); - -impl IndexMap { - pub fn new() -> Self { - Self(indexmap::IndexMap::new()) - } - - pub fn insert(mut self, key: K, value: V) -> (Self, Option) { - let existing = self.0.insert(key, value); - - (self, existing) - } - - pub fn get(&self, key: &K) -> Option<&V> { - self.0.get(key) - } - - pub fn keys(&self) -> Keys { - self.0.keys() - } - - pub fn len(&self) -> usize { - self.0.len() - } -} - -impl Default for IndexMap { - fn default() -> Self { - Self::new() - } -} - -impl IntoIterator for IndexMap { - type Item = (K, V); - type IntoIter = IntoIter; - - fn into_iter(self) -> Self::IntoIter { - self.0.into_iter() - } -} diff --git a/src/utils/or_stream.rs b/src/utils/or_stream.rs deleted file mode 100644 index 6e54a89f..00000000 --- a/src/utils/or_stream.rs +++ /dev/null @@ -1,114 +0,0 @@ -use core::cmp::max; -use core::pin::Pin; -use futures::ready; -use futures::stream::Stream; -use futures::task::{Context, Poll}; -use pin_project::pin_project; - -#[derive(Debug)] -enum State { - Initial, - InSt1, - InSt2, -} - -#[pin_project] -#[derive(Debug)] -#[must_use = "streams do nothing unless polled"] -pub struct OrStream { - #[pin] - stream1: St1, - #[pin] - stream2: St2, - state: State, -} - -use State::{InSt1, InSt2, Initial}; - -impl OrStream -where - St1: Stream, - St2: Stream, -{ - pub fn new(stream1: St1, stream2: St2) -> Self { - Self { - stream1, - stream2, - state: Initial, - } - } -} - -impl Stream for OrStream -where - St1: Stream, - St2: Stream, -{ - type Item = St1::Item; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.project(); - - match this.state { - Initial => match ready!(this.stream1.poll_next(cx)) { - item @ Some(_) => { - *this.state = InSt1; - - Poll::Ready(item) - } - None => { - *this.state = InSt2; - - this.stream2.poll_next(cx) - } - }, - InSt1 => this.stream1.poll_next(cx), - InSt2 => this.stream2.poll_next(cx), - } - } - - fn size_hint(&self) -> (usize, Option) { - match self.state { - Initial => match self.stream1.size_hint() { - (_, Some(0)) => self.stream2.size_hint(), - (0, i1_high) => { - let (i2_low, i2_high) = self.stream2.size_hint(); - let low = if i2_low > 0 { 1 } else { 0 }; - - let high = i1_high.and_then(|h1| i2_high.map(|h2| max(h1, h2))); - (low, high) - } - i1_hint => i1_hint, - }, - InSt1 => self.stream1.size_hint(), - InSt2 => self.stream2.size_hint(), - } - } -} - -#[cfg(test)] -mod tests { - use super::OrStream; - use futures::executor::block_on; - use futures::stream::{empty, once, StreamExt}; - - #[test] - fn basic() { - block_on(async move { - let s1 = once(async { 1 }); - let s2 = once(async { 3 }); - let v = OrStream::new(s1, s2).collect::>().await; - assert_eq!(vec![1], v); - - let s1 = empty(); - let s2 = once(async { 3 }); - let v = OrStream::new(s1, s2).collect::>().await; - assert_eq!(vec![3], v); - - let s1 = once(async { 3 }); - let s2 = empty(); - let v = OrStream::new(s1, s2).collect::>().await; - assert_eq!(vec![3], v); - }); - } -} diff --git a/src/utils/vector.rs b/src/utils/vector.rs deleted file mode 100644 index abc244e3..00000000 --- a/src/utils/vector.rs +++ /dev/null @@ -1,54 +0,0 @@ -use std::convert::From; -use std::vec::IntoIter; - -pub struct Vector(Vec); - -impl Vector { - pub fn new() -> Self { - Self(vec![]) - } - - pub fn push(mut self, value: T) -> Self { - self.0.push(value); - - self - } - - #[cfg(all(feature = "alter-table", feature = "sled-storage"))] - pub fn update(mut self, i: usize, value: T) -> Self { - self.0[i] = value; - - self - } - - pub fn get(&self, i: usize) -> Option<&T> { - self.0.get(i) - } -} - -impl Default for Vector { - fn default() -> Self { - Self::new() - } -} - -impl IntoIterator for Vector { - type Item = T; - type IntoIter = IntoIter; - - fn into_iter(self) -> Self::IntoIter { - self.0.into_iter() - } -} - -impl From> for Vector { - fn from(vector: Vec) -> Self { - Self(vector) - } -} - -impl From> for Vec { - fn from(vector: Vector) -> Self { - vector.0 - } -} diff --git a/tests/functionality/api/csv.rs b/tests/functionality/api/csv.rs new file mode 100644 index 00000000..21fc60f4 --- /dev/null +++ b/tests/functionality/api/csv.rs @@ -0,0 +1,28 @@ +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + crate::util_macros::make_basic_table!(glue); + + assert_eq!( + glue.select_as_csv("SELECT * FROM basic"), + Ok(String::from("a\n1\n")) + ); + + glue.execute("INSERT INTO basic VALUES (2),(3),(4),(5)") + .unwrap(); + + assert_eq!( + glue.select_as_csv("SELECT * FROM basic ORDER BY a"), + Ok(String::from("a\n1\n2\n3\n4\n5\n")) + ); + + glue.execute("ALTER TABLE basic ADD COLUMN empty FLOAT NULL") + .unwrap(); + + assert_eq!( + glue.select_as_csv("SELECT * FROM basic ORDER BY a"), + Ok(String::from( + "a,empty\n1,NULL\n2,NULL\n3,NULL\n4,NULL\n5,NULL\n" + )) + ); + }) +); diff --git a/tests/functionality/api/mod.rs b/tests/functionality/api/mod.rs new file mode 100644 index 00000000..1ce65ed0 --- /dev/null +++ b/tests/functionality/api/mod.rs @@ -0,0 +1 @@ +crate::util_macros::make_all!(functionality::api, [csv]); diff --git a/tests/functionality/mod.rs b/tests/functionality/mod.rs index c135842b..d8e3668b 100644 --- a/tests/functionality/mod.rs +++ b/tests/functionality/mod.rs @@ -1,8 +1 @@ -pub(crate) mod statement; - -macro_rules! all { - ($storage: ident) => { - crate::functionality::statement::all!($storage); - }; -} -pub(crate) use all; +crate::util_macros::make_all!(functionality, [statement, query, api]); diff --git a/tests/functionality/query/mod.rs b/tests/functionality/query/mod.rs new file mode 100644 index 00000000..d12d48e2 --- /dev/null +++ b/tests/functionality/query/mod.rs @@ -0,0 +1 @@ +crate::util_macros::make_all!(functionality::query, [with]); diff --git a/tests/functionality/query/with.rs b/tests/functionality/query/with.rs new file mode 100644 index 00000000..57e66f28 --- /dev/null +++ b/tests/functionality/query/with.rs @@ -0,0 +1,81 @@ +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + crate::util_macros::make_basic_table!(glue); + + crate::util_macros::assert_select!(glue, r#" + WITH cte AS ( + SELECT + a + FROM + basic + ) + SELECT + a + FROM + cte + "# => a = I64: (1)); + + crate::util_macros::assert_select!(glue, r#" + WITH cte_0 AS ( + SELECT + a + FROM + basic + ), cte_1 AS ( + SELECT + a + FROM + cte_0 + ) + SELECT + a + FROM + cte_1 + "# => a = I64: (1)); + + glue.execute( + r#" + WITH cte_0 AS ( + SELECT + a + FROM + cte_1 + ), cte_1 AS ( + SELECT + a + FROM + basic + ) + SELECT + a + FROM + cte_0 + "#, + ) + .expect_err("CTE is not simultaneous"); + + glue.execute("CREATE TABLE basic_insert (a INTEGER)") + .unwrap(); + + crate::util_macros::assert_select!(glue, r#" + WITH basic_inserted AS ( + INSERT INTO basic_insert + SELECT + a + FROM + basic + ) + SELECT + a + FROM + basic_inserted + "# => a = I64: (1)); + + crate::util_macros::assert_select!(glue, r#" + SELECT + a + FROM + basic_insert + "# => a = I64: (1)); + }) +); diff --git a/tests/functionality/statement/create/mod.rs b/tests/functionality/statement/create/mod.rs index 70dd7431..e20c88bd 100644 --- a/tests/functionality/statement/create/mod.rs +++ b/tests/functionality/statement/create/mod.rs @@ -1,8 +1 @@ -pub(crate) mod table; - -macro_rules! all { - ($storage: ident) => { - crate::functionality::statement::create::table::all!($storage); - }; -} -pub(crate) use all; +crate::util_macros::make_all!(functionality::statement::create, [table]); diff --git a/tests/functionality/statement/create/table/mod.rs b/tests/functionality/statement/create/table/mod.rs index 72dfab7b..1f23e910 100644 --- a/tests/functionality/statement/create/table/mod.rs +++ b/tests/functionality/statement/create/table/mod.rs @@ -1,17 +1,12 @@ -macro_rules! all { - ($storage: ident) => { - #[test] - fn create_table() { - let mut glue = $storage(); - glue.execute( - r#" - CREATE TABLE basic ( - a INTEGER - ) - "#, - ) - .expect("CREATE TABLE basic"); - } - }; -} -pub(crate) use all; +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + glue.execute( + r#" + CREATE TABLE basic ( + a INTEGER + ) + "#, + ) + .expect("CREATE TABLE basic"); + }) +); diff --git a/tests/functionality/statement/insert.rs b/tests/functionality/statement/insert.rs new file mode 100644 index 00000000..3ecbbd16 --- /dev/null +++ b/tests/functionality/statement/insert.rs @@ -0,0 +1,22 @@ +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + glue.execute( + r#" + CREATE TABLE basic ( + a INTEGER + ) + "#, + ) + .expect("CREATE TABLE basic"); + glue.execute( + r#" + INSERT INTO basic ( + a + ) VALUES ( + 1 + ) + "#, + ) + .expect("INSERT basic"); + }) +); diff --git a/tests/functionality/statement/insert/mod.rs b/tests/functionality/statement/insert/mod.rs deleted file mode 100644 index 9cdf8de6..00000000 --- a/tests/functionality/statement/insert/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -macro_rules! all { - ($storage: ident) => { - #[test] - fn insert() { - let mut glue = $storage(); - glue.execute( - r#" - CREATE TABLE basic ( - a INTEGER - ) - "#, - ) - .expect("CREATE TABLE basic"); - glue.execute( - r#" - INSERT INTO basic ( - a - ) VALUES ( - 1 - ) - "#, - ) - .expect("INSERT basic"); - } - }; -} -pub(crate) use all; diff --git a/tests/functionality/statement/mod.rs b/tests/functionality/statement/mod.rs index 775a3b40..c58f203b 100644 --- a/tests/functionality/statement/mod.rs +++ b/tests/functionality/statement/mod.rs @@ -1,14 +1,4 @@ -pub(crate) mod create; -pub(crate) mod insert; -pub(crate) mod select; -pub(crate) mod set; - -macro_rules! all { - ($storage: ident) => { - crate::functionality::statement::set::all!($storage); - crate::functionality::statement::select::all!($storage); - crate::functionality::statement::insert::all!($storage); - crate::functionality::statement::create::all!($storage); - }; -} -pub(crate) use all; +crate::util_macros::make_all!( + functionality::statement, + [create, insert, select, truncate, set] +); diff --git a/tests/functionality/statement/select.rs b/tests/functionality/statement/select.rs new file mode 100644 index 00000000..d170a125 --- /dev/null +++ b/tests/functionality/statement/select.rs @@ -0,0 +1,31 @@ +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + glue.execute( + r#" + CREATE TABLE basic ( + a INTEGER + ) + "#, + ) + .expect("CREATE TABLE basic"); + glue.execute( + r#" + INSERT INTO basic ( + a + ) VALUES ( + 1 + ) + "#, + ) + .expect("INSERT basic"); + glue.execute( + r#" + SELECT + a + FROM + basic + "#, + ) + .expect("SELECT basic"); + }) +); diff --git a/tests/functionality/statement/select/mod.rs b/tests/functionality/statement/select/mod.rs deleted file mode 100644 index 6f40de28..00000000 --- a/tests/functionality/statement/select/mod.rs +++ /dev/null @@ -1,36 +0,0 @@ -macro_rules! all { - ($storage: ident) => { - #[test] - fn select() { - let mut glue = $storage(); - glue.execute( - r#" - CREATE TABLE basic ( - a INTEGER - ) - "#, - ) - .expect("CREATE TABLE basic"); - glue.execute( - r#" - INSERT INTO basic ( - a - ) VALUES ( - 1 - ) - "#, - ) - .expect("INSERT basic"); - glue.execute( - r#" - SELECT - a - FROM - basic - "#, - ) - .expect("SELECT basic"); - } - }; -} -pub(crate) use all; diff --git a/tests/functionality/statement/set.rs b/tests/functionality/statement/set.rs new file mode 100644 index 00000000..f114e78f --- /dev/null +++ b/tests/functionality/statement/set.rs @@ -0,0 +1,36 @@ +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + use multisql::*; + glue.execute("SET @variable = 1;").expect("SET variable"); + assert_eq!( + glue.execute("VALUES (@variable)"), + Ok(Payload::Select { + labels: vec![String::from("unnamed_0")], + rows: vec![Row(vec![Value::I64(1)])] + }) + ); + crate::util_macros::make_basic_table!(glue); + + assert_eq!( + glue.execute("SELECT a + @variable FROM basic"), + Ok(Payload::Select { + labels: vec![String::from("unnamed_0")], + rows: vec![Row(vec![Value::I64(2)])] + }) + ); + assert_eq!( + glue.execute("SELECT a FROM basic WHERE @variable = 1"), + Ok(Payload::Select { + labels: vec![String::from("a")], + rows: vec![Row(vec![Value::I64(1)])] + }) + ); + assert_eq!( + glue.execute("SELECT a FROM basic WHERE @variable = 0"), + Ok(Payload::Select { + labels: vec![String::from("a")], + rows: vec![] + }) + ); + }) +); diff --git a/tests/functionality/statement/set/mod.rs b/tests/functionality/statement/set/mod.rs deleted file mode 100644 index 764cee67..00000000 --- a/tests/functionality/statement/set/mod.rs +++ /dev/null @@ -1,41 +0,0 @@ -macro_rules! all { - ($storage: ident) => { - #[test] - fn variable() { - use multisql::*; - let mut glue = $storage(); - glue.execute("SET @variable = 1;").expect("SET variable"); - assert_eq!( - glue.execute("VALUES (@variable)"), - Ok(Payload::Select { - labels: vec![String::from("unnamed_0")], - rows: vec![Row(vec![Value::I64(1)])] - }) - ); - crate::util_macros::make_basic_table!(glue); - - assert_eq!( - glue.execute("SELECT a + @variable FROM basic"), - Ok(Payload::Select { - labels: vec![String::from("unnamed_0")], - rows: vec![Row(vec![Value::I64(2)])] - }) - ); - assert_eq!( - glue.execute("SELECT a FROM basic WHERE @variable = 1"), - Ok(Payload::Select { - labels: vec![String::from("a")], - rows: vec![Row(vec![Value::I64(1)])] - }) - ); - assert_eq!( - glue.execute("SELECT a FROM basic WHERE @variable = 0"), - Ok(Payload::Select { - labels: vec![String::from("a")], - rows: vec![] - }) - ); - } - }; -} -pub(crate) use all; diff --git a/tests/functionality/statement/truncate.rs b/tests/functionality/statement/truncate.rs new file mode 100644 index 00000000..cc3a8238 --- /dev/null +++ b/tests/functionality/statement/truncate.rs @@ -0,0 +1,33 @@ +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + glue.execute( + r#" + CREATE TABLE basic ( + a INTEGER + ) + "#, + ) + .expect("CREATE TABLE basic"); + glue.execute( + r#" + INSERT INTO basic ( + a + ) VALUES ( + 1 + ) + "#, + ) + .expect("INSERT basic"); + + crate::util_macros::assert_select!(glue, "SELECT a FROM basic" => a = I64: (1)); + + glue.execute( + r#" + TRUNCATE TABLE basic + "#, + ) + .expect("TRUNCATE basic"); + + crate::util_macros::assert_select!(glue, "SELECT a FROM basic" => a = I64: ); + }) +); diff --git a/tests/original/basic.rs b/tests/original/basic.rs index fb54b305..67726460 100644 --- a/tests/original/basic.rs +++ b/tests/original/basic.rs @@ -1,63 +1,54 @@ -macro_rules! all { - ($storage: ident) => { - use fstrings::*; - #[test] - fn basic() { - let basic_table = |num: u16| { - f!(r#" - CREATE TABLE basic_{num} ( - id INTEGER, - num INTEGER, - name TEXT - ) - "#) - }; - let mut glue = $storage(); - glue.execute(&basic_table(0)).unwrap(); - glue.execute(&basic_table(1)).unwrap(); - - glue.execute("INSERT INTO basic_0 (id, num, name) VALUES (1, 2, 'Hello')") - .unwrap(); - glue.execute("INSERT INTO basic_0 (id, num, name) VALUES (1, 9, 'World')") - .unwrap(); - glue.execute( - "INSERT INTO basic_0 (id, num, name) VALUES (3, 4, 'Great'), (4, 7, 'Job')", +crate::util_macros::testcase!( + (|mut glue: multisql::Glue| { + let basic_table = |num: u16| { + use fstrings::*; + f!(r#" + CREATE TABLE basic_{num} ( + id INTEGER, + num INTEGER, + name TEXT ) + "#) + }; + glue.execute(&basic_table(0)).unwrap(); + glue.execute(&basic_table(1)).unwrap(); + + glue.execute("INSERT INTO basic_0 (id, num, name) VALUES (1, 2, 'Hello')") + .unwrap(); + glue.execute("INSERT INTO basic_0 (id, num, name) VALUES (1, 9, 'World')") + .unwrap(); + glue.execute("INSERT INTO basic_0 (id, num, name) VALUES (3, 4, 'Great'), (4, 7, 'Job')") + .unwrap(); + glue.execute("INSERT INTO basic_1 (id, num, name) SELECT id, num, name FROM basic_0") .unwrap(); - glue.execute("INSERT INTO basic_1 (id, num, name) SELECT id, num, name FROM basic_0") - .unwrap(); - glue.execute("CREATE TABLE basic_a (id INTEGER);").unwrap(); - glue.execute("INSERT INTO basic_a (id) SELECT id FROM basic_0") - .unwrap(); + glue.execute("CREATE TABLE basic_a (id INTEGER);").unwrap(); + glue.execute("INSERT INTO basic_a (id) SELECT id FROM basic_0") + .unwrap(); - crate::util_macros::assert_select!(glue, "SELECT * FROM basic_a" => id = I64: (1), (1), (3), (4)); + crate::util_macros::assert_select!(glue, "SELECT * FROM basic_a" => id = I64: (1), (1), (3), (4)); - crate::util_macros::assert_select!(glue, - "SELECT id, num, name FROM basic_0" => - id = I64, num = I64, name = Str: - (1, 2, String::from("Hello")), - (1, 9, String::from("World")), - (3, 4, String::from("Great")), - (4, 7, String::from("Job")) - ); + crate::util_macros::assert_select!(glue, + "SELECT id, num, name FROM basic_0" => + id = I64, num = I64, name = Str: + (1, 2, String::from("Hello")), + (1, 9, String::from("World")), + (3, 4, String::from("Great")), + (4, 7, String::from("Job")) + ); - crate::util_macros::assert_select!(glue, - "SELECT id, num, name FROM basic_1" => - id = I64, num = I64, name = Str: - (1, 2, String::from("Hello")), - (1, 9, String::from("World")), - (3, 4, String::from("Great")), - (4, 7, String::from("Job")) - ); + crate::util_macros::assert_select!(glue, + "SELECT id, num, name FROM basic_1" => + id = I64, num = I64, name = Str: + (1, 2, String::from("Hello")), + (1, 9, String::from("World")), + (3, 4, String::from("Great")), + (4, 7, String::from("Job")) + ); - glue - .execute("UPDATE basic_0 SET id = 2") - .unwrap(); + glue.execute("UPDATE basic_0 SET id = 2").unwrap(); - crate::util_macros::assert_select!(glue, "SELECT id FROM basic_0" => id = I64: (2), (2), (2), (2)); - crate::util_macros::assert_select!(glue, "SELECT id, num FROM basic_0" => id = I64, num = I64: (2, 2), (2, 9), (2, 4), (2, 7)); - } - }; -} -pub(crate) use all; + crate::util_macros::assert_select!(glue, "SELECT id FROM basic_0" => id = I64: (2), (2), (2), (2)); + crate::util_macros::assert_select!(glue, "SELECT id, num FROM basic_0" => id = I64, num = I64: (2, 2), (2, 9), (2, 4), (2, 7)); + }) +); diff --git a/tests/original/mod.rs b/tests/original/mod.rs index d3d63785..0b6c42b0 100644 --- a/tests/original/mod.rs +++ b/tests/original/mod.rs @@ -1,8 +1 @@ -pub(crate) mod basic; - -macro_rules! all { - ($storage: ident) => { - crate::original::basic::all!($storage); - }; -} -pub(crate) use all; +crate::util_macros::make_all!(original, [basic]); diff --git a/tests/storages/csv.rs b/tests/storages/csv.rs index 8180864d..b2af0a21 100644 --- a/tests/storages/csv.rs +++ b/tests/storages/csv.rs @@ -1,31 +1,22 @@ -static mut CSV_NUM: u16 = 0; -macro_rules! storage { - () => {{ - use {fstrings::*, multisql::*}; +pub fn csv_storage(name: &str) -> multisql::Glue { + use {fstrings::*, multisql::*}; - let path = unsafe { - CSV_NUM = CSV_NUM + 1; - f!("data/csv_{CSV_NUM}.csv") - }; + let path = f!("data/csv_{name}.csv"); - match std::fs::remove_file(&path) { - Ok(()) => (), - Err(e) => { - println!("fs::remove_file {:?}", e); - } + match std::fs::remove_file(&path) { + Ok(()) => (), + Err(e) => { + println!("fs::remove_file {:?}", e); } + } - let storage = CSVStorage::new(&path) - .map(Storage::new_csv) - .expect("Create Storage"); + let storage = CSVStorage::new(&path) + .map(Storage::new_csv) + .expect("Create Storage"); - Glue::new(String::from("main"), storage) - }}; -} -pub fn csv_storage() -> multisql::Glue { - storage!() + Glue::new(String::from("main"), storage) } -crate::functionality::statement::create::all!(csv_storage); -crate::functionality::statement::insert::all!(csv_storage); -crate::functionality::statement::select::all!(csv_storage); +crate::util_macros::run!(csv_storage, functionality::statement::create); +crate::util_macros::run!(csv_storage, functionality::statement::insert); +crate::util_macros::run!(csv_storage, functionality::statement::select); diff --git a/tests/storages/sled.rs b/tests/storages/sled.rs index 99f7ef0f..0dc7111f 100644 --- a/tests/storages/sled.rs +++ b/tests/storages/sled.rs @@ -1,30 +1,22 @@ -static mut SLED_NUM: u16 = 0; -macro_rules! storage { - () => {{ - use {fstrings::*, multisql::*}; +pub fn sled_storage(name: &str) -> multisql::Glue { + use {fstrings::*, multisql::*}; - let path = unsafe { - SLED_NUM = SLED_NUM + 1; - f!("data/sled_{SLED_NUM}") - }; + println_f!("{name}"); + let path = f!("data/sled_{name}"); - match std::fs::remove_dir_all(&path) { - Ok(()) => (), - Err(e) => { - println!("fs::remove_file {:?}", e); - } + match std::fs::remove_dir_all(&path) { + Ok(()) => (), + Err(e) => { + println!("fs::remove_file {:?}", e); } + } - let storage = SledStorage::new(&path) - .map(Storage::new_sled) - .expect("Create Storage"); + let storage = SledStorage::new(&path) + .map(Storage::new_sled) + .expect("Create Storage"); - Glue::new(String::from("main"), storage) - }}; -} -pub fn sled_storage() -> multisql::Glue { - storage!() + Glue::new(String::from("main"), storage) } -crate::functionality::all!(sled_storage); -crate::original::all!(sled_storage); +crate::util_macros::run!(sled_storage, functionality); +crate::util_macros::run!(sled_storage, original); diff --git a/tests/util_macros/mod.rs b/tests/util_macros/mod.rs index ddc936c2..6c81c61c 100644 --- a/tests/util_macros/mod.rs +++ b/tests/util_macros/mod.rs @@ -1,5 +1,56 @@ #![allow(unused_macros)] #![allow(unused_imports)] +macro_rules! make_all { + ($($path_part: ident)::*, [$($test: ident),*]) => { + $(pub(crate) mod $test;)* + macro_rules! all { + ($storage: ident, $name: tt) => { + use crate::$($path_part)::*::{$($test),*}; + $($test::all!($storage, ($name, $test));)* + }; + } + pub(crate) use all; + } +} +pub(crate) use make_all; + +macro_rules! testcase { + ($test: expr) => { + macro_rules! all { + ($storage: ident, $name: tt) => { + crate::util_macros::make_test!($test, $storage, $name); + }; + } + pub(crate) use all; + }; +} +pub(crate) use testcase; + +macro_rules! make_test { + ($test: expr, $storage: ident, ($($path_part: ident)::*)) => { + concat_idents::concat_idents!(name = ""$(, $path_part,)"_"* { + #[test] + fn name() { + $test($storage(concat!(""$(, stringify!($path_part),)"_"*))); + } + }); + }; + ($test: expr, $storage: ident, (($($path_part: ident)::*), $($path_part_extension: ident)::+)) => { + crate::util_macros::make_test!($test, $storage, ($($path_part)::*::$($path_part_extension)::*)); + }; + ($test: expr, $storage: ident, (($more: tt, $extension: ident), $($path_part_extension: ident)::+)) => { + crate::util_macros::make_test!($test, $storage, ($more, $extension::$($path_part_extension)::+)); + }; +} +pub(crate) use make_test; + +macro_rules! run { + ($storage: ident, $($path_part: ident)::*) => { + crate::$($path_part)::*::all!($storage, ($($path_part)::*)); + }; +} +pub(crate) use run; + macro_rules! make_basic_table { ($glue: expr) => { $glue @@ -43,6 +94,9 @@ macro_rules! rows { (($($type: ident),*) : ($($value: expr),*)) => { vec![multisql::Row(vec![$(multisql::Value::$type($value)),*])] }; + (($($_type: ident),*) :) => { + vec![] + }; } pub(crate) use rows;