From ef09b57c6a859ae153901b8533749068bcfd4e5b Mon Sep 17 00:00:00 2001 From: Arseniy Volynets <vol0ncar@yandex.ru> Date: Thu, 2 Feb 2023 16:03:35 +0300 Subject: [PATCH] fix linting --- sbroad-benches/src/engine.rs | 8 +-- .../src/api/calculate_bucket_id.rs | 3 +- sbroad-cartridge/src/api/exec_query.rs | 6 +- sbroad-cartridge/src/api/helper.rs | 9 +-- .../src/api/invalidate_cached_schema.rs | 15 ++--- sbroad-cartridge/src/cartridge/config.rs | 30 +++------ sbroad-cartridge/src/cartridge/router.rs | 48 +++++++------- sbroad-cartridge/src/cartridge/storage.rs | 2 - .../test_app/test/integration/motion_test.lua | 2 +- sbroad-core/src/backend/sql/ir.rs | 61 +----------------- sbroad-core/src/backend/sql/ir/tests.rs | 1 + .../src/backend/sql/ir/tests/selection.rs | 1 + sbroad-core/src/backend/sql/space.rs | 2 - sbroad-core/src/backend/sql/tree/tests.rs | 5 +- sbroad-core/src/executor.rs | 3 +- sbroad-core/src/executor/engine.rs | 11 ++-- sbroad-core/src/executor/engine/mock.rs | 8 +-- sbroad-core/src/executor/ir.rs | 7 +- sbroad-core/src/executor/lru/tests.rs | 3 +- sbroad-core/src/executor/result.rs | 3 - sbroad-core/src/executor/result/tests.rs | 10 ++- sbroad-core/src/executor/tests.rs | 8 +-- sbroad-core/src/frontend/sql.rs | 11 ++-- sbroad-core/src/frontend/sql/ast/tests.rs | 3 +- sbroad-core/src/frontend/sql/ir.rs | 2 +- sbroad-core/src/ir/api/constant.rs | 3 +- sbroad-core/src/ir/expression.rs | 64 ++++++------------- sbroad-core/src/ir/operator.rs | 25 +++----- sbroad-core/src/ir/transformation/dnf.rs | 4 +- .../src/ir/transformation/merge_tuples.rs | 3 +- .../src/ir/transformation/redistribution.rs | 13 +--- .../src/ir/transformation/split_columns.rs | 3 +- sbroad-core/src/ir/tree/subtree.rs | 5 +- sbroad-core/src/ir/tree/tests.rs | 9 +-- sbroad-core/src/ir/value.rs | 5 +- sbroad-core/src/otm/statistics.rs | 5 +- 36 files changed, 132 insertions(+), 269 deletions(-) diff --git a/sbroad-benches/src/engine.rs b/sbroad-benches/src/engine.rs index 9dd78b30b8..7e7a028db4 100644 --- a/sbroad-benches/src/engine.rs +++ b/sbroad-benches/src/engine.rs @@ -454,16 +454,16 @@ impl Coordinator for RouterRuntimeMock { Ok(Box::new(explain)) } - fn extract_sharding_keys_from_map<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_map<'rec>( + &self, space: String, args: &'rec HashMap<String, Value>, ) -> Result<Vec<&'rec Value>, SbroadError> { sharding_keys_from_map(&*self.cached_config()?, &space, args) } - fn extract_sharding_keys_from_tuple<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_tuple<'rec>( + &self, space: String, rec: &'rec [Value], ) -> Result<Vec<&'rec Value>, SbroadError> { diff --git a/sbroad-cartridge/src/api/calculate_bucket_id.rs b/sbroad-cartridge/src/api/calculate_bucket_id.rs index 7103c62403..ba81c22b05 100644 --- a/sbroad-cartridge/src/api/calculate_bucket_id.rs +++ b/sbroad-cartridge/src/api/calculate_bucket_id.rs @@ -124,8 +124,7 @@ pub extern "C" fn calculate_bucket_id(ctx: FunctionCtx, args: FunctionArgs) -> c Ok(runtime) => runtime, Err(e) => { return tarantool_error(&format!( - "Failed to borrow the runtime while calculating a bucket id: {:?}", - e, + "Failed to borrow the runtime while calculating a bucket id: {e:?}", )); } }; diff --git a/sbroad-cartridge/src/api/exec_query.rs b/sbroad-cartridge/src/api/exec_query.rs index bf4ced65ed..847b112649 100644 --- a/sbroad-cartridge/src/api/exec_query.rs +++ b/sbroad-cartridge/src/api/exec_query.rs @@ -50,8 +50,7 @@ pub extern "C" fn dispatch_query(f_ctx: FunctionCtx, args: FunctionArgs) -> c_in Ok(runtime) => runtime, Err(e) => { return tarantool_error(&format!( - "Failed to borrow the runtime while dispatching the query: {}", - e + "Failed to borrow the runtime while dispatching the query: {e}" )); } }; @@ -175,8 +174,7 @@ pub extern "C" fn execute(f_ctx: FunctionCtx, args: FunctionArgs) -> c_int { Ok(runtime) => runtime, Err(e) => { return tarantool_error(&format!( - "Failed to borrow the runtime while executing the query: {}", - e + "Failed to borrow the runtime while executing the query: {e}" )); } }; diff --git a/sbroad-cartridge/src/api/helper.rs b/sbroad-cartridge/src/api/helper.rs index 9d5bbc41a3..380c18042e 100644 --- a/sbroad-cartridge/src/api/helper.rs +++ b/sbroad-cartridge/src/api/helper.rs @@ -17,8 +17,7 @@ where Ok(runtime) => runtime, Err(e) => { return tarantool_error(&format!( - "Failed to borrow the runtime while loading configuration: {}", - e + "Failed to borrow the runtime while loading configuration: {e}" )); } }; @@ -46,15 +45,13 @@ where Ok(runtime) => runtime, Err(e) => { return tarantool_error(&format!( - "Failed to borrow the runtime while updating configuration: {}", - e + "Failed to borrow the runtime while updating configuration: {e}" )); } }; if let Err(e) = runtime.update_config(config) { return tarantool_error(&format!( - "Failed to update the configuration in the runtime during configuration loading: {}", - e + "Failed to update the configuration in the runtime during configuration loading: {e}" )); } 0 diff --git a/sbroad-cartridge/src/api/invalidate_cached_schema.rs b/sbroad-cartridge/src/api/invalidate_cached_schema.rs index 3d1049ae67..f1879402dd 100644 --- a/sbroad-cartridge/src/api/invalidate_cached_schema.rs +++ b/sbroad-cartridge/src/api/invalidate_cached_schema.rs @@ -13,22 +13,19 @@ pub extern "C" fn invalidate_coordinator_cache(ctx: FunctionCtx, _: FunctionArgs Ok(runtime) => { if let Err(e) = runtime.clear_config() { return tarantool_error(&format!( - "Failed to clear the configuration in the coordinator runtime during cache invalidation: {}", - e + "Failed to clear the configuration in the coordinator runtime during cache invalidation: {e}" )); } if let Err(e) = runtime.clear_ir_cache() { return tarantool_error(&format!( - "Failed to clear the IR cache on router: {:?}", - e + "Failed to clear the IR cache on router: {e:?}" )); } ctx.return_mp(&true).unwrap(); 0 } Err(e) => tarantool_error(&format!( - "Failed to borrow the runtime while clearing cached configuration on router: {}", - e + "Failed to borrow the runtime while clearing cached configuration on router: {e}" )), }) } @@ -41,16 +38,14 @@ pub extern "C" fn invalidate_segment_cache(ctx: FunctionCtx, _: FunctionArgs) -> Ok(runtime) => { if let Err(e) = runtime.clear_config() { return tarantool_error(&format!( - "Failed to clear the configuration on segment during cache invalidation: {:?}", - e + "Failed to clear the configuration on segment during cache invalidation: {e:?}" )); } ctx.return_mp(&true).unwrap(); 0 } Err(e) => tarantool_error(&format!( - "Failed to borrow the runtime while clearing cached configuration on a storage: {}", - e + "Failed to borrow the runtime while clearing cached configuration on a storage: {e}" )), }) } diff --git a/sbroad-cartridge/src/cartridge/config.rs b/sbroad-cartridge/src/cartridge/config.rs index 5a07b23b78..cde6be1f3a 100644 --- a/sbroad-cartridge/src/cartridge/config.rs +++ b/sbroad-cartridge/src/cartridge/config.rs @@ -97,14 +97,11 @@ impl RouterConfiguration { #[allow(clippy::too_many_lines)] fn init_table_segments(&mut self, schema: &Yaml) -> Result<(), SbroadError> { self.tables.clear(); - let spaces = match schema["spaces"].as_hash() { - Some(v) => v, - None => { - return Err(SbroadError::Invalid( - Entity::ClusterSchema, - Some("schema.spaces is invalid".into()), - )) - } + let Some(spaces) = schema["spaces"].as_hash() else { + return Err(SbroadError::Invalid( + Entity::ClusterSchema, + Some("schema.spaces is invalid".into()), + )) }; for (space_name, params) in spaces.iter() { @@ -129,8 +126,7 @@ impl RouterConfiguration { return Err(SbroadError::Invalid( Entity::ClusterSchema, Some(format!( - "Type not found for columns {} of table {}", - name, current_space_name + "Type not found for columns {name} of table {current_space_name}" )), )) } @@ -139,8 +135,7 @@ impl RouterConfiguration { debug!( Option::from("configuration parsing"), &format!( - "Column's original name: {}, qualified name {}", - name, qualified_name + "Column's original name: {name}, qualified name {qualified_name}" ), ); let role = if self.get_sharding_column().eq(&qualified_name) { @@ -169,8 +164,7 @@ impl RouterConfiguration { warn!( Option::from("configuration parsing"), &format!( - "Skip space {}: failed to convert key {:?} to string.", - current_space_name, k + "Skip space {current_space_name}: failed to convert key {k:?} to string." ), ); continue; @@ -192,10 +186,7 @@ impl RouterConfiguration { } else { warn!( Option::from("configuration parsing"), - &format!( - "Skip space {current_space_name}: unknown engine {}.", - engine - ), + &format!("Skip space {current_space_name}: unknown engine {engine}."), ); continue; } @@ -211,8 +202,7 @@ impl RouterConfiguration { debug!( Option::from("configuration parsing"), &format!( - "Table's original name: {}, qualified name {}", - current_space_name, table_name + "Table's original name: {current_space_name}, qualified name {table_name}" ), ); let keys_str = keys.iter().map(String::as_str).collect::<Vec<&str>>(); diff --git a/sbroad-cartridge/src/cartridge/router.rs b/sbroad-cartridge/src/cartridge/router.rs index 36409a22bc..56bf31fc72 100644 --- a/sbroad-cartridge/src/cartridge/router.rs +++ b/sbroad-cartridge/src/cartridge/router.rs @@ -31,7 +31,6 @@ use sbroad::executor::lru::{LRUCache, DEFAULT_CAPACITY}; use sbroad::executor::result::ProducerResult; use sbroad::executor::vtable::VirtualTable; use sbroad::frontend::sql::ast::AbstractSyntaxTree; -use sbroad::ir::expression::Expression; use sbroad::ir::helpers::RepeatableState; use sbroad::ir::tree::Snapshot; use sbroad::ir::value::Value; @@ -175,7 +174,7 @@ impl Configuration for RouterRuntime { } impl RouterRuntime { - fn filter_vtable(&self, plan: &mut ExecutionPlan, bucket_ids: &[u64]) { + fn filter_vtable(plan: &mut ExecutionPlan, bucket_ids: &[u64]) { if let Some(vtables) = plan.get_mut_vtables() { for rc_vtable in vtables.values_mut() { // If the virtual table id hashed by the bucket_id, we can filter its tuples. @@ -187,7 +186,7 @@ impl RouterRuntime { } } - fn encode_plan(&self, exec_plan: ExecutionPlan) -> Result<(Binary, Binary), SbroadError> { + fn encode_plan(exec_plan: ExecutionPlan) -> Result<(Binary, Binary), SbroadError> { // We should not use the cache on the storage if the plan contains virtual tables, // as they can contain different amount of tuples that are not taken into account // when calculating the cache key. @@ -216,9 +215,7 @@ impl RouterRuntime { ) -> Result<Box<dyn Any>, SbroadError> { let query_type = sub_plan.query_type()?; let conn_type = sub_plan.connection_type()?; - let bucket_set = if let Buckets::Filtered(bucket_set) = buckets { - bucket_set - } else { + let Buckets::Filtered(bucket_set) = buckets else { return Err(SbroadError::Invalid( Entity::Buckets, Some(format!("Expected Buckets::Filtered, got {buckets:?}")), @@ -250,13 +247,19 @@ impl RouterRuntime { if let Some((last, other)) = rs_bucket_vec.split_last() { for (rs, bucket_ids) in other { let mut rs_plan = sub_plan.clone(); - self.filter_vtable(&mut rs_plan, bucket_ids); - rs_ir.insert(rs.clone(), Message::from(self.encode_plan(rs_plan)?)); + RouterRuntime::filter_vtable(&mut rs_plan, bucket_ids); + rs_ir.insert( + rs.clone(), + Message::from(RouterRuntime::encode_plan(rs_plan)?), + ); } let (rs, bucket_ids) = last; - self.filter_vtable(&mut sub_plan, bucket_ids); - rs_ir.insert(rs.clone(), Message::from(self.encode_plan(sub_plan)?)); + RouterRuntime::filter_vtable(&mut sub_plan, bucket_ids); + rs_ir.insert( + rs.clone(), + Message::from(RouterRuntime::encode_plan(sub_plan)?), + ); } self.exec_ir_on_some(rs_ir, query_type, conn_type) } @@ -303,7 +306,7 @@ impl Coordinator for RouterRuntime { let all_buckets = Buckets::new_filtered(bucket_set); return self.exec_with_filtered_buckets(sub_plan, &all_buckets); } - let (required, optional) = self.encode_plan(sub_plan)?; + let (required, optional) = RouterRuntime::encode_plan(sub_plan)?; self.exec_ir_on_all(required, optional, query_type, conn_type) } } @@ -363,8 +366,8 @@ impl Coordinator for RouterRuntime { Ok(vtable) } - fn extract_sharding_keys_from_map<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_map<'rec>( + &self, space: String, map: &'rec HashMap<String, Value>, ) -> Result<Vec<&'rec Value>, SbroadError> { @@ -374,8 +377,8 @@ impl Coordinator for RouterRuntime { sharding_keys_from_map(&*metadata, &space, map) } - fn extract_sharding_keys_from_tuple<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_tuple<'rec>( + &self, space: String, rec: &'rec [Value], ) -> Result<Vec<&'rec Value>, SbroadError> { @@ -424,8 +427,7 @@ impl RouterRuntime { Err(e) => { error!(Option::from("set_bucket_count"), &format!("{e:?}")); return Err(SbroadError::LuaError(format!( - "Failed lua function load: {}", - e + "Failed lua function load: {e}" ))); } }; @@ -471,8 +473,7 @@ impl RouterRuntime { Err(e) => { error!(Option::from("dql_on_some"), &format!("{e:?}")); Err(SbroadError::LuaError(format!( - "Lua error (IR dispatch): {:?}", - e + "Lua error (IR dispatch): {e:?}" ))) } } @@ -495,8 +496,7 @@ impl RouterRuntime { Err(e) => { error!(Option::from("dml_on_some"), &format!("{e:?}")); Err(SbroadError::LuaError(format!( - "Lua error (IR dispatch): {:?}", - e + "Lua error (IR dispatch): {e:?}" ))) } } @@ -540,8 +540,7 @@ impl RouterRuntime { Err(e) => { error!(Option::from("dql_on_all"), &format!("{e:?}")); Err(SbroadError::LuaError(format!( - "Lua error (dispatch IR): {:?}", - e + "Lua error (dispatch IR): {e:?}" ))) } } @@ -570,8 +569,7 @@ impl RouterRuntime { Err(e) => { error!(Option::from("dml_on_all"), &format!("{e:?}")); Err(SbroadError::LuaError(format!( - "Lua error (dispatch IR): {:?}", - e + "Lua error (dispatch IR): {e:?}" ))) } } diff --git a/sbroad-cartridge/src/cartridge/storage.rs b/sbroad-cartridge/src/cartridge/storage.rs index a470f267d1..d952c29312 100644 --- a/sbroad-cartridge/src/cartridge/storage.rs +++ b/sbroad-cartridge/src/cartridge/storage.rs @@ -208,7 +208,6 @@ impl StorageRuntime { } let (pattern_with_params, tmp_spaces) = compile_encoded_optional(raw_optional)?; - println!("{}", String::from(pattern_with_params.clone())); debug!( Option::from("execute"), &format!( @@ -274,7 +273,6 @@ impl StorageRuntime { ); let (pattern_with_params, tmp_spaces) = compile_encoded_optional(raw_optional)?; - println!("{}", String::from(pattern_with_params.clone())); let result = match prepare(&pattern_with_params.pattern) { Ok(stmt) => { let stmt_id = stmt.id()?; diff --git a/sbroad-cartridge/test_app/test/integration/motion_test.lua b/sbroad-cartridge/test_app/test/integration/motion_test.lua index 5f36d205ba..e00a5f44f9 100644 --- a/sbroad-cartridge/test_app/test/integration/motion_test.lua +++ b/sbroad-cartridge/test_app/test/integration/motion_test.lua @@ -220,4 +220,4 @@ g.test_motion_dotted_name = function() }, rows = {}, }) -end \ No newline at end of file +end diff --git a/sbroad-core/src/backend/sql/ir.rs b/sbroad-core/src/backend/sql/ir.rs index 806bb0bdc9..35754c64de 100644 --- a/sbroad-core/src/backend/sql/ir.rs +++ b/sbroad-core/src/backend/sql/ir.rs @@ -1,7 +1,7 @@ use ahash::AHashMap; use opentelemetry::Context; use serde::{Deserialize, Serialize}; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::fmt::Write as _; use tarantool::tlua::{self, Push}; use tarantool::tuple::{FunctionArgs, Tuple}; @@ -433,65 +433,6 @@ impl ExecutionPlan { Ok((PatternWithParams::new(sql, params), tmp_spaces)) } - // column names are from tarantool instance output, it can happen that - // column name is different from motion output, for example in query like this: - // select s."b" from (select "t.b" from TMP_SPACE) as s - // where TMP_SPACE is output from `select "t"."b" from "t"` - // in this case we must alias column name to output name. - // Because we support only column names like this: scan_name.col_name - // where scan_name and col_name do not contain dots (.), we can assume that - // column name != output_alias => column_name = X.output_alias, where X is some string - // and we also can assume that there are no columns: Y.output_alias and X.output_alias in VTable - // because we ensure that output row aliases are unique (see `add_row_of_aliases`). - fn construct_proj_cols(&self, vtable: &SyntaxData) -> Result<Vec<String>, SbroadError> { - let (vtable, motion_id) = if let SyntaxData::VTable(motion_id) = vtable { - (self.get_motion_vtable(*motion_id)?, motion_id) - } else { - return Err(SbroadError::Invalid( - Entity::SyntaxNode, - Some("Expected VTable!".into()), - )); - }; - let plan = self.get_ir_plan(); - let nodes = &plan.nodes; - let aliases = plan - .get_relation_node(*motion_id)? - .output_alias_position_map(nodes)? - .into_keys() - .collect::<HashSet<&str>>(); - let mut proj_cols: Vec<String> = Vec::with_capacity(vtable.get_columns().len()); - for vcol in vtable.get_columns() { - let vcol_q = format!("\"{}\"", vcol.name); - // currently if we generate bucket_id for vtable, we do not specify it in the output of motion - if vcol.name == "bucket_id" { - proj_cols.push(vcol_q); - continue; - } - // aliases can be surrounded by " or not - if aliases.contains(vcol_q.as_str()) || aliases.contains(vcol.name.as_str()) { - proj_cols.push(vcol_q); - continue; - } else if vcol.name.contains('.') { - if let Some(c) = vcol.name.split('.').last() { - let c_q = format!("\"{c}\""); - if aliases.contains(c_q.as_str()) || aliases.contains(c) { - proj_cols.push(format!("{vcol_q} as {c_q}")); - continue; - } - } - } - return Err(SbroadError::Invalid( - Entity::SyntaxNode, - Some(format!( - "VTable column with name {} is not found in motion output: {aliases:?}!", - vcol.name - )), - )); - } - - Ok(proj_cols) - } - /// Checks if the given query subtree modifies data or not. /// /// # Errors diff --git a/sbroad-core/src/backend/sql/ir/tests.rs b/sbroad-core/src/backend/sql/ir/tests.rs index a601e003f1..87ce24b046 100644 --- a/sbroad-core/src/backend/sql/ir/tests.rs +++ b/sbroad-core/src/backend/sql/ir/tests.rs @@ -10,6 +10,7 @@ use crate::ir::tree::Snapshot; use super::*; +#[allow(clippy::needless_pass_by_value)] fn check_sql_with_snapshot( query: &str, params: Vec<Value>, diff --git a/sbroad-core/src/backend/sql/ir/tests/selection.rs b/sbroad-core/src/backend/sql/ir/tests/selection.rs index de3cb30770..1d791249d8 100644 --- a/sbroad-core/src/backend/sql/ir/tests/selection.rs +++ b/sbroad-core/src/backend/sql/ir/tests/selection.rs @@ -43,6 +43,7 @@ fn selection1_oldest() { } #[test] +#[allow(clippy::too_many_lines)] fn selection2_latest() { let query = r#"SELECT "product_code" FROM "hash_testing" WHERE "identification_number" IN (6659253, -21, 5933116, 8257405, 3676468, 6580234, 9557717) diff --git a/sbroad-core/src/backend/sql/space.rs b/sbroad-core/src/backend/sql/space.rs index abbb5e99dd..6beca9f5e6 100644 --- a/sbroad-core/src/backend/sql/space.rs +++ b/sbroad-core/src/backend/sql/space.rs @@ -46,8 +46,6 @@ impl TmpSpace { .map(|c| Field::from(c.clone())) .collect(); - println!("cols: {:?}", vtable.get_columns()); - println!("fields: {fields:?}"); let pk_name = TmpSpace::generate_pk_name(base, motion_id); fields.push(Field::unsigned(pk_name.clone())); let fields_len = fields.len() as u32; diff --git a/sbroad-core/src/backend/sql/tree/tests.rs b/sbroad-core/src/backend/sql/tree/tests.rs index 49be7fcf1d..7be7d9ca16 100644 --- a/sbroad-core/src/backend/sql/tree/tests.rs +++ b/sbroad-core/src/backend/sql/tree/tests.rs @@ -91,6 +91,7 @@ fn sql_order_selection() { } #[test] +#[allow(clippy::too_many_lines)] fn sql_arithmetic_plan() { // select a from t where a + (b/c + d*e) * f - b = 1 let mut plan = Plan::default(); @@ -145,12 +146,12 @@ fn sql_arithmetic_plan() { .add_arithmetic_to_plan(arith_addition_id2, Arithmetic::Subtract, b_id, false) .unwrap(); // a + (b/c + d*e) * f - b = 1 - let eq_id = plan + let equal_id = plan .nodes .add_bool(arith_subract_id, Bool::Eq, const_row) .unwrap(); // where a + (b/c + d*e) * f - b = 1 - let select_id = plan.add_select(&[scan_id], eq_id).unwrap(); + let select_id = plan.add_select(&[scan_id], equal_id).unwrap(); let proj_id = plan.add_proj(select_id, &["a"]).unwrap(); plan.set_top(proj_id).unwrap(); diff --git a/sbroad-core/src/executor.rs b/sbroad-core/src/executor.rs index a3574af13c..e12dde5f2e 100644 --- a/sbroad-core/src/executor.rs +++ b/sbroad-core/src/executor.rs @@ -264,8 +264,7 @@ where SbroadError::NotFound( Entity::DistributionKey, format!( - "failed to find a distribution key column {} in the tuple {:?}.", - pos, tuple + "failed to find a distribution key column {pos} in the tuple {tuple:?}." ), ) })?; diff --git a/sbroad-core/src/executor/engine.rs b/sbroad-core/src/executor/engine.rs index 82887e6a19..9938502d9d 100644 --- a/sbroad-core/src/executor/engine.rs +++ b/sbroad-core/src/executor/engine.rs @@ -141,8 +141,8 @@ pub trait Coordinator: Configuration { /// /// # Errors /// - Columns are not present in the sharding key of the space. - fn extract_sharding_keys_from_map<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_map<'rec>( + &self, space: String, args: &'rec HashMap<String, Value>, ) -> Result<Vec<&'rec Value>, SbroadError>; @@ -151,8 +151,8 @@ pub trait Coordinator: Configuration { /// /// # Errors /// - Internal error in the table (should never happen, but we recheck). - fn extract_sharding_keys_from_tuple<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_tuple<'rec>( + &self, space: String, args: &'rec [Value], ) -> Result<Vec<&'rec Value>, SbroadError>; @@ -204,8 +204,7 @@ pub fn sharding_keys_from_tuple<'rec>( return Err(SbroadError::Invalid( Entity::Tuple, Some(format!( - r#"the tuple {:?} contains a "bucket_id" position {} in a sharding key {:?}"#, - tuple, position, sharding_positions + r#"the tuple {tuple:?} contains a "bucket_id" position {position} in a sharding key {sharding_positions:?}"# )), )) } diff --git a/sbroad-core/src/executor/engine/mock.rs b/sbroad-core/src/executor/engine/mock.rs index 0c69d20ed4..98b8d83297 100644 --- a/sbroad-core/src/executor/engine/mock.rs +++ b/sbroad-core/src/executor/engine/mock.rs @@ -386,16 +386,16 @@ impl Coordinator for RouterRuntimeMock { Ok(Box::new(explain)) } - fn extract_sharding_keys_from_map<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_map<'rec>( + &self, space: String, args: &'rec HashMap<String, Value>, ) -> Result<Vec<&'rec Value>, SbroadError> { sharding_keys_from_map(&*self.metadata.borrow(), &space, args) } - fn extract_sharding_keys_from_tuple<'engine, 'rec>( - &'engine self, + fn extract_sharding_keys_from_tuple<'rec>( + &self, space: String, rec: &'rec [Value], ) -> Result<Vec<&'rec Value>, SbroadError> { diff --git a/sbroad-core/src/executor/ir.rs b/sbroad-core/src/executor/ir.rs index a5c1dee353..99eee4361f 100644 --- a/sbroad-core/src/executor/ir.rs +++ b/sbroad-core/src/executor/ir.rs @@ -95,6 +95,7 @@ impl ExecutionPlan { )) } + #[must_use] pub fn has_segmented_tables(&self) -> bool { self.vtables.as_ref().map_or(false, |vtable_map| { vtable_map.map().values().any(|t| !t.get_index().is_empty()) @@ -341,8 +342,7 @@ impl ExecutionPlan { Action::Build, Some(Entity::SubTree), format!( - "could not find filter/condition node id {} in the map", - undo_expr_id + "could not find filter/condition node id {undo_expr_id} in the map" ), ) })?; @@ -360,8 +360,7 @@ impl ExecutionPlan { Action::Build, Some(Entity::SubTree), format!( - "could not find relation {} in the original plan", - relation + "could not find relation {relation} in the original plan" ), ) })? diff --git a/sbroad-core/src/executor/lru/tests.rs b/sbroad-core/src/executor/lru/tests.rs index 681a8d8f84..3740aad755 100644 --- a/sbroad-core/src/executor/lru/tests.rs +++ b/sbroad-core/src/executor/lru/tests.rs @@ -27,8 +27,7 @@ fn lru3() { let value_old = value.clone(); value.push_str("_old"); Err(SbroadError::UnexpectedNumberOfValues(format!( - "changed {} to {} during cache eviction", - value_old, value + "changed {value_old} to {value} during cache eviction" ))) }); let mut cache: LRUCache<usize, String> = LRUCache::new(1, Some(evict_fn)).unwrap(); diff --git a/sbroad-core/src/executor/result.rs b/sbroad-core/src/executor/result.rs index fb0405fbe2..7f338bb831 100644 --- a/sbroad-core/src/executor/result.rs +++ b/sbroad-core/src/executor/result.rs @@ -1,15 +1,12 @@ use core::fmt::Debug; use serde::ser::{Serialize, SerializeMap, Serializer}; use serde::Deserialize; -use std::collections::HashSet; use tarantool::tlua::{self, LuaRead}; use crate::errors::{Entity, SbroadError}; use crate::executor::vtable::VirtualTable; -use crate::ir::operator::Relational; use crate::ir::relation::{Column, ColumnRole, Type}; use crate::ir::value::{EncodedValue, Value}; -use crate::ir::Plan; type ExecutorTuple = Vec<EncodedValue>; diff --git a/sbroad-core/src/executor/result/tests.rs b/sbroad-core/src/executor/result/tests.rs index de8b6cc66d..4d5383c38c 100644 --- a/sbroad-core/src/executor/result/tests.rs +++ b/sbroad-core/src/executor/result/tests.rs @@ -1,5 +1,4 @@ use pretty_assertions::{assert_eq, assert_ne}; -use serde::de::IntoDeserializer; use tarantool::decimal; use super::*; @@ -113,7 +112,12 @@ fn convert_to_vtable() { assert_eq!( excepted, - r.as_virtual_table(col_names.into_iter().map(|s| s.to_string()).collect()) - .unwrap() + r.as_virtual_table( + col_names + .into_iter() + .map(std::string::ToString::to_string) + .collect() + ) + .unwrap() ); } diff --git a/sbroad-core/src/executor/tests.rs b/sbroad-core/src/executor/tests.rs index 07185270bc..e474d55af3 100644 --- a/sbroad-core/src/executor/tests.rs +++ b/sbroad-core/src/executor/tests.rs @@ -535,6 +535,7 @@ fn join_linker3_test() { } #[test] +#[allow(clippy::too_many_lines)] fn join_linker4_test() { let sql = r#"SELECT t1."id" FROM "test_space" as t1 JOIN (SELECT "FIRST_NAME" as "r_id" FROM "test_space") as t2 @@ -707,7 +708,7 @@ on q."f" = "t1"."a""#; r#type: Type::Integer, role: ColumnRole::User, }); - virtual_sq.set_alias("Q"); + virtual_sq.set_alias("Q").unwrap(); if let MotionPolicy::Segment(key) = get_motion_policy(query.exec_plan.get_ir_plan(), motion_sq_id) { @@ -728,7 +729,7 @@ on q."f" = "t1"."a""#; let mut expected = ProducerResult::new(); expected.rows.extend(vec![vec![ - EncodedValue::String(format!("Execute query on all buckets")), + EncodedValue::String("Execute query on all buckets".to_string()), EncodedValue::String(String::from(PatternWithParams::new( format!( "{} {} {} {}", @@ -1184,9 +1185,6 @@ fn insert4_test() { assert_eq!(expected, result); } -// this is not a valid sql for tarantool, what this tests checks? -// if tmp space have columns: COLUMN_5, COLUMN_6 we can't select a, b from it -#[ignore] #[test] fn insert5_test() { let sql = r#"insert into "t" ("b", "a") select 5, 6 from "t" diff --git a/sbroad-core/src/frontend/sql.rs b/sbroad-core/src/frontend/sql.rs index 65efcf5001..3e20382b69 100644 --- a/sbroad-core/src/frontend/sql.rs +++ b/sbroad-core/src/frontend/sql.rs @@ -119,9 +119,8 @@ impl Ast for AbstractSyntaxTree { { let mut plan = Plan::default(); - let top = match self.top { - Some(t) => t, - None => return Err(SbroadError::Invalid(Entity::AST, None)), + let Some(top) = self.top else { + return Err(SbroadError::Invalid(Entity::AST, None)) }; let capacity = self.nodes.arena.len(); let mut dft_post = PostOrder::with_capacity(|node| self.nodes.ast_iter(node), capacity); @@ -276,8 +275,7 @@ impl Ast for AbstractSyntaxTree { return Err(SbroadError::NotFound( Entity::Column, format!( - "'{}' in the join left child '{:?}'", - col_name, left_name + "'{col_name}' in the join left child '{left_name:?}'" ), )); } @@ -297,8 +295,7 @@ impl Ast for AbstractSyntaxTree { return Err(SbroadError::NotFound( Entity::Column, format!( - "'{}' in the join right child '{:?}'", - col_name, right_name + "'{col_name}' in the join right child '{right_name:?}'" ), )); } diff --git a/sbroad-core/src/frontend/sql/ast/tests.rs b/sbroad-core/src/frontend/sql/ast/tests.rs index c1c2e1663a..5232d0d27c 100644 --- a/sbroad-core/src/frontend/sql/ast/tests.rs +++ b/sbroad-core/src/frontend/sql/ast/tests.rs @@ -180,10 +180,11 @@ fn invalid_condition() { = expected EOI, Multiply, Divide, Add, or Subtract"#, ), format!("{ast}"), - ) + ); } #[test] +#[allow(clippy::similar_names)] fn sql_arithmetic_ast() { let ast = AbstractSyntaxTree::new("select a from t where a + b = 1").unwrap(); diff --git a/sbroad-core/src/frontend/sql/ir.rs b/sbroad-core/src/frontend/sql/ir.rs index 6d5069e989..e126b4ec86 100644 --- a/sbroad-core/src/frontend/sql/ir.rs +++ b/sbroad-core/src/frontend/sql/ir.rs @@ -8,7 +8,7 @@ use crate::frontend::sql::ast::{ParseNode, Type}; use crate::ir::expression::Expression; use crate::ir::helpers::RepeatableState; use crate::ir::operator::{Arithmetic, Bool, Relational, Unary}; -use crate::ir::tree::traversal::{PostOrder, EXPR_CAPACITY, REL_CAPACITY}; +use crate::ir::tree::traversal::{PostOrder, EXPR_CAPACITY}; use crate::ir::value::double::Double; use crate::ir::value::Value; use crate::ir::{Node, Plan}; diff --git a/sbroad-core/src/ir/api/constant.rs b/sbroad-core/src/ir/api/constant.rs index 1f314bb17d..f5aaf66b94 100644 --- a/sbroad-core/src/ir/api/constant.rs +++ b/sbroad-core/src/ir/api/constant.rs @@ -81,8 +81,7 @@ impl Plan { return Err(SbroadError::Invalid( Entity::Expression, Some(format!( - "Restoring parameters filed: node {:?} (id: {}) is not of a constant type", - const_node, id + "Restoring parameters filed: node {const_node:?} (id: {id}) is not of a constant type" )), )); } diff --git a/sbroad-core/src/ir/expression.rs b/sbroad-core/src/ir/expression.rs index ad40406977..b34d185d4a 100644 --- a/sbroad-core/src/ir/expression.rs +++ b/sbroad-core/src/ir/expression.rs @@ -158,14 +158,11 @@ impl Expression { /// other than `Row` or a node doesn't know its distribution yet. pub fn distribution(&self) -> Result<&Distribution, SbroadError> { if let Expression::Row { distribution, .. } = self { - let dist = match distribution { - Some(d) => d, - None => { - return Err(SbroadError::Invalid( - Entity::Distribution, - Some("distribution is uninitialized".into()), - )) - } + let Some(dist) = distribution else { + return Err(SbroadError::Invalid( + Entity::Distribution, + Some("distribution is uninitialized".into()), + )) }; return Ok(dist); } @@ -296,19 +293,13 @@ impl Nodes { self.arena.get(left).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!( - "(left child of boolean node) from arena with index {}", - left - ), + format!("(left child of boolean node) from arena with index {left}"), ) })?; self.arena.get(right).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!( - "(right child of boolean node) from arena with index {}", - right - ), + format!("(right child of boolean node) from arena with index {right}"), ) })?; Ok(self.push(Node::Expression(Expression::Bool { left, op, right }))) @@ -328,19 +319,13 @@ impl Nodes { self.arena.get(left).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!( - "(left child of Arithmetic node) from arena with index {}", - left - ), + format!("(left child of Arithmetic node) from arena with index {left}"), ) })?; self.arena.get(right).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!( - "(right child of Arithmetic node) from arena with index {}", - right - ), + format!("(right child of Arithmetic node) from arena with index {right}"), ) })?; Ok(self.push(Node::Expression(Expression::Arithmetic { @@ -426,8 +411,7 @@ impl Nodes { { if !names.insert(String::from(name)) { return Err(SbroadError::DuplicatedValue(format!( - "row can't be added because `{}` already has an alias", - name + "row can't be added because `{name}` already has an alias" ))); } } else { @@ -549,8 +533,7 @@ impl Plan { *sel_child_id } else { return Err(SbroadError::UnexpectedNumberOfValues(format!( - "Selection node has invalid children: {:?}", - sel_child_ids + "Selection node has invalid children: {sel_child_ids:?}" ))); }; let sel_child = self.get_relation_node(sel_child_id)?; @@ -664,8 +647,7 @@ impl Plan { } if map.insert(name, pos).is_some() { return Err(SbroadError::DuplicatedValue(format!( - "Duplicate column name {} at position {}", - name, pos + "Duplicate column name {name} at position {pos}" ))); } } @@ -831,9 +813,7 @@ impl Plan { targets, parent, .. }) = self.get_node(ref_id)? { - let referred_rel_id = if let Some(parent) = parent { - parent - } else { + let Some(referred_rel_id) = parent else { return Err(SbroadError::NotFound( Entity::Node, "that is Reference parent".into(), @@ -863,8 +843,7 @@ impl Plan { return Ok(referred_rel_id); } return Err(SbroadError::UnexpectedNumberOfValues(format!( - "Relational node {:?} has no children", - rel + "Relational node {rel:?} has no children" ))); } _ => { @@ -934,23 +913,20 @@ impl Plan { /// Check that the node is a boolean equality and its children are both rows. #[must_use] pub fn is_bool_eq_with_rows(&self, node_id: usize) -> bool { - let node = match self.get_expression_node(node_id) { - Ok(e) => e, - Err(_) => return false, + let Ok(node) = self.get_expression_node(node_id) else { + return false }; if let Expression::Bool { left, op, right } = node { if *op != Bool::Eq { return false; } - let left_node = match self.get_expression_node(*left) { - Ok(e) => e, - Err(_) => return false, + let Ok(left_node) = self.get_expression_node(*left) else { + return false }; - let right_node = match self.get_expression_node(*right) { - Ok(e) => e, - Err(_) => return false, + let Ok(right_node) = self.get_expression_node(*right) else { + return false }; if left_node.is_row() && right_node.is_row() { diff --git a/sbroad-core/src/ir/operator.rs b/sbroad-core/src/ir/operator.rs index 4426af61bd..fc5d1c826c 100644 --- a/sbroad-core/src/ir/operator.rs +++ b/sbroad-core/src/ir/operator.rs @@ -287,8 +287,8 @@ impl Relational { /// /// # Errors /// Returns `SbroadError` when the output tuple is invalid. - pub fn output_alias_position_map<'rel_op, 'nodes>( - &'rel_op self, + pub fn output_alias_position_map<'nodes>( + &self, nodes: &'nodes Nodes, ) -> Result<HashMap<&'nodes str, usize, RandomState>, SbroadError> { if let Some(Node::Expression(Expression::Row { list, .. })) = nodes.arena.get(self.output()) @@ -518,8 +518,7 @@ impl Relational { let rel_node = plan.get_relation_node(rel_id)?; if rel_node == self { return Err(SbroadError::DuplicatedValue(format!( - "Reference to the same node {:?} at position {}", - rel_node, position + "Reference to the same node {rel_node:?} at position {position}" ))); } return rel_node.scan_name(plan, *pos); @@ -581,8 +580,7 @@ impl Plan { let right_row_len = child_row_len(right, self)?; if left_row_len != right_row_len { return Err(SbroadError::UnexpectedNumberOfValues(format!( - "children tuples have mismatching amount of columns in except node: left {}, right {}", - left_row_len, right_row_len + "children tuples have mismatching amount of columns in except node: left {left_row_len}, right {right_row_len}" ))); } @@ -976,8 +974,7 @@ impl Plan { let right_row_len = child_row_len(right, self)?; if left_row_len != right_row_len { return Err(SbroadError::UnexpectedNumberOfValues(format!( - "children tuples have mismatching amount of columns in union all node: left {}, right {}", - left_row_len, right_row_len + "children tuples have mismatching amount of columns in union all node: left {left_row_len}, right {right_row_len}" ))); } @@ -1096,12 +1093,12 @@ impl Plan { } } - /// Gets list of aliases in output tuple of rel_id + /// Gets list of aliases in output tuple of `rel_id` /// /// # Errors /// - node is not relational - /// - output is not Expression::Row - /// - any node in the output tuple is not Expression::Alias + /// - output is not `Expression::Row` + /// - any node in the output tuple is not `Expression::Alias` pub fn get_relational_aliases(&self, rel_id: usize) -> Result<Vec<String>, SbroadError> { let output = self.get_relational_output(rel_id)?; if let Expression::Row { list, .. } = self.get_expression_node(output)? { @@ -1110,7 +1107,7 @@ impl Plan { .map(|alias_id| { self.get_expression_node(*alias_id)? .get_alias_name() - .map(|a| a.to_string()) + .map(std::string::ToString::to_string) }) .collect::<Result<Vec<String>, SbroadError>>(); } @@ -1240,9 +1237,7 @@ impl Plan { rel_id: usize, sq_id: usize, ) -> Result<bool, SbroadError> { - let children = if let Some(children) = self.get_relational_children(rel_id)? { - children - } else { + let Some(children) = self.get_relational_children(rel_id)? else { return Ok(false); }; match self.get_relation_node(rel_id)? { diff --git a/sbroad-core/src/ir/transformation/dnf.rs b/sbroad-core/src/ir/transformation/dnf.rs index ca485b6de9..a51aa5df5d 100644 --- a/sbroad-core/src/ir/transformation/dnf.rs +++ b/sbroad-core/src/ir/transformation/dnf.rs @@ -188,9 +188,7 @@ impl Plan { stack.push(top_chain); while let Some(mut chain) = stack.pop() { - let expr_id = if let Some(expr_id) = chain.pop_back(self)? { - expr_id - } else { + let Some(expr_id) = chain.pop_back(self)? else { result.push_back(chain); continue; }; diff --git a/sbroad-core/src/ir/transformation/merge_tuples.rs b/sbroad-core/src/ir/transformation/merge_tuples.rs index 45476ddf7c..e33a1b6961 100644 --- a/sbroad-core/src/ir/transformation/merge_tuples.rs +++ b/sbroad-core/src/ir/transformation/merge_tuples.rs @@ -385,8 +385,7 @@ impl Plan { *child_id = new_child_id; } else { return Err(SbroadError::UnexpectedNumberOfValues(format!( - "expected a column at position {} in the row {:?}", - pos, expr_mut + "expected a column at position {pos} in the row {expr_mut:?}" ))); } } else { diff --git a/sbroad-core/src/ir/transformation/redistribution.rs b/sbroad-core/src/ir/transformation/redistribution.rs index e344bda275..05d520541b 100644 --- a/sbroad-core/src/ir/transformation/redistribution.rs +++ b/sbroad-core/src/ir/transformation/redistribution.rs @@ -223,16 +223,14 @@ impl Plan { Ordering::Equal => sq_set.iter().next().map_or_else( || { Err(SbroadError::UnexpectedNumberOfValues(format!( - "Failed to get the first sub-query node from the list of relational nodes: {:?}.", - rel_nodes + "Failed to get the first sub-query node from the list of relational nodes: {rel_nodes:?}." ))) }, |sq_id| Ok(Some(*sq_id)), ), Ordering::Less => Ok(None), Ordering::Greater => Err(SbroadError::UnexpectedNumberOfValues(format!( - "Found multiple sub-queries in a list of relational nodes: {:?}.", - rel_nodes + "Found multiple sub-queries in a list of relational nodes: {rel_nodes:?}." ))), } } @@ -799,12 +797,7 @@ impl Plan { }; let child_rel = self.get_relation_node(child)?; let child_row = self.get_expression_node(child_rel.output())?; - let (list, distribution) = if let Expression::Row { - list, distribution, .. - } = child_row - { - (list, distribution) - } else { + let Expression::Row { list, distribution } = child_row else { return Err(SbroadError::Invalid( Entity::Node, Some( diff --git a/sbroad-core/src/ir/transformation/split_columns.rs b/sbroad-core/src/ir/transformation/split_columns.rs index b712c2d1a8..27ba2ab2b8 100644 --- a/sbroad-core/src/ir/transformation/split_columns.rs +++ b/sbroad-core/src/ir/transformation/split_columns.rs @@ -72,8 +72,7 @@ impl Plan { { if left_list.len() != right_list.len() { return Err(SbroadError::UnexpectedNumberOfValues(format!( - "left and right rows have different number of columns: {:?}, {:?}", - left_expr, right_expr + "left and right rows have different number of columns: {left_expr:?}, {right_expr:?}" ))); } let pairs = left_list diff --git a/sbroad-core/src/ir/tree/subtree.rs b/sbroad-core/src/ir/tree/subtree.rs index fbc0370890..eb3013c5e0 100644 --- a/sbroad-core/src/ir/tree/subtree.rs +++ b/sbroad-core/src/ir/tree/subtree.rs @@ -239,9 +239,8 @@ fn subtree_next<'plan>( // for selection filter or a join condition, we need to check whether // the reference points to an **additional** sub-query and then traverse // into it. Otherwise, stop traversal. - let parent_id = match exp.get_parent() { - Ok(parent_id) => parent_id, - Err(_) => return None, + let Ok(parent_id) = exp.get_parent() else { + return None }; if let Ok(rel_id) = iter .get_plan() diff --git a/sbroad-core/src/ir/tree/tests.rs b/sbroad-core/src/ir/tree/tests.rs index 18cb38df5f..cfe0ee8229 100644 --- a/sbroad-core/src/ir/tree/tests.rs +++ b/sbroad-core/src/ir/tree/tests.rs @@ -229,12 +229,9 @@ fn subtree_dfs_post() { .clone_row_list() .unwrap(); let alias_id = row_children.first().unwrap(); - let c_ref_id = - if let Expression::Alias { child, .. } = plan.get_expression_node(*alias_id).unwrap() { - child - } else { - panic!("invalid child in the row"); - }; + let Expression::Alias { child: c_ref_id, .. } = plan.get_expression_node(*alias_id).unwrap() else { + panic!("invalid child in the row"); + }; // Traverse relational nodes in the plan tree let mut dft_post = PostOrder::with_capacity(|node| plan.subtree_iter(node), plan.next_id()); diff --git a/sbroad-core/src/ir/value.rs b/sbroad-core/src/ir/value.rs index 246cdadfae..d702f37c9f 100644 --- a/sbroad-core/src/ir/value.rs +++ b/sbroad-core/src/ir/value.rs @@ -511,9 +511,8 @@ where Ok(v) => return Ok(Self::Tuple(v)), Err(lua) => lua, }; - let lua = match tlua::Null::lua_read_at_position(lua, index) { - Ok(_) => return Ok(Self::Null), - Err(lua) => lua, + let Err(lua) = tlua::Null::lua_read_at_position(lua, index) else { + return Ok(Self::Null) }; Err(lua) diff --git a/sbroad-core/src/otm/statistics.rs b/sbroad-core/src/otm/statistics.rs index e6e41b0ccc..599cafa960 100644 --- a/sbroad-core/src/otm/statistics.rs +++ b/sbroad-core/src/otm/statistics.rs @@ -67,9 +67,8 @@ impl Default for StatCollector { impl SpanProcessor for StatCollector { fn on_start(&self, span: &mut Span, _cx: &Context) { - let span_data = match span.exported_data() { - Some(span_data) => span_data, - None => return, + let Some(span_data) = span.exported_data() else { + return }; let id: String = match span_data.attributes.get(&"id".into()) { -- GitLab