From 60e8b4a9b8177420f09a87354f8e77605c2e116f Mon Sep 17 00:00:00 2001 From: Andrey Strochuk <a.strochuk@picodata.io> Date: Tue, 2 Apr 2024 13:59:55 +0300 Subject: [PATCH] Change String to SmolStr in SbroadError --- .../src/api/calculate_bucket_id.rs | 4 + sbroad-cartridge/src/cartridge.rs | 8 +- sbroad-cartridge/src/cartridge/config.rs | 35 +-- sbroad-cartridge/src/cartridge/router.rs | 40 +-- sbroad-cartridge/src/cartridge/storage.rs | 34 ++- sbroad-core/src/backend/sql/ir.rs | 29 +- sbroad-core/src/backend/sql/space.rs | 19 +- sbroad-core/src/backend/sql/tree.rs | 53 ++-- sbroad-core/src/cbo/helpers.rs | 16 +- sbroad-core/src/cbo/histogram.rs | 4 +- .../src/cbo/histogram/normalization.rs | 12 +- sbroad-core/src/cbo/selectivity.rs | 43 ++- sbroad-core/src/errors.rs | 204 ++++++------- sbroad-core/src/executor.rs | 11 +- sbroad-core/src/executor/bucket.rs | 4 +- sbroad-core/src/executor/engine.rs | 8 +- sbroad-core/src/executor/engine/helpers.rs | 288 +++++++++--------- .../engine/helpers/storage/runtime.rs | 14 +- .../src/executor/engine/helpers/vshard.rs | 42 +-- sbroad-core/src/executor/engine/mock.rs | 30 +- sbroad-core/src/executor/ir.rs | 88 +++--- sbroad-core/src/executor/lru.rs | 10 +- sbroad-core/src/executor/lru/tests.rs | 8 +- sbroad-core/src/executor/protocol.rs | 14 +- sbroad-core/src/executor/result.rs | 4 +- sbroad-core/src/executor/tests/frontend.rs | 16 +- sbroad-core/src/executor/vtable.rs | 49 ++- sbroad-core/src/frontend/sql.rs | 265 +++++++--------- sbroad-core/src/frontend/sql/ast.rs | 24 +- sbroad-core/src/frontend/sql/ir.rs | 40 +-- sbroad-core/src/frontend/sql/ir/tests/join.rs | 1 - sbroad-core/src/ir.rs | 98 +++--- sbroad-core/src/ir/acl.rs | 12 +- sbroad-core/src/ir/aggregates.rs | 34 +-- sbroad-core/src/ir/api/constant.rs | 6 +- sbroad-core/src/ir/api/parameter.rs | 63 ++-- sbroad-core/src/ir/block.rs | 10 +- sbroad-core/src/ir/ddl.rs | 10 +- sbroad-core/src/ir/distribution.rs | 26 +- sbroad-core/src/ir/explain.rs | 81 +++-- sbroad-core/src/ir/expression.rs | 60 ++-- sbroad-core/src/ir/expression/cast.rs | 6 +- sbroad-core/src/ir/expression/types.rs | 28 +- sbroad-core/src/ir/function.rs | 16 +- sbroad-core/src/ir/operator.rs | 109 ++++--- sbroad-core/src/ir/relation.rs | 79 ++--- sbroad-core/src/ir/relation/tests.rs | 13 +- sbroad-core/src/ir/transformation.rs | 46 ++- sbroad-core/src/ir/transformation/bool_in.rs | 5 +- .../src/ir/transformation/merge_tuples.rs | 27 +- .../src/ir/transformation/not_push_down.rs | 8 +- .../src/ir/transformation/redistribution.rs | 123 ++++---- .../ir/transformation/redistribution/dml.rs | 47 +-- .../transformation/redistribution/groupby.rs | 165 +++++----- .../redistribution/left_join.rs | 8 +- .../src/ir/transformation/split_columns.rs | 9 +- sbroad-core/src/ir/value.rs | 74 +++-- sbroad-core/src/ir/value/double.rs | 3 +- sbroad-core/src/otm.rs | 5 +- 59 files changed, 1270 insertions(+), 1318 deletions(-) diff --git a/sbroad-cartridge/src/api/calculate_bucket_id.rs b/sbroad-cartridge/src/api/calculate_bucket_id.rs index 78b955be7..5a1dacedd 100644 --- a/sbroad-cartridge/src/api/calculate_bucket_id.rs +++ b/sbroad-cartridge/src/api/calculate_bucket_id.rs @@ -106,7 +106,11 @@ impl TryFrom<&Tuple> for Args { format_smolstr!( "expected string, tuple with a space name, or map with a space name as an argument, \ got args {:?}", +<<<<<<< HEAD &tuple +======= + &value +>>>>>>> eac5d15 (Change String to SmolStr in SbroadError) ), )) } diff --git a/sbroad-cartridge/src/cartridge.rs b/sbroad-cartridge/src/cartridge.rs index 6585e4b47..b8b8d7307 100644 --- a/sbroad-cartridge/src/cartridge.rs +++ b/sbroad-cartridge/src/cartridge.rs @@ -8,7 +8,7 @@ use std::cell::Ref; use sbroad::error; use sbroad::errors::SbroadError; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use tarantool::tlua::LuaFunction; /// Cartridge cluster configuration provider. @@ -57,9 +57,9 @@ fn bucket_count() -> Result<u64, SbroadError> { Ok(v) => v, Err(e) => { error!(Option::from("set_bucket_count"), &format!("{e:?}")); - return Err(SbroadError::LuaError( - format!("Failed lua function load: {e}").into(), - )); + return Err(SbroadError::LuaError(format_smolstr!( + "Failed lua function load: {e}" + ))); } }; diff --git a/sbroad-cartridge/src/cartridge/config.rs b/sbroad-cartridge/src/cartridge/config.rs index 0989500e0..aa4704d58 100644 --- a/sbroad-cartridge/src/cartridge/config.rs +++ b/sbroad-cartridge/src/cartridge/config.rs @@ -2,7 +2,7 @@ extern crate yaml_rust; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::collections::HashMap; use yaml_rust::{Yaml, YamlLoader}; @@ -97,12 +97,9 @@ impl RouterConfiguration { None => { return Err(SbroadError::Invalid( Entity::ClusterSchema, - Some( - format!( - "column name of table {current_space_name} is invalid" - ) - .into(), - ), + Some(format_smolstr!( + "column name of table {current_space_name} is invalid" + )), )) } }; @@ -111,9 +108,9 @@ impl RouterConfiguration { None => { return Err(SbroadError::Invalid( Entity::ClusterSchema, - Some(format!( + Some(format_smolstr!( "Type not found for columns {name} of table {current_space_name}" - ).into()), + )), )) } }; @@ -122,12 +119,9 @@ impl RouterConfiguration { None => { return Err(SbroadError::Invalid( Entity::ClusterSchema, - Some( - format!( + Some(format_smolstr!( "column is_nullable of table {current_space_name} is invalid" - ) - .into(), - ), + )), )) } }; @@ -186,25 +180,22 @@ impl RouterConfiguration { let pk = indexes.first().ok_or_else(|| { SbroadError::NotFound( Entity::PrimaryKey, - format!("for space {current_space_name}").into(), + format_smolstr!("for space {current_space_name}"), ) })?; let pk_parts = pk["parts"].as_vec().ok_or_else(|| { SbroadError::Invalid( Entity::PrimaryKey, - Some( - format!( - "for space {current_space_name}: failed to get index parts" - ) - .into(), - ), + Some(format_smolstr!( + "for space {current_space_name}: failed to get index parts" + )), ) })?; pk_parts.iter().map(|p| { let name = p["path"].as_str().ok_or_else(|| SbroadError::Invalid( Entity::PrimaryKey, - Some(format!("for space {current_space_name}: failed to get index part field").into())) + Some(format_smolstr!("for space {current_space_name}: failed to get index part field"))) )?; Ok(normalize_name_from_schema(name)) }).collect::<Result<Vec<SmolStr>, SbroadError>>()? diff --git a/sbroad-cartridge/src/cartridge/router.rs b/sbroad-cartridge/src/cartridge/router.rs index b7855771e..1216d3f54 100644 --- a/sbroad-cartridge/src/cartridge/router.rs +++ b/sbroad-cartridge/src/cartridge/router.rs @@ -5,7 +5,7 @@ use sbroad::executor::engine::helpers::vshard::{ exec_ir_on_all_buckets, exec_ir_on_some_buckets, get_random_bucket, }; use sbroad::executor::engine::{QueryCache, Vshard}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::any::Any; use std::cell::{Ref, RefCell}; @@ -48,7 +48,7 @@ use super::ConfigurationProvider; pub struct RouterRuntime { metadata: RefCell<RouterConfiguration>, bucket_count: u64, - ir_cache: RefCell<LRUCache<String, Plan>>, + ir_cache: RefCell<LRUCache<SmolStr, Plan>>, } impl ConfigurationProvider for RouterRuntime { @@ -59,7 +59,7 @@ impl ConfigurationProvider for RouterRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) }) } @@ -69,7 +69,7 @@ impl ConfigurationProvider for RouterRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; *metadata = Self::Configuration::new(); @@ -81,7 +81,7 @@ impl ConfigurationProvider for RouterRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; Ok(metadata.is_empty()) @@ -97,7 +97,7 @@ impl ConfigurationProvider for RouterRuntime { Ok(res) => res, Err(e) => { error!(Option::from("getting schema"), &format!("{e:?}")); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; @@ -106,7 +106,7 @@ impl ConfigurationProvider for RouterRuntime { Ok(res) => res, Err(e) => { error!(Option::from("getting waiting timeout"), &format!("{e:?}")); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; @@ -118,7 +118,9 @@ impl ConfigurationProvider for RouterRuntime { usize::try_from(val).map_err(|_| { SbroadError::Invalid( Entity::Cache, - Some(format!("router cache capacity is too big: {capacity}").into()), + Some(format_smolstr!( + "router cache capacity is too big: {capacity}" + )), ) })? } @@ -127,7 +129,7 @@ impl ConfigurationProvider for RouterRuntime { Option::from("getting router cache capacity"), &format!("{e:?}"), ); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; @@ -136,7 +138,7 @@ impl ConfigurationProvider for RouterRuntime { Ok(column) => column, Err(e) => { error!(Option::from("getting sharding column"), &format!("{e:?}")); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; @@ -157,7 +159,7 @@ impl ConfigurationProvider for RouterRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; *cached_metadata = metadata; @@ -166,7 +168,7 @@ impl ConfigurationProvider for RouterRuntime { } impl QueryCache for RouterRuntime { - type Cache = LRUCache<String, Plan>; + type Cache = LRUCache<SmolStr, Plan>; fn cache(&self) -> &RefCell<Self::Cache> where @@ -182,7 +184,7 @@ impl QueryCache for RouterRuntime { self.ir_cache .try_borrow_mut() .map_err(|e| { - SbroadError::FailedTo(Action::Clear, Some(Entity::Cache), format!("{e:?}").into()) + SbroadError::FailedTo(Action::Clear, Some(Entity::Cache), format_smolstr!("{e:?}")) })? .clear()?; Ok(()) @@ -193,7 +195,7 @@ impl QueryCache for RouterRuntime { .cache() .try_borrow() .map_err(|e| { - SbroadError::FailedTo(Action::Borrow, Some(Entity::Cache), format!("{e}").into()) + SbroadError::FailedTo(Action::Borrow, Some(Entity::Cache), format_smolstr!("{e}")) })? .capacity()) } @@ -216,7 +218,7 @@ impl Router for RouterRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) }) } @@ -232,7 +234,7 @@ impl Router for RouterRuntime { dispatch_impl(self, plan, top_id, buckets) } - fn explain_format(&self, explain: String) -> Result<Box<dyn Any>, SbroadError> { + fn explain_format(&self, explain: SmolStr) -> Result<Box<dyn Any>, SbroadError> { explain_format(&explain) } @@ -256,7 +258,7 @@ impl Router for RouterRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) })?; sharding_key_from_map(&*metadata, &space, map) @@ -290,7 +292,7 @@ impl Statistics for RouterRuntime { #[allow(unused_variables)] fn update_table_stats( &mut self, - table_name: String, + table_name: SmolStr, table_stats: TableStats, ) -> Result<(), SbroadError> { // Will be added later. @@ -314,7 +316,7 @@ impl RouterRuntime { /// # Errors /// - Failed to detect the correct amount of buckets. pub fn new() -> Result<Self, SbroadError> { - let cache: LRUCache<String, Plan> = LRUCache::new(DEFAULT_CAPACITY, None)?; + let cache: LRUCache<SmolStr, Plan> = LRUCache::new(DEFAULT_CAPACITY, None)?; let result = RouterRuntime { metadata: RefCell::new(RouterConfiguration::new()), bucket_count: bucket_count()?, diff --git a/sbroad-cartridge/src/cartridge/storage.rs b/sbroad-cartridge/src/cartridge/storage.rs index 0c818b42e..83a60df40 100644 --- a/sbroad-cartridge/src/cartridge/storage.rs +++ b/sbroad-cartridge/src/cartridge/storage.rs @@ -13,7 +13,7 @@ use sbroad::executor::lru::{Cache, LRUCache, DEFAULT_CAPACITY}; use sbroad::executor::protocol::{Binary, RequiredData, SchemaInfo}; use sbroad::ir::value::Value; use sbroad::{debug, error, warn}; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::any::Any; use std::cell::{Ref, RefCell}; use std::fmt::Display; @@ -28,19 +28,19 @@ pub struct StorageRuntime { cache: RefCell<CartridgeCache>, } -pub struct CartridgeCache(LRUCache<String, PreparedStmt>); +pub struct CartridgeCache(LRUCache<SmolStr, PreparedStmt>); impl StorageCache for CartridgeCache { fn put( &mut self, - plan_id: String, + plan_id: SmolStr, stmt: PreparedStmt, _: &SchemaInfo, ) -> Result<(), SbroadError> { self.0.put(plan_id, stmt) } - fn get(&mut self, plan_id: &String) -> Result<Option<&PreparedStmt>, SbroadError> { + fn get(&mut self, plan_id: &SmolStr) -> Result<Option<&PreparedStmt>, SbroadError> { self.0.get(plan_id) } @@ -61,7 +61,11 @@ impl QueryCache for StorageRuntime { .cache() .try_borrow() .map_err(|e| { - SbroadError::FailedTo(Action::Borrow, Some(Entity::Cache), format!("{e:?}").into()) + SbroadError::FailedTo( + Action::Borrow, + Some(Entity::Cache), + format_smolstr!("{e:?}"), + ) })? .0 .capacity()) @@ -71,7 +75,7 @@ impl QueryCache for StorageRuntime { self.cache .try_borrow_mut() .map_err(|e| { - SbroadError::FailedTo(Action::Clear, Some(Entity::Cache), format!("{e:?}").into()) + SbroadError::FailedTo(Action::Clear, Some(Entity::Cache), format_smolstr!("{e:?}")) })? .clear()?; Ok(()) @@ -94,7 +98,7 @@ impl ConfigurationProvider for StorageRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) }) } @@ -104,7 +108,7 @@ impl ConfigurationProvider for StorageRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; *metadata = Self::Configuration::new(); @@ -116,7 +120,7 @@ impl ConfigurationProvider for StorageRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) })?; Ok(metadata.is_empty()) @@ -135,11 +139,11 @@ impl ConfigurationProvider for StorageRuntime { Option::from("getting storage cache capacity"), &format!("{e:?}"), ); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; let storage_capacity = usize::try_from(capacity) - .map_err(|e| SbroadError::Invalid(Entity::Cache, Some(format!("{e:?}").into())))?; + .map_err(|e| SbroadError::Invalid(Entity::Cache, Some(format_smolstr!("{e:?}"))))?; let storage_cache_size_bytes: LuaFunction<_> = lua.eval("return get_storage_cache_size_bytes;").unwrap(); @@ -150,11 +154,11 @@ impl ConfigurationProvider for StorageRuntime { Option::from("getting storage cache size bytes"), &format!("{e:?}"), ); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; let storage_size_bytes = usize::try_from(cache_size_bytes) - .map_err(|e| SbroadError::Invalid(Entity::Cache, Some(format!("{e}").into())))?; + .map_err(|e| SbroadError::Invalid(Entity::Cache, Some(format_smolstr!("{e}"))))?; let mut metadata = StorageConfiguration::new(); metadata.storage_capacity = storage_capacity; @@ -170,7 +174,7 @@ impl ConfigurationProvider for StorageRuntime { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) })?; let storage_size_bytes = metadata.storage_size_bytes; @@ -232,7 +236,7 @@ impl StorageRuntime { /// # Errors /// - Failed to initialize the LRU cache. pub fn new() -> Result<Self, SbroadError> { - let cache: LRUCache<String, PreparedStmt> = + let cache: LRUCache<SmolStr, PreparedStmt> = LRUCache::new(DEFAULT_CAPACITY, Some(Box::new(unprepare)))?; let result = StorageRuntime { metadata: RefCell::new(StorageConfiguration::new()), diff --git a/sbroad-core/src/backend/sql/ir.rs b/sbroad-core/src/backend/sql/ir.rs index 42a5a2c65..6c5b85b7c 100644 --- a/sbroad-core/src/backend/sql/ir.rs +++ b/sbroad-core/src/backend/sql/ir.rs @@ -2,7 +2,7 @@ use crate::debug; use ahash::AHashMap; use opentelemetry::Context; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::collections::hash_map::IntoIter; use std::collections::HashMap; use std::fmt::Write as _; @@ -57,7 +57,7 @@ impl TryFrom<&Tuple> for PatternWithParams { Ok(encoded) => Ok(PatternWithParams::try_from(encoded)?), Err(e) => Err(SbroadError::ParsingError( Entity::PatternWithParams, - format!("{e:?}").into(), + format_smolstr!("{e:?}"), )), } } @@ -150,12 +150,12 @@ impl From<PatternWithParams> for String { #[derive(Debug)] pub struct TmpSpaceMap { - inner: AHashMap<String, TmpSpace>, + inner: AHashMap<SmolStr, TmpSpace>, } impl IntoIterator for TmpSpaceMap { - type Item = (String, TmpSpace); - type IntoIter = IntoIter<String, TmpSpace>; + type Item = (SmolStr, TmpSpace); + type IntoIter = IntoIter<SmolStr, TmpSpace>; fn into_iter(self) -> Self::IntoIter { self.inner.into_iter() @@ -173,12 +173,12 @@ impl TmpSpaceMap { self.inner.get(name) } - fn insert(&mut self, name: String, space: TmpSpace) -> Result<(), SbroadError> { + fn insert(&mut self, name: SmolStr, space: TmpSpace) -> Result<(), SbroadError> { if self.inner.contains_key(&name) { return Err(SbroadError::FailedTo( Action::Insert, Some(Entity::Space), - format!("in the temporary space map ({name})").into(), + format_smolstr!("in the temporary space map ({name})"), )); } self.inner.insert(name, space); @@ -206,7 +206,7 @@ impl ExecutionPlan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("parameter {value:?} is not a constant").into()), + Some(format_smolstr!("parameter {value:?} is not a constant")), )); } } @@ -376,7 +376,7 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Put, Some(Entity::Value), - format!("constant value to SQL: {e}").into(), + format_smolstr!("constant value to SQL: {e}"), ) })?; } @@ -394,10 +394,9 @@ impl ExecutionPlan { .ok_or_else(|| { SbroadError::NotFound( Entity::Name, - format!( + format_smolstr!( "for column at position {position}" - ) - .into(), + ), ) })?; if let Some(name) = (*vt).get_alias() { @@ -444,7 +443,7 @@ impl ExecutionPlan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("parameter {value:?} is not a constant").into()), + Some(format_smolstr!("parameter {value:?} is not a constant")), )); } } @@ -460,7 +459,7 @@ impl ExecutionPlan { { c.name.clone() } else { - SmolStr::from(format!("\"{}\"", c.name)) + format_smolstr!("\"{}\"", c.name) } }) .collect::<Vec<_>>() @@ -469,7 +468,7 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Serialize, Some(Entity::VirtualTable), - format!("SQL builder: {e}").into(), + format_smolstr!("SQL builder: {e}"), ) })?; // BETWEEN can refer to the same virtual table multiple times. diff --git a/sbroad-core/src/backend/sql/space.rs b/sbroad-core/src/backend/sql/space.rs index 2dc6318a7..62210140e 100644 --- a/sbroad-core/src/backend/sql/space.rs +++ b/sbroad-core/src/backend/sql/space.rs @@ -15,11 +15,12 @@ mod prod_imports { #[cfg(not(feature = "mock"))] use prod_imports::*; +use smol_str::{format_smolstr, SmolStr}; #[allow(clippy::module_name_repetitions)] #[derive(Hash, Eq, PartialEq, Debug)] pub struct TmpSpace { - pub name: String, + pub name: SmolStr, } impl TmpSpace { @@ -74,7 +75,7 @@ impl TmpSpace { SbroadError::FailedTo( Action::Create, Some(Entity::Space), - format!("{name}: {e}").into(), + format_smolstr!("{name}: {e}"), ) })?; let cleanup = |space: Space| match space.drop() { @@ -93,7 +94,7 @@ impl TmpSpace { return Err(SbroadError::FailedTo( Action::Create, Some(Entity::Index), - format!("{pk_name} for space {name}: {e}").into(), + format_smolstr!("{pk_name} for space {name}: {e}"), )); } } @@ -111,7 +112,7 @@ impl TmpSpace { return Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Bytes), - format!("to tuple: {e}").into(), + format_smolstr!("to tuple: {e}"), )); } }; @@ -122,7 +123,7 @@ impl TmpSpace { return Err(SbroadError::FailedTo( Action::Insert, Some(Entity::Tuple), - format!("tuple {tuple:?} into {name}: {e}").into(), + format_smolstr!("tuple {tuple:?} into {name}: {e}"), )); } } @@ -132,13 +133,13 @@ impl TmpSpace { } #[must_use] - pub fn generate_space_name(base: &str, motion_id: usize) -> String { - format!("TMP_{base}_{motion_id}") + pub fn generate_space_name(base: &str, motion_id: usize) -> SmolStr { + format_smolstr!("TMP_{base}_{motion_id}") } #[must_use] - pub fn generate_pk_name(base: &str, motion_id: usize) -> String { - format!("PK_TMP_{base}_{motion_id}") + pub fn generate_pk_name(base: &str, motion_id: usize) -> SmolStr { + format_smolstr!("PK_TMP_{base}_{motion_id}") } } diff --git a/sbroad-core/src/backend/sql/tree.rs b/sbroad-core/src/backend/sql/tree.rs index 5b13a23df..0b09f69a8 100644 --- a/sbroad-core/src/backend/sql/tree.rs +++ b/sbroad-core/src/backend/sql/tree.rs @@ -1,6 +1,6 @@ use ahash::RandomState; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::collections::HashMap; use std::mem::take; @@ -33,7 +33,7 @@ pub enum SyntaxData { /// "distinct" Distinct, /// Inline sql string - Inline(String), + Inline(SmolStr), /// "from" From, /// "leading" @@ -45,7 +45,7 @@ pub enum SyntaxData { /// "(" OpenParenthesis, /// "=, >, <, and, or, ..." - Operator(String), + Operator(SmolStr), /// plan node id PlanId(usize), /// parameter (a wrapper over a plan constants) @@ -327,7 +327,7 @@ impl SyntaxNodes { return Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::SyntaxNodes), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), )) } }; @@ -340,7 +340,7 @@ impl SyntaxNodes { /// - current node is invalid (doesn't exist in arena) pub fn get_syntax_node(&self, id: usize) -> Result<&SyntaxNode, SbroadError> { self.arena.get(id).ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("from arena with index {id}").into()) + SbroadError::NotFound(Entity::Node, format_smolstr!("from arena with index {id}")) }) } @@ -352,7 +352,7 @@ impl SyntaxNodes { self.arena.get_mut(id).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(mutable) from arena with index {id}").into(), + format_smolstr!("(mutable) from arena with index {id}"), ) }) } @@ -363,7 +363,7 @@ impl SyntaxNodes { /// - nothing was found fn get_syntax_node_id(&self, plan_id: usize) -> Result<usize, SbroadError> { self.map.get(&plan_id).copied().ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("({plan_id}) in the map").into()) + SbroadError::NotFound(Entity::Node, format_smolstr!("({plan_id}) in the map")) }) } @@ -510,15 +510,21 @@ impl<'p> SyntaxPlan<'p> { match node { Node::Ddl(..) => Err(SbroadError::Invalid( Entity::SyntaxPlan, - Some(format!("DDL node {node:?} is not supported in the syntax plan").into()), + Some(format_smolstr!( + "DDL node {node:?} is not supported in the syntax plan" + )), )), Node::Acl(..) => Err(SbroadError::Invalid( Entity::SyntaxPlan, - Some(format!("ACL node {node:?} is not supported in the syntax plan").into()), + Some(format_smolstr!( + "ACL node {node:?} is not supported in the syntax plan" + )), )), Node::Block(..) => Err(SbroadError::Invalid( Entity::SyntaxPlan, - Some(format!("Block node {node:?} is not supported in the syntax plan").into()), + Some(format_smolstr!( + "Block node {node:?} is not supported in the syntax plan" + )), )), Node::Parameter => { let sn = SyntaxNode::new_parameter(id); @@ -529,7 +535,9 @@ impl<'p> SyntaxPlan<'p> { | Relational::Delete { .. } | Relational::Update { .. } => Err(SbroadError::Invalid( Entity::SyntaxPlan, - Some(format!("DML node {node:?} is not supported in the syntax plan").into()), + Some(format_smolstr!( + "DML node {node:?} is not supported in the syntax plan" + )), )), Relational::Join { children, @@ -622,9 +630,9 @@ impl<'p> SyntaxPlan<'p> { children, filter, .. } => { let left_id = *children.first().ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("{node:?} has no children.").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "{node:?} has no children." + )) })?; let filter_id = match self.snapshot { Snapshot::Latest => *filter, @@ -714,7 +722,7 @@ impl<'p> SyntaxPlan<'p> { let is_enabled = matches!(op, MotionOpcode::SerializeAsEmptyTable(true)); if is_enabled { let output_len = self.plan.get_ir_plan().get_row_list(*output)?.len(); - let empty_select = format!( + let empty_select = format_smolstr!( "select {}null where false", "null, ".repeat(output_len - 1) ); @@ -732,10 +740,9 @@ impl<'p> SyntaxPlan<'p> { let child_sp_id = *self.nodes.map.get(&child_plan_id).ok_or_else(|| { SbroadError::Invalid( Entity::SyntaxPlan, - Some( - format!("motion child {child_plan_id} is not found in map") - .into(), - ), + Some(format_smolstr!( + "motion child {child_plan_id} is not found in map" + )), ) })?; self.nodes.map.insert(id, child_sp_id); @@ -758,9 +765,9 @@ impl<'p> SyntaxPlan<'p> { if name.is_empty() { return Err(SbroadError::Invalid( Entity::VirtualTable, - Some( - format!("Vtable {vtable:?} has an empty alias name").into(), - ), + Some(format_smolstr!( + "Vtable {vtable:?} has an empty alias name" + )), )); } children.push( @@ -1281,7 +1288,7 @@ impl OrderedSyntaxNodes { .arena .get(*id) .ok_or_else(|| { - SbroadError::NotFound(Entity::SyntaxNode, format!("(id {id})").into()) + SbroadError::NotFound(Entity::SyntaxNode, format_smolstr!("(id {id})")) })? .data, ); diff --git a/sbroad-core/src/cbo/helpers.rs b/sbroad-core/src/cbo/helpers.rs index 529f62326..6021f5ac9 100644 --- a/sbroad-core/src/cbo/helpers.rs +++ b/sbroad-core/src/cbo/helpers.rs @@ -1,7 +1,7 @@ use crate::errors::{Entity, SbroadError}; use crate::ir::value::double::Double; use itertools::enumerate; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use tarantool::decimal; use tarantool::decimal::Decimal; @@ -96,9 +96,9 @@ impl<'bytes> Bytes<'bytes> { let base_shift = Decimal::pow(base, power).ok_or_else(|| { SbroadError::Invalid( Entity::Statistics, - Some( - format!("Unable to raise a Decimal {base} to chosen power {power}").into(), - ), + Some(format_smolstr!( + "Unable to raise a Decimal {base} to chosen power {power}" + )), ) })?; result += Decimal::from(constrained_byte - low_bound) * base_shift; @@ -357,8 +357,8 @@ pub fn decimal_boundaries_occupied_fraction( Err( SbroadError::Invalid( Entity::Value, - Some(format!( - "Converted high_bound {right_boundary} must be greater than converted low_bound {left_boundary}").into() + Some(format_smolstr!( + "Converted high_bound {right_boundary} must be greater than converted low_bound {left_boundary}") ), ) ) @@ -366,8 +366,8 @@ pub fn decimal_boundaries_occupied_fraction( Err( SbroadError::Invalid( Entity::Value, - Some(format!( - "Converted value {value} must lie between converted low_bound {left_boundary} and converted high_bound {right_boundary}").into() + Some(format_smolstr!( + "Converted value {value} must lie between converted low_bound {left_boundary} and converted high_bound {right_boundary}") ), ) ) diff --git a/sbroad-core/src/cbo/histogram.rs b/sbroad-core/src/cbo/histogram.rs index 43e6eb850..5d6137a19 100644 --- a/sbroad-core/src/cbo/histogram.rs +++ b/sbroad-core/src/cbo/histogram.rs @@ -10,7 +10,7 @@ use crate::errors::{Entity, SbroadError}; use crate::ir::value::double::Double; use itertools::enumerate; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::Debug; @@ -168,7 +168,7 @@ impl Scalar for Double { } else { Err(SbroadError::Invalid( Entity::Statistics, - Some(format!("Boundaries occupied fraction calculation resulted in invalid f64 fraction: {fraction_f64}").into()) + Some(format_smolstr!("Boundaries occupied fraction calculation resulted in invalid f64 fraction: {fraction_f64}")) )) } } diff --git a/sbroad-core/src/cbo/histogram/normalization.rs b/sbroad-core/src/cbo/histogram/normalization.rs index 20111944d..338ae5eb1 100644 --- a/sbroad-core/src/cbo/histogram/normalization.rs +++ b/sbroad-core/src/cbo/histogram/normalization.rs @@ -3,7 +3,7 @@ use crate::cbo::histogram::{Bucket, BucketType, HistogramBuckets, Scalar}; use crate::errors::{Entity, SbroadError}; use itertools::enumerate; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::cmp::Ordering; use tarantool::decimal; use tarantool::decimal::Decimal; @@ -77,7 +77,9 @@ pub fn get_expected_number_of_buckets() -> Result<u64, SbroadError> { let Ok(decimal_error) = Decimal::try_from(EXPECTED_MERGING_ERROR) else { return Err(SbroadError::Invalid( Entity::Value, - Some(format!("Unable to convert {EXPECTED_MERGING_ERROR} to decimal").into()), + Some(format_smolstr!( + "Unable to convert {EXPECTED_MERGING_ERROR} to decimal" + )), )); }; let number_of_buckets = @@ -87,7 +89,9 @@ pub fn get_expected_number_of_buckets() -> Result<u64, SbroadError> { } else { Err(SbroadError::Invalid( Entity::Value, - Some(format!("Unable to convert {number_of_buckets} to u64").into()), + Some(format_smolstr!( + "Unable to convert {number_of_buckets} to u64" + )), )) } } @@ -105,7 +109,7 @@ pub fn get_max_buckets_frequency_error(total_buckets_rows_number: u64) -> Result } else { Err(SbroadError::Invalid( Entity::Value, - Some(format!("Unable to convert {error} to u64").into()), + Some(format_smolstr!("Unable to convert {error} to u64")), )) } } diff --git a/sbroad-core/src/cbo/selectivity.rs b/sbroad-core/src/cbo/selectivity.rs index 929feb06d..7e36df176 100644 --- a/sbroad-core/src/cbo/selectivity.rs +++ b/sbroad-core/src/cbo/selectivity.rs @@ -11,7 +11,7 @@ use crate::ir::operator::Bool; use crate::ir::relation::{Column, Type}; use crate::ir::value::double::Double; use crate::ir::value::Value; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::any::Any; use std::fmt::Display; use std::num::TryFromIntError; @@ -162,12 +162,9 @@ fn downcast_column_stats<'stats, T: Scalar>( } else { Err(SbroadError::Invalid( Entity::Statistics, - Some( - format!( - "Unable to downcast {column_name} column statistics to {column_type:?} type" - ) - .into(), - ), + Some(format_smolstr!( + "Unable to downcast {column_name} column statistics to {column_type:?} type" + )), )) } } @@ -182,7 +179,7 @@ pub fn decimal_from_str(value: &dyn Display) -> Result<Decimal, SbroadError> { } else { Err(SbroadError::Invalid( Entity::Value, - Some(format!("Unable to cast {value} to decimal").into()), + Some(format_smolstr!("Unable to cast {value} to decimal")), )) } } @@ -197,7 +194,7 @@ pub fn double_from_str(value: &dyn Display) -> Result<Double, SbroadError> { } else { Err(SbroadError::Invalid( Entity::Value, - Some(format!("Unable to cast {value} to double").into()), + Some(format_smolstr!("Unable to cast {value} to double")), )) } } @@ -250,17 +247,18 @@ pub fn calculate_filter_selectivity( let column = table.columns.get(*colum_index).ok_or_else(|| { SbroadError::Invalid( Entity::Statistics, - Some(format!("Column with name {table_name} is not found in metadata",).into()), + Some(format_smolstr!( + "Column with name {table_name} is not found in metadata", + )), ) })?; let column_type = &column.r#type; let types_mismatch_error = Err(SbroadError::Invalid( Entity::Statistics, - Some( - format!("Column type {column_type:?} mismatches with constant type {constant:?}") - .into(), - ), + Some(format_smolstr!( + "Column type {column_type:?} mismatches with constant type {constant:?}" + )), )); match column_type { @@ -370,7 +368,9 @@ pub fn calculate_condition_selectivity( let left_column = left_table.columns.get(*left_colum_index).ok_or_else(|| { SbroadError::Invalid( Entity::Statistics, - Some(format!("Column with name {left_table_name} is not found in metadata",).into()), + Some(format_smolstr!( + "Column with name {left_table_name} is not found in metadata", + )), ) })?; let left_column_type = &left_column.r#type; @@ -387,19 +387,18 @@ pub fn calculate_condition_selectivity( let right_column = right_table.columns.get(*right_colum_index).ok_or_else(|| { SbroadError::Invalid( Entity::Statistics, - Some(format!("Column with name {right_table_name} is not found in metadata",).into()), + Some(format_smolstr!( + "Column with name {right_table_name} is not found in metadata", + )), ) })?; let right_column_type = &right_column.r#type; let types_mismatch_error = Err(SbroadError::Invalid( Entity::Statistics, - Some( - format!( - "Column types {left_column_type:?} and {right_column_type:?} doesn't correspond." - ) - .into(), - ), + Some(format_smolstr!( + "Column types {left_column_type:?} and {right_column_type:?} doesn't correspond." + )), )); match (left_column_type, right_column_type) { diff --git a/sbroad-core/src/errors.rs b/sbroad-core/src/errors.rs index a0ec18104..952d8f63d 100644 --- a/sbroad-core/src/errors.rs +++ b/sbroad-core/src/errors.rs @@ -1,5 +1,5 @@ use serde::Serialize; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::fmt; use tarantool::error::Error; use tarantool::transaction::TransactionError; @@ -148,73 +148,73 @@ pub enum Entity { impl fmt::Display for Entity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let p = match self { - Entity::Acl => "ACL".to_string(), - Entity::Args => "args".to_string(), - Entity::AST => "AST".to_string(), - Entity::Aggregate => "aggregate".to_string(), - Entity::AggregateCollector => "aggregate collector".to_string(), - Entity::AggregateSignature => "aggregate signature".to_string(), - Entity::Buckets => "buckets".to_string(), - Entity::Bytes => "bytes".to_string(), - Entity::Cache => "cache".to_string(), - Entity::Chain => "chain".to_string(), - Entity::ClusterSchema => "cluster schema".to_string(), - Entity::Column => "column".to_string(), - Entity::Distribution => "distribution".to_string(), - Entity::DistributionKey => "distribution key".to_string(), - Entity::Engine => "engine".to_string(), - Entity::Expression => "expression".to_string(), - Entity::ExpressionMapper => "expression mapper".to_string(), - Entity::Histogram => "histogram".to_string(), - Entity::Index => "index".to_string(), - Entity::KeyDef => "key definition".to_string(), - Entity::Metadata => "metadata".to_string(), - Entity::Motion => "motion".to_string(), - Entity::MotionOpcode => "motion opcode".to_string(), - Entity::MsgPack => "msgpack".to_string(), - Entity::Name => "name".to_string(), - Entity::Node => "node".to_string(), - Entity::Operator => "operator".to_string(), - Entity::PatternWithParams => "pattern with parameters".to_string(), - Entity::Plan => "plan".to_string(), - Entity::PrimaryKey => "primary key".to_string(), - Entity::Privilege => "privilege".to_string(), - Entity::ProducerResult => "producer result".to_string(), - Entity::ParseNode => "parse node".to_string(), - Entity::Query => "query".to_string(), - Entity::Relational => "relational".to_string(), - Entity::RequiredData => "required data".to_string(), - Entity::ReferredNodes => "referred nodes".to_string(), - Entity::Routine => "routine".to_string(), - Entity::Rule => "rule".to_string(), - Entity::Runtime => "runtime".to_string(), - Entity::Option => "option".to_string(), - Entity::OptionalData => "optional data".to_string(), - Entity::OptionSpec => "OptionSpec".to_string(), - Entity::Schema => "schema".to_string(), - Entity::ShardingKey => "sharding key".to_string(), - Entity::Space => "space".to_string(), - Entity::SpaceEngine => "space engine".to_string(), - Entity::SpaceMetadata => "space metadata".to_string(), - Entity::SQLFunction => "SQL function".to_string(), - Entity::Statement => "statement".to_string(), - Entity::Statistics => "statistics".to_string(), - Entity::SubQuery => "sub-query plan subtree".to_string(), - Entity::SubTree => "execution plan subtree".to_string(), - Entity::SyntaxNode => "syntax node".to_string(), - Entity::SyntaxNodes => "syntax nodes".to_string(), - Entity::SyntaxPlan => "syntax plan".to_string(), - Entity::Table => "table".to_string(), - Entity::Tarantool => "tarantool".to_string(), - Entity::Target => "target".to_string(), - Entity::Transaction => "transaction".to_string(), - Entity::Tuple => "tuple".to_string(), - Entity::TupleBuilderCommand => "TupleBuilderCommand".to_string(), - Entity::Type => "type".to_string(), - Entity::Update => "Update node".to_string(), - Entity::Value => "value".to_string(), - Entity::VirtualTable => "virtual table".to_string(), - Entity::VTableKey => "virtual table key".to_string(), + Entity::Acl => "ACL".to_smolstr(), + Entity::Args => "args".to_smolstr(), + Entity::AST => "AST".to_smolstr(), + Entity::Aggregate => "aggregate".to_smolstr(), + Entity::AggregateCollector => "aggregate collector".to_smolstr(), + Entity::AggregateSignature => "aggregate signature".to_smolstr(), + Entity::Buckets => "buckets".to_smolstr(), + Entity::Bytes => "bytes".to_smolstr(), + Entity::Cache => "cache".to_smolstr(), + Entity::Chain => "chain".to_smolstr(), + Entity::ClusterSchema => "cluster schema".to_smolstr(), + Entity::Column => "column".to_smolstr(), + Entity::Distribution => "distribution".to_smolstr(), + Entity::DistributionKey => "distribution key".to_smolstr(), + Entity::Engine => "engine".to_smolstr(), + Entity::Expression => "expression".to_smolstr(), + Entity::ExpressionMapper => "expression mapper".to_smolstr(), + Entity::Histogram => "histogram".to_smolstr(), + Entity::Index => "index".to_smolstr(), + Entity::KeyDef => "key definition".to_smolstr(), + Entity::Metadata => "metadata".to_smolstr(), + Entity::Motion => "motion".to_smolstr(), + Entity::MotionOpcode => "motion opcode".to_smolstr(), + Entity::MsgPack => "msgpack".to_smolstr(), + Entity::Name => "name".to_smolstr(), + Entity::Node => "node".to_smolstr(), + Entity::Operator => "operator".to_smolstr(), + Entity::PatternWithParams => "pattern with parameters".to_smolstr(), + Entity::Plan => "plan".to_smolstr(), + Entity::PrimaryKey => "primary key".to_smolstr(), + Entity::Privilege => "privilege".to_smolstr(), + Entity::ProducerResult => "producer result".to_smolstr(), + Entity::ParseNode => "parse node".to_smolstr(), + Entity::Query => "query".to_smolstr(), + Entity::Relational => "relational".to_smolstr(), + Entity::RequiredData => "required data".to_smolstr(), + Entity::ReferredNodes => "referred nodes".to_smolstr(), + Entity::Routine => "routine".to_smolstr(), + Entity::Rule => "rule".to_smolstr(), + Entity::Runtime => "runtime".to_smolstr(), + Entity::Option => "option".to_smolstr(), + Entity::OptionalData => "optional data".to_smolstr(), + Entity::OptionSpec => "OptionSpec".to_smolstr(), + Entity::Schema => "schema".to_smolstr(), + Entity::ShardingKey => "sharding key".to_smolstr(), + Entity::Space => "space".to_smolstr(), + Entity::SpaceEngine => "space engine".to_smolstr(), + Entity::SpaceMetadata => "space metadata".to_smolstr(), + Entity::SQLFunction => "SQL function".to_smolstr(), + Entity::Statement => "statement".to_smolstr(), + Entity::Statistics => "statistics".to_smolstr(), + Entity::SubQuery => "sub-query plan subtree".to_smolstr(), + Entity::SubTree => "execution plan subtree".to_smolstr(), + Entity::SyntaxNode => "syntax node".to_smolstr(), + Entity::SyntaxNodes => "syntax nodes".to_smolstr(), + Entity::SyntaxPlan => "syntax plan".to_smolstr(), + Entity::Table => "table".to_smolstr(), + Entity::Tarantool => "tarantool".to_smolstr(), + Entity::Target => "target".to_smolstr(), + Entity::Transaction => "transaction".to_smolstr(), + Entity::Tuple => "tuple".to_smolstr(), + Entity::TupleBuilderCommand => "TupleBuilderCommand".to_smolstr(), + Entity::Type => "type".to_smolstr(), + Entity::Update => "Update node".to_smolstr(), + Entity::Value => "value".to_smolstr(), + Entity::VirtualTable => "virtual table".to_smolstr(), + Entity::VTableKey => "virtual table key".to_smolstr(), }; write!(f, "{p}") } @@ -248,26 +248,26 @@ pub enum Action { impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let p = match self { - Action::Add => "add".to_string(), - Action::Borrow => "borrow".to_string(), - Action::Build => "build".to_string(), - Action::Clear => "clear".to_string(), - Action::Create => "create".to_string(), - Action::Delete => "delete".to_string(), - Action::Decode => "decode".to_string(), - Action::Drop => "drop".to_string(), - Action::Find => "find".to_string(), - Action::Deserialize => "deserialize".to_string(), - Action::Get => "get".to_string(), - Action::Insert => "insert".to_string(), - Action::Prepare => "prepare".to_string(), - Action::Put => "put".to_string(), - Action::Replace => "replace".to_string(), - Action::ReplaceOnConflict => "replace on conflict".to_string(), - Action::Retrieve => "retrieve".to_string(), - Action::Serialize => "serialize".to_string(), - Action::Update => "update".to_string(), - Action::Upsert => "upsert".to_string(), + Action::Add => "add".to_smolstr(), + Action::Borrow => "borrow".to_smolstr(), + Action::Build => "build".to_smolstr(), + Action::Clear => "clear".to_smolstr(), + Action::Create => "create".to_smolstr(), + Action::Delete => "delete".to_smolstr(), + Action::Decode => "decode".to_smolstr(), + Action::Drop => "drop".to_smolstr(), + Action::Find => "find".to_smolstr(), + Action::Deserialize => "deserialize".to_smolstr(), + Action::Get => "get".to_smolstr(), + Action::Insert => "insert".to_smolstr(), + Action::Prepare => "prepare".to_smolstr(), + Action::Put => "put".to_smolstr(), + Action::Replace => "replace".to_smolstr(), + Action::ReplaceOnConflict => "replace on conflict".to_smolstr(), + Action::Retrieve => "retrieve".to_smolstr(), + Action::Serialize => "serialize".to_smolstr(), + Action::Update => "update".to_smolstr(), + Action::Upsert => "upsert".to_smolstr(), }; write!(f, "{p}") } @@ -315,24 +315,24 @@ impl fmt::Display for SbroadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let p: SmolStr = match self { SbroadError::DoSkip => DO_SKIP.to_smolstr(), - SbroadError::DuplicatedValue(s) => format!("duplicated value: {s}").to_smolstr(), + SbroadError::DuplicatedValue(s) => format_smolstr!("duplicated value: {s}"), SbroadError::FailedTo(a, e, s) => match e { - Some(entity) => format!("failed to {a} {entity}: {s}").to_smolstr(), - None => format!("failed to {a} {s}").to_smolstr(), + Some(entity) => format_smolstr!("failed to {a} {entity}: {s}"), + None => format_smolstr!("failed to {a} {s}"), }, SbroadError::Invalid(e, s) => match s { - Some(msg) => format!("invalid {e}: {msg}").to_smolstr(), - None => format!("invalid {e}").to_smolstr(), + Some(msg) => format_smolstr!("invalid {e}: {msg}"), + None => format_smolstr!("invalid {e}"), }, - SbroadError::NotFound(e, s) => format!("{e} {s} not found").to_smolstr(), - SbroadError::NotImplemented(e, s) => format!("{e} {s} not implemented").to_smolstr(), - SbroadError::ParsingError(e, s) => format!("{e} parsing error: {s}").to_smolstr(), + SbroadError::NotFound(e, s) => format_smolstr!("{e} {s} not found"), + SbroadError::NotImplemented(e, s) => format_smolstr!("{e} {s} not implemented"), + SbroadError::ParsingError(e, s) => format_smolstr!("{e} parsing error: {s}"), SbroadError::Unsupported(e, s) => match s { - Some(msg) => format!("unsupported {e}: {msg}").to_smolstr(), - None => format!("unsupported {e}").to_smolstr(), + Some(msg) => format_smolstr!("unsupported {e}: {msg}"), + None => format_smolstr!("unsupported {e}"), }, SbroadError::UnexpectedNumberOfValues(s) => { - format!("unexpected number of values: {s}").to_smolstr() + format_smolstr!("unexpected number of values: {s}") } SbroadError::LuaError(e) => e.clone(), SbroadError::UseOfBothParamsStyles => { @@ -342,7 +342,7 @@ impl fmt::Display for SbroadError { "storage schema version different from router".into() } SbroadError::UnsupportedOpForGlobalTables(op) => { - format!("{op} is not supported for global tables").to_smolstr() + format_smolstr!("{op} is not supported for global tables") } }; @@ -357,7 +357,7 @@ impl<E: fmt::Debug> From<TransactionError<E>> for SbroadError { SbroadError::FailedTo( Action::Create, Some(Entity::Transaction), - format!("{error:?}").to_smolstr(), + format_smolstr!("{error:?}"), ) } } @@ -367,7 +367,7 @@ impl From<Error> for SbroadError { SbroadError::FailedTo( Action::Create, Some(Entity::Tarantool), - format!("{error:?}").to_smolstr(), + format_smolstr!("{error:?}"), ) } } diff --git a/sbroad-core/src/executor.rs b/sbroad-core/src/executor.rs index 9f57e5cb2..7be585c09 100644 --- a/sbroad-core/src/executor.rs +++ b/sbroad-core/src/executor.rs @@ -39,6 +39,7 @@ use crate::ir::value::Value; use crate::ir::Plan; use crate::otm::{child_span, query_id}; use sbroad_proc::otm_child_span; +use smol_str::{format_smolstr, SmolStr}; pub mod bucket; pub mod engine; @@ -112,7 +113,7 @@ where /// - Failed to apply optimizing transformations to IR plan. pub fn new(coordinator: &'a C, sql: &str, params: Vec<Value>) -> Result<Self, SbroadError> where - C::Cache: Cache<String, Plan>, + C::Cache: Cache<SmolStr, Plan>, C::ParseTree: Ast, { let key = query_id(sql); @@ -120,7 +121,11 @@ where let mut plan = Plan::new(); let mut cache = ir_cache.try_borrow_mut().map_err(|e| { - SbroadError::FailedTo(Action::Create, Some(Entity::Query), format!("{e:?}").into()) + SbroadError::FailedTo( + Action::Create, + Some(Entity::Query), + format_smolstr!("{e:?}"), + ) })?; if let Some(cached_plan) = cache.get(&key)? { plan = cached_plan.clone(); @@ -258,7 +263,7 @@ where /// /// # Errors /// - Failed to build explain - pub fn to_explain(&self) -> Result<String, SbroadError> { + pub fn to_explain(&self) -> Result<SmolStr, SbroadError> { self.exec_plan.get_ir_plan().as_explain() } diff --git a/sbroad-core/src/executor/bucket.rs b/sbroad-core/src/executor/bucket.rs index cd082db63..6cd90349f 100644 --- a/sbroad-core/src/executor/bucket.rs +++ b/sbroad-core/src/executor/bucket.rs @@ -1,6 +1,6 @@ use itertools::FoldWhile::{Continue, Done}; use itertools::Itertools; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use std::collections::HashSet; use crate::errors::{Action, Entity, SbroadError}; @@ -156,7 +156,7 @@ where *right_columns.get(*position).ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!("at position {position} for right row").into(), + format_smolstr!("at position {position} for right row"), ) })?; let right_column_expr = ir_plan.get_expression_node(right_column_id)?; diff --git a/sbroad-core/src/executor/engine.rs b/sbroad-core/src/executor/engine.rs index 1c6f2b78f..8663c0bce 100644 --- a/sbroad-core/src/executor/engine.rs +++ b/sbroad-core/src/executor/engine.rs @@ -74,7 +74,7 @@ pub trait StorageCache { /// - invalid `schema_info` fn put( &mut self, - plan_id: String, + plan_id: SmolStr, stmt: PreparedStmt, schema_info: &SchemaInfo, ) -> Result<(), SbroadError>; @@ -86,7 +86,7 @@ pub trait StorageCache { /// # Errors /// - failed to get schema version for some table #[allow(clippy::ptr_arg)] - fn get(&mut self, plan_id: &String) -> Result<Option<&PreparedStmt>, SbroadError>; + fn get(&mut self, plan_id: &SmolStr) -> Result<Option<&PreparedStmt>, SbroadError>; /// Clears the cache. /// @@ -153,7 +153,7 @@ pub trait Router: QueryCache { /// # Errors /// - Internal error. Under normal conditions we should always return /// formatted explain successfully. - fn explain_format(&self, explain: String) -> Result<Box<dyn Any>, SbroadError>; + fn explain_format(&self, explain: SmolStr) -> Result<Box<dyn Any>, SbroadError>; /// Extract a list of the sharding key values from a map for the given space. /// @@ -242,7 +242,7 @@ pub trait Statistics { /// - Table statistics couldn't be mutually borrowed. fn update_table_stats( &mut self, - table_name: String, + table_name: SmolStr, table_stats: TableStats, ) -> Result<(), SbroadError>; diff --git a/sbroad-core/src/executor/engine/helpers.rs b/sbroad-core/src/executor/engine/helpers.rs index 29aaad515..6fd2f09e3 100644 --- a/sbroad-core/src/executor/engine/helpers.rs +++ b/sbroad-core/src/executor/engine/helpers.rs @@ -1,7 +1,7 @@ use ahash::AHashMap; use itertools::enumerate; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::{ any::Any, cmp::Ordering, @@ -57,7 +57,7 @@ pub mod vshard; #[must_use] pub fn normalize_name_from_schema(s: &str) -> SmolStr { - format!("\"{s}\"").to_smolstr() + format_smolstr!("\"{s}\"") } /// Transform: @@ -68,7 +68,7 @@ pub fn normalize_name_from_sql(s: &str) -> SmolStr { if let (Some('"'), Some('"')) = (s.chars().next(), s.chars().last()) { return s.to_smolstr(); } - format!("\"{}\"", s.to_uppercase()).to_smolstr() + format_smolstr!("\"{}\"", s.to_uppercase()) } /// Transform: @@ -115,16 +115,15 @@ pub fn encode_plan(mut exec_plan: ExecutionPlan) -> Result<(Binary, Binary), Sbr | Relational::Update { children, .. } => *children.first().ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some( - format!("expected at least one child under DML node {sp_top:?}",) - .into(), - ), + Some(format_smolstr!( + "expected at least one child under DML node {sp_top:?}", + )), ) })?, _ => { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("unsupported DML statement: {sp_top:?}",).into()), + Some(format_smolstr!("unsupported DML statement: {sp_top:?}",)), )); } }; @@ -132,7 +131,9 @@ pub fn encode_plan(mut exec_plan: ExecutionPlan) -> Result<(Binary, Binary), Sbr let Relational::Motion { policy, .. } = motion else { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("expected motion node under dml node, got: {motion:?}",).into()), + Some(format_smolstr!( + "expected motion node under dml node, got: {motion:?}", + )), )); }; let mut sub_plan_id = SmolStr::default(); @@ -154,7 +155,9 @@ pub fn encode_plan(mut exec_plan: ExecutionPlan) -> Result<(Binary, Binary), Sbr // so we mustn't got here. return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("unsupported motion policy under DML node: {policy:?}",).into()), + Some(format_smolstr!( + "unsupported motion policy under DML node: {policy:?}", + )), )); }; (ordered, sub_plan_id) @@ -196,20 +199,22 @@ pub fn decode_msgpack(tuple_buf: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SbroadErro SbroadError::FailedTo( Action::Decode, Some(Entity::MsgPack), - format!("array length: {e:?}").into(), + format_smolstr!("array length: {e:?}"), ) })? as usize; if array_len != 2 { return Err(SbroadError::Invalid( Entity::Tuple, - Some(format!("expected tuple of 2 elements, got {array_len}").into()), + Some(format_smolstr!( + "expected tuple of 2 elements, got {array_len}" + )), )); } let req_len = rmp::decode::read_str_len(&mut stream).map_err(|e| { SbroadError::FailedTo( Action::Decode, Some(Entity::MsgPack), - format!("read required data length: {e:?}").into(), + format_smolstr!("read required data length: {e:?}"), ) })? as usize; let mut required: Vec<u8> = vec![0_u8; req_len]; @@ -217,7 +222,7 @@ pub fn decode_msgpack(tuple_buf: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SbroadErro SbroadError::FailedTo( Action::Decode, Some(Entity::MsgPack), - format!("read required data: {e:?}").into(), + format_smolstr!("read required data: {e:?}"), ) })?; @@ -225,7 +230,7 @@ pub fn decode_msgpack(tuple_buf: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SbroadErro SbroadError::FailedTo( Action::Decode, Some(Entity::MsgPack), - format!("read optional data string length: {e:?}").into(), + format_smolstr!("read optional data string length: {e:?}"), ) })? as usize; let mut optional: Vec<u8> = vec![0_u8; opt_len]; @@ -233,7 +238,7 @@ pub fn decode_msgpack(tuple_buf: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SbroadErro SbroadError::FailedTo( Action::Decode, Some(Entity::MsgPack), - format!("read optional data: {e:?}").into(), + format_smolstr!("read optional data: {e:?}"), ) })?; @@ -325,18 +330,18 @@ fn init_local_update_tuple_builder( .columns .get(*table_pos) .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid position in update table: {table_pos}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid position in update table: {table_pos}" + )) })? .r#type; let vtable_type = &vtable .get_columns() .get(*tuple_pos) .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid position in update vtable: {tuple_pos}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid position in update vtable: {tuple_pos}" + )) })? .r#type; if rel_type == vtable_type { @@ -353,23 +358,20 @@ fn init_local_update_tuple_builder( let table_pos = *rel.primary_key.positions.get(idx).ok_or_else(|| { SbroadError::Invalid( Entity::Update, - Some( - format!( - "invalid primary key positions: len: {}, expected len: {}", - pk_positions.len(), - rel.primary_key.positions.len() - ) - .into(), - ), + Some(format_smolstr!( + "invalid primary key positions: len: {}, expected len: {}", + pk_positions.len(), + rel.primary_key.positions.len() + )), ) })?; let rel_type = &rel .columns .get(table_pos) .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid primary key position in table: {table_pos}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid primary key position in table: {table_pos}" + )) })? .r#type; let vtable_type = &vtable @@ -378,7 +380,7 @@ fn init_local_update_tuple_builder( .ok_or_else(|| { SbroadError::Invalid( Entity::Update, - Some(format!("invalid pk position: {pk_pos}").into()), + Some(format_smolstr!("invalid pk position: {pk_pos}")), ) })? .r#type; @@ -395,7 +397,7 @@ fn init_local_update_tuple_builder( } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected Update on id ({update_id})").into()), + Some(format_smolstr!("expected Update on id ({update_id})")), )) } @@ -443,9 +445,9 @@ fn init_insert_tuple_builder( .get_columns() .get(tuple_pos) .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid index in virtual table: {tuple_pos}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid index in virtual table: {tuple_pos}" + )) })? .r#type; let rel_type = &table_col.r#type; @@ -480,7 +482,9 @@ fn init_sharded_update_tuple_builder( else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("update tuple builder: expected update node on id: {update_id}").into()), + Some(format_smolstr!( + "update tuple builder: expected update node on id: {update_id}" + )), )); }; let relation = plan.dml_node_table(update_id)?; @@ -498,9 +502,9 @@ fn init_sharded_update_tuple_builder( .get_columns() .get(tuple_pos) .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid index in virtual table: {tuple_pos}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid index in virtual table: {tuple_pos}" + )) })? .r#type; let rel_type = &table_col.r#type; @@ -520,7 +524,9 @@ fn init_sharded_update_tuple_builder( return Err(SbroadError::Invalid( Entity::Update, - Some(format!("user column {pos} not found in update column map").into()), + Some(format_smolstr!( + "user column {pos} not found in update column map" + )), )); } } @@ -543,7 +549,7 @@ pub fn empty_query_result(plan: &ExecutionPlan) -> Result<Option<Box<dyn Any>>, QueryType::DML => { let result = ConsumerResult::default(); let tuple = Tuple::new(&(result,)) - .map_err(|e| SbroadError::Invalid(Entity::Tuple, Some(format!("{e:?}").into())))?; + .map_err(|e| SbroadError::Invalid(Entity::Tuple, Some(format_smolstr!("{e:?}"))))?; Ok(Some(Box::new(tuple) as Box<dyn Any>)) } QueryType::DQL => { @@ -567,7 +573,7 @@ pub fn empty_query_result(plan: &ExecutionPlan) -> Result<Option<Box<dyn Any>>, } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("expected alias, got {column:?}").into()), + Some(format_smolstr!("expected alias, got {column:?}")), )); }; metadata.push(MetadataColumn::new( @@ -581,7 +587,7 @@ pub fn empty_query_result(plan: &ExecutionPlan) -> Result<Option<Box<dyn Any>>, }; let tuple = Tuple::new(&(result,)) - .map_err(|e| SbroadError::Invalid(Entity::Tuple, Some(format!("{e:?}").into())))?; + .map_err(|e| SbroadError::Invalid(Entity::Tuple, Some(format_smolstr!("{e:?}"))))?; Ok(Some(Box::new(tuple) as Box<dyn Any>)) } } @@ -599,7 +605,7 @@ pub fn explain_format(explain: &str) -> Result<Box<dyn Any>, SbroadError> { Err(e) => Err(SbroadError::FailedTo( Action::Create, Some(Entity::Tuple), - format!("{e}").into(), + format_smolstr!("{e}"), )), } } @@ -655,7 +661,7 @@ pub fn dispatch_by_buckets( if !vtable.get_bucket_index().is_empty() { return Err(SbroadError::Invalid( Entity::Motion, - Some(format!("motion ({motion_id}) in subtree with distribution Single, but policy is not Full!").into()), + Some(format_smolstr!("motion ({motion_id}) in subtree with distribution Single, but policy is not Full!")), )); } } @@ -721,7 +727,7 @@ pub(crate) fn materialize_values( let Relational::ValuesRow { data, .. } = row_node else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("Expected ValuesRow, got {row_node:?}").into()), + Some(format_smolstr!("Expected ValuesRow, got {row_node:?}")), )); }; plan.get_ir_plan() @@ -731,7 +737,9 @@ pub(crate) fn materialize_values( } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("Values node {child_node:?} must contain children").into()), + Some(format_smolstr!( + "Values node {child_node:?} must contain children" + )), )); }; let mut nullable_column_indices = HashSet::with_capacity(columns_len); @@ -760,7 +768,7 @@ pub(crate) fn materialize_values( .ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!("at position {idx} in the row").into(), + format_smolstr!("at position {idx} in the row"), ) })?; let column_node_ref = plan.get_mut_ir_plan().get_mut_node(column_id)?; @@ -773,9 +781,9 @@ pub(crate) fn materialize_values( } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!( + Some(format_smolstr!( "VALUES rows supports only constants in its columns (got: {column_node:?})." - ).into()), + )), )); } } @@ -783,7 +791,9 @@ pub(crate) fn materialize_values( } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("value node child ({child_id}) is not a values row node!").into()), + Some(format_smolstr!( + "value node child ({child_id}) is not a values row node!" + )), )); } } @@ -808,7 +818,9 @@ pub(crate) fn materialize_values( } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("output column ({column_id}) is not an alias node!").into()), + Some(format_smolstr!( + "output column ({column_id}) is not an alias node!" + )), )); } } @@ -843,7 +855,7 @@ pub fn materialize_motion( SbroadError::FailedTo( Action::Decode, Some(Entity::Tuple), - format!("motion node {motion_node_id}. {e}").into(), + format_smolstr!("motion node {motion_node_id}. {e}"), ) })?; data.get_mut(0) @@ -904,7 +916,7 @@ pub fn sharding_key_from_tuple<'tuple>( let value = tuple.get(*position).ok_or_else(|| { SbroadError::NotFound( Entity::ShardingKey, - format!("position {position:?} in the tuple {tuple:?}").into(), + format_smolstr!("position {position:?} in the tuple {tuple:?}"), ) })?; sharding_tuple.push(value); @@ -931,9 +943,9 @@ pub fn sharding_key_from_tuple<'tuple>( Ordering::Equal => { return Err(SbroadError::Invalid( Entity::Tuple, - Some(format!( + Some(format_smolstr!( r#"the tuple {tuple:?} contains a "bucket_id" position {position} in a sharding key {sharding_positions:?}"# - ).into()), + )), )); } Ordering::Greater => *position - 1, @@ -941,7 +953,7 @@ pub fn sharding_key_from_tuple<'tuple>( let value = tuple.get(corrected_pos).ok_or_else(|| { SbroadError::NotFound( Entity::ShardingKey, - format!("position {corrected_pos:?} in the tuple {tuple:?}").into(), + format_smolstr!("position {corrected_pos:?} in the tuple {tuple:?}"), ) })?; sharding_tuple.push(value); @@ -950,15 +962,12 @@ pub fn sharding_key_from_tuple<'tuple>( } else { Err(SbroadError::Invalid( Entity::Tuple, - Some( - format!( - "the tuple {:?} was expected to have {} filed(s), got {}.", - tuple, - table_col_amount - 1, - tuple.len() - ) - .into(), - ), + Some(format_smolstr!( + "the tuple {:?} was expected to have {} filed(s), got {}.", + tuple, + table_col_amount - 1, + tuple.len() + )), )) } } @@ -987,9 +996,9 @@ where .cache() .try_borrow_mut() .map_err(|e| { - SbroadError::FailedTo(Action::Borrow, Some(Entity::Cache), format!("{e}").into()) + SbroadError::FailedTo(Action::Borrow, Some(Entity::Cache), format_smolstr!("{e}")) })? - .get(&plan_id.to_string())? + .get(plan_id)? { let stmt_id = stmt.id()?; // The statement was found in the cache, so we can execute it. @@ -1075,10 +1084,10 @@ where SbroadError::FailedTo( Action::Put, None, - format!("prepared statement {stmt:?} into the cache: {e:?}").into(), + format_smolstr!("prepared statement {stmt:?} into the cache: {e:?}"), ) })? - .put(plan_id.to_string(), stmt, schema_info)?; + .put(plan_id.clone(), stmt, schema_info)?; // The statement was found in the cache, so we can execute it. debug!( Option::from("execute plan"), @@ -1185,7 +1194,9 @@ where Relational::Update { .. } => execute_update_on_storage(runtime, &mut optional, required), _ => Err(SbroadError::Invalid( Entity::Plan, - Some(format!("expected DML node on the plan top, got {top:?}").into()), + Some(format_smolstr!( + "expected DML node on the plan top, got {top:?}" + )), )), } } @@ -1214,14 +1225,14 @@ where SbroadError::FailedTo( Action::Deserialize, Some(Entity::Tuple), - format!("motion node {child_id}. {e:?}").into(), + format_smolstr!("motion node {child_id}. {e:?}"), ) })?; let mut data = tuple.decode::<Vec<ProducerResult>>().map_err(|e| { SbroadError::FailedTo( Action::Decode, Some(Entity::Tuple), - format!("motion node {child_id}. {e}").into(), + format_smolstr!("motion node {child_id}. {e}"), ) })?; let vtable = data @@ -1269,7 +1280,7 @@ where let space = Space::find(&space_name).ok_or_else(|| { SbroadError::Invalid( Entity::Space, - Some(format!("space {space_name} not found").into()), + Some(format_smolstr!("space {space_name} not found")), ) })?; transaction(|| -> Result<(), SbroadError> { @@ -1307,7 +1318,7 @@ fn execute_sharded_update( return Err(SbroadError::FailedTo( Action::Delete, Some(Entity::Tuple), - format!("{tnt_err:?}").into(), + format_smolstr!("{tnt_err:?}"), )); } } @@ -1317,7 +1328,7 @@ fn execute_sharded_update( let vt_tuple = vtable.get_tuples().get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::VirtualTable, - Some(format!("invalid tuple position in index: {pos}").into()), + Some(format_smolstr!("invalid tuple position in index: {pos}")), ) })?; @@ -1329,12 +1340,9 @@ fn execute_sharded_update( let value = vt_tuple.get(*tuple_pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!( - "column at position {pos} not found in virtual table" - ) - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; insert_tuple.push(EncodedValue::Ref(value.into())); @@ -1343,12 +1351,9 @@ fn execute_sharded_update( let value = vt_tuple.get(*tuple_pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!( - "column at position {pos} not found in virtual table" - ) - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; insert_tuple.push(value.cast(table_type)?); @@ -1359,7 +1364,7 @@ fn execute_sharded_update( _ => { return Err(SbroadError::Invalid( Entity::TupleBuilderCommand, - Some(format!("got command {command:?} for update insert").into()), + Some(format_smolstr!("got command {command:?} for update insert")), )); } } @@ -1370,7 +1375,7 @@ fn execute_sharded_update( return Err(SbroadError::FailedTo( Action::Insert, Some(Entity::Tuple), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), )); } result.row_count += 1; @@ -1399,10 +1404,9 @@ fn execute_local_update( let value = vt_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!("column at position {pos} not found in virtual table") - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; let op = [ @@ -1416,10 +1420,9 @@ fn execute_local_update( let value = vt_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!("column at position {pos} not found in virtual table") - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; key_tuple.push(EncodedValue::Ref(MsgPackValue::from(value))); @@ -1428,10 +1431,9 @@ fn execute_local_update( let value = vt_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!("column at position {pos} not found in virtual table") - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; key_tuple.push(value.cast(table_type)?); @@ -1440,10 +1442,9 @@ fn execute_local_update( let value = vt_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!("column at position {pos} not found in virtual table") - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; let op = [ @@ -1456,14 +1457,14 @@ fn execute_local_update( _ => { return Err(SbroadError::Invalid( Entity::TupleBuilderCommand, - Some(format!("got command {command:?} for update").into()), + Some(format_smolstr!("got command {command:?} for update")), )); } } } let update_res = space.update(&key_tuple, &update_tuple); update_res.map_err(|e| { - SbroadError::FailedTo(Action::Update, Some(Entity::Space), format!("{e}").into()) + SbroadError::FailedTo(Action::Update, Some(Entity::Space), format_smolstr!("{e}")) })?; result.row_count += 1; } @@ -1496,7 +1497,7 @@ where let space = Space::find(&space_name).ok_or_else(|| { SbroadError::Invalid( Entity::Space, - Some(format!("space {space_name} not found").into()), + Some(format_smolstr!("space {space_name} not found")), ) })?; transaction(|| -> Result<(), SbroadError> { @@ -1507,22 +1508,18 @@ where let value = vt_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!( + Some(format_smolstr!( "column at position {pos} not found in the delete virtual table" - ) - .into(), - ), + )), ) })?; delete_tuple.push(EncodedValue::Ref(value.into())); } else { return Err(SbroadError::Invalid( Entity::Tuple, - Some( - format!("unexpected tuple builder cmd for delete primary key: {cmd:?}") - .into(), - ), + Some(format_smolstr!( + "unexpected tuple builder cmd for delete primary key: {cmd:?}" + )), )); } } @@ -1530,7 +1527,7 @@ where return Err(SbroadError::FailedTo( Action::Delete, Some(Entity::Tuple), - format!("{tnt_err:?}").into(), + format_smolstr!("{tnt_err:?}"), )); } result.row_count += 1; @@ -1580,7 +1577,7 @@ where let space = Space::find(&space_name).ok_or_else(|| { SbroadError::Invalid( Entity::Space, - Some(format!("space {space_name} not found").into()), + Some(format_smolstr!("space {space_name} not found")), ) })?; let plan = optional.exec_plan.get_ir_plan(); @@ -1596,7 +1593,9 @@ where let vt_tuple = vtable.get_tuples().get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::VirtualTable, - Some(format!("tuple at position {pos} not found in virtual table").into()), + Some(format_smolstr!( + "tuple at position {pos} not found in virtual table" + )), ) })?; let mut insert_tuple = Vec::with_capacity(builder.len()); @@ -1609,12 +1608,9 @@ where let value = vt_tuple.get(*tuple_pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!( - "column at position {pos} not found in virtual table" - ) - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; insert_tuple.push(EncodedValue::Ref(value.into())); @@ -1623,12 +1619,9 @@ where let value = vt_tuple.get(*tuple_pos).ok_or_else(|| { SbroadError::Invalid( Entity::Tuple, - Some( - format!( - "column at position {pos} not found in virtual table" - ) - .into(), - ), + Some(format_smolstr!( + "column at position {pos} not found in virtual table" + )), ) })?; insert_tuple.push(value.cast(table_type)?); @@ -1642,12 +1635,9 @@ where _ => { return Err(SbroadError::Invalid( Entity::Tuple, - Some( - format!( - "unexpected tuple builder command for insert: {command:?}" - ) - .into(), - ), + Some(format_smolstr!( + "unexpected tuple builder command for insert: {command:?}" + )), )); } } @@ -1681,7 +1671,7 @@ where SbroadError::FailedTo( Action::ReplaceOnConflict, Some(Entity::Space), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; result.row_count += 1; @@ -1690,7 +1680,7 @@ where return Err(SbroadError::FailedTo( Action::Insert, Some(Entity::Space), - format!("{tnt_err}").into(), + format_smolstr!("{tnt_err}"), )); } } @@ -1705,7 +1695,7 @@ where SbroadError::FailedTo( Action::Insert, Some(Entity::Space), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; result.row_count += 1; @@ -1739,7 +1729,7 @@ where let result = execute_dml_on_storage(runtime, raw_optional, required)?; let tuple = Tuple::new(&(result,)) - .map_err(|e| SbroadError::Invalid(Entity::Tuple, Some(format!("{e:?}").into())))?; + .map_err(|e| SbroadError::Invalid(Entity::Tuple, Some(format_smolstr!("{e:?}"))))?; Ok(Box::new(tuple) as Box<dyn Any>) } @@ -1844,16 +1834,16 @@ pub fn sharding_key_from_map<'rec, S: ::std::hash::BuildHasher>( let value = map.get(*column).ok_or_else(|| { SbroadError::NotFound( Entity::ShardingKey, - format!("column {column:?} in the map {map:?}").into(), + format_smolstr!("column {column:?} in the map {map:?}"), ) })?; tuple.push(value); } else { return Err(SbroadError::NotFound( Entity::ShardingKey, - format!( + format_smolstr!( "(quoted) column {quoted_column:?} in the quoted map {quoted_map:?} (original map: {map:?})" - ).into())); + ))); } } Ok(tuple) diff --git a/sbroad-core/src/executor/engine/helpers/storage/runtime.rs b/sbroad-core/src/executor/engine/helpers/storage/runtime.rs index e03cac7d6..b0cdb648f 100644 --- a/sbroad-core/src/executor/engine/helpers/storage/runtime.rs +++ b/sbroad-core/src/executor/engine/helpers/storage/runtime.rs @@ -1,7 +1,7 @@ use std::any::Any; use sbroad_proc::otm_child_span; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use tarantool::{tlua::LuaFunction, tuple::Tuple}; use crate::ir::ExecuteOptions; @@ -27,7 +27,7 @@ pub fn prepare(pattern: &str) -> Result<PreparedStmt, SbroadError> { } Err(e) => { error!(Option::from("prepare"), &format!("{e:?}")); - Err(SbroadError::LuaError(format!("{e:?}").into())) + Err(SbroadError::LuaError(format_smolstr!("{e:?}"))) } } } @@ -44,7 +44,7 @@ pub fn unprepare(stmt: &mut PreparedStmt) -> Result<(), SbroadError> { Ok(()) => Ok(()), Err(e) => { error!(Option::from("unprepare"), &format!("{e:?}")); - Err(SbroadError::LuaError(format!("{e:?}").into())) + Err(SbroadError::LuaError(format_smolstr!("{e:?}"))) } } } @@ -67,7 +67,7 @@ pub fn read_prepared( Ok(v) => Ok(Box::new(v) as Box<dyn Any>), Err(e) => { error!(Option::from("read_prepared"), &format!("{e:?}")); - Err(SbroadError::LuaError(format!("{e:?}").into())) + Err(SbroadError::LuaError(format_smolstr!("{e:?}"))) } } } @@ -93,7 +93,7 @@ pub fn read_unprepared( Ok(v) => Ok(Box::new(v) as Box<dyn Any>), Err(e) => { error!(Option::from("read_unprepared"), &format!("{e:?}")); - Err(SbroadError::LuaError(format!("{e:?}").into())) + Err(SbroadError::LuaError(format_smolstr!("{e:?}"))) } } } @@ -115,7 +115,7 @@ pub fn write_prepared( Ok(v) => Ok(Box::new(v) as Box<dyn Any>), Err(e) => { error!(Option::from("write_prepared"), &format!("{e:?}")); - Err(SbroadError::LuaError(format!("{e:?}").into())) + Err(SbroadError::LuaError(format_smolstr!("{e:?}"))) } } } @@ -136,7 +136,7 @@ pub fn write_unprepared( Ok(v) => Ok(Box::new(v) as Box<dyn Any>), Err(e) => { error!(Option::from("write_unprepared"), &format!("{e:?}")); - Err(SbroadError::LuaError(format!("{e:?}").into())) + Err(SbroadError::LuaError(format_smolstr!("{e:?}"))) } } } diff --git a/sbroad-core/src/executor/engine/helpers/vshard.rs b/sbroad-core/src/executor/engine/helpers/vshard.rs index 1c0275415..30b6b7ee8 100644 --- a/sbroad-core/src/executor/engine/helpers/vshard.rs +++ b/sbroad-core/src/executor/engine/helpers/vshard.rs @@ -19,6 +19,7 @@ use crate::{ }; use rand::{thread_rng, Rng}; use sbroad_proc::otm_child_span; +use smol_str::format_smolstr; use tarantool::{tlua::LuaFunction, tuple::Tuple}; use crate::{ @@ -67,9 +68,9 @@ fn dql_on_some( } Err(e) => { error!(Option::from("dql_on_some"), &format!("{e:?}")); - Err(SbroadError::LuaError( - format!("Lua error (IR dispatch): {e:?}").into(), - )) + Err(SbroadError::LuaError(format_smolstr!( + "Lua error (IR dispatch): {e:?}" + ))) } } } @@ -94,9 +95,9 @@ fn dml_on_some( Ok(v) => Ok(Box::new(v)), Err(e) => { error!(Option::from("dml_on_some"), &format!("{e:?}")); - Err(SbroadError::LuaError( - format!("Lua error (IR dispatch): {e:?}").into(), - )) + Err(SbroadError::LuaError(format_smolstr!( + "Lua error (IR dispatch): {e:?}" + ))) } } } @@ -128,9 +129,9 @@ fn dql_on_all( } Err(e) => { error!(Option::from("dql_on_all"), &format!("{e:?}")); - Err(SbroadError::LuaError( - format!("Lua error (dispatch IR): {e:?}").into(), - )) + Err(SbroadError::LuaError(format_smolstr!( + "Lua error (dispatch IR): {e:?}" + ))) } } } @@ -155,9 +156,9 @@ fn dml_on_all( Ok(v) => Ok(Box::new(v)), Err(e) => { error!(Option::from("dml_on_all"), &format!("{e:?}")); - Err(SbroadError::LuaError( - format!("Lua error (dispatch IR): {e:?}").into(), - )) + Err(SbroadError::LuaError(format_smolstr!( + "Lua error (dispatch IR): {e:?}" + ))) } } } @@ -193,7 +194,9 @@ pub fn exec_ir_on_some_buckets( let Buckets::Filtered(bucket_set) = buckets else { return Err(SbroadError::Invalid( Entity::Buckets, - Some(format!("Expected Buckets::Filtered, got {buckets:?}").into()), + Some(format_smolstr!( + "Expected Buckets::Filtered, got {buckets:?}" + )), )); }; let mut buckets = buckets; @@ -211,12 +214,9 @@ pub fn exec_ir_on_some_buckets( // this way we could implement it for mock runtime for better testing let rs_bucket_vec: Vec<(String, Vec<u64>)> = group(buckets)?.drain().collect(); if rs_bucket_vec.is_empty() { - return Err(SbroadError::UnexpectedNumberOfValues( - format!( - "no replica sets were found for the buckets {buckets:?} to execute the query on" - ) - .into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "no replica sets were found for the buckets {buckets:?} to execute the query on" + ))); } let rs_ir = prepare_rs_to_ir_map(&rs_bucket_vec, sub_plan)?; let mut rs_message = HashMap::with_capacity(rs_ir.len()); @@ -395,7 +395,7 @@ fn disable_serialize_as_empty_opcode( } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected motion node on id {motion_id}").into()), + Some(format_smolstr!("expected motion node on id {motion_id}")), )); }; for op in &mut program.0 { @@ -439,7 +439,7 @@ fn group(buckets: &Buckets) -> Result<GroupedBuckets, SbroadError> { Ok(v) => v, Err(e) => { error!(Option::from("buckets group"), &format!("{e:?}")); - return Err(SbroadError::LuaError(format!("{e:?}").into())); + return Err(SbroadError::LuaError(format_smolstr!("{e:?}"))); } }; diff --git a/sbroad-core/src/executor/engine/mock.rs b/sbroad-core/src/executor/engine/mock.rs index c8bdacc51..bb5708bb0 100644 --- a/sbroad-core/src/executor/engine/mock.rs +++ b/sbroad-core/src/executor/engine/mock.rs @@ -1,4 +1,4 @@ -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::any::Any; use std::cell::{Ref, RefCell}; use std::cmp::Ordering; @@ -989,8 +989,8 @@ impl VshardMock { pub struct RouterRuntimeMock { metadata: RefCell<RouterConfigurationMock>, virtual_tables: RefCell<HashMap<usize, VirtualTable>>, - ir_cache: RefCell<LRUCache<String, Plan>>, - table_statistics_cache: RefCell<HashMap<String, Rc<TableStats>>>, + ir_cache: RefCell<LRUCache<SmolStr, Plan>>, + table_statistics_cache: RefCell<HashMap<SmolStr, Rc<TableStats>>>, initial_column_statistics_cache: RefCell<HashMap<TableColumnPair, Rc<Box<dyn Any>>>>, pub vshard_mock: VshardMock, } @@ -1030,7 +1030,7 @@ impl ProducerResult { } impl QueryCache for RouterRuntimeMock { - type Cache = LRUCache<String, Plan>; + type Cache = LRUCache<SmolStr, Plan>; fn clear_cache(&self) -> Result<(), SbroadError> { *self.ir_cache.borrow_mut() = LRUCache::new(self.cache_capacity()?, None)?; @@ -1046,7 +1046,11 @@ impl QueryCache for RouterRuntimeMock { .cache() .try_borrow() .map_err(|e| { - SbroadError::FailedTo(Action::Borrow, Some(Entity::Cache), format!("{e:?}").into()) + SbroadError::FailedTo( + Action::Borrow, + Some(Entity::Cache), + format_smolstr!("{e:?}"), + ) })? .capacity()) } @@ -1176,22 +1180,22 @@ impl RouterRuntimeMock { #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] #[must_use] pub fn new() -> Self { - let cache: LRUCache<String, Plan> = LRUCache::new(DEFAULT_CAPACITY, None).unwrap(); + let cache: LRUCache<SmolStr, Plan> = LRUCache::new(DEFAULT_CAPACITY, None).unwrap(); let mut table_statistics_cache = HashMap::new(); let hash_testing_hist_rows_number = 1000.0; table_statistics_cache.insert( - "\"hash_testing_hist\"".to_string(), + "\"hash_testing_hist\"".to_smolstr(), Rc::new(TableStats::new(hash_testing_hist_rows_number as u64)), ); let hash_testing_rows_number = 10000.0; table_statistics_cache.insert( - "\"hash_testing\"".to_string(), + "\"hash_testing\"".to_smolstr(), Rc::new(TableStats::new(hash_testing_rows_number as u64)), ); let test_space_rows_number = 25000.0; table_statistics_cache.insert( - "\"test_space\"".to_string(), + "\"test_space\"".to_smolstr(), Rc::new(TableStats::new(test_space_rows_number as u64)), ); @@ -1498,7 +1502,7 @@ impl Router for RouterRuntimeMock { SbroadError::FailedTo( Action::Borrow, Some(Entity::Metadata), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) }) } @@ -1514,7 +1518,7 @@ impl Router for RouterRuntimeMock { } else { Err(SbroadError::NotFound( Entity::VirtualTable, - format!("for motion node {motion_node_id}").into(), + format_smolstr!("for motion node {motion_node_id}"), )) } } @@ -1554,7 +1558,7 @@ impl Router for RouterRuntimeMock { Ok(Box::new(result)) } - fn explain_format(&self, explain: String) -> Result<Box<dyn Any>, SbroadError> { + fn explain_format(&self, explain: SmolStr) -> Result<Box<dyn Any>, SbroadError> { Ok(Box::new(explain)) } @@ -1611,7 +1615,7 @@ impl Statistics for RouterRuntimeMock { fn update_table_stats( &mut self, - table_name: String, + table_name: SmolStr, table_stats: TableStats, ) -> Result<(), SbroadError> { if let Ok(mut borrow_res) = self.table_statistics_cache.try_borrow_mut() { diff --git a/sbroad-core/src/executor/ir.rs b/sbroad-core/src/executor/ir.rs index 732ae82d6..452eb0a14 100644 --- a/sbroad-core/src/executor/ir.rs +++ b/sbroad-core/src/executor/ir.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use ahash::AHashMap; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use crate::errors::{Action, Entity, SbroadError}; use crate::executor::engine::Vshard; @@ -108,7 +108,7 @@ impl ExecutionPlan { Err(SbroadError::NotFound( Entity::VirtualTable, - format!("for Motion node ({motion_id})").into(), + format_smolstr!("for Motion node ({motion_id})"), )) } @@ -177,9 +177,9 @@ impl ExecutionPlan { )); }; let Some(from_vtable) = vtables.mut_map().remove(&motion_id) else { - return Err(SbroadError::UnexpectedNumberOfValues( - format!("expected virtual table for motion {motion_id}").into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "expected virtual table for motion {motion_id}" + ))); }; let from_vtable = Rc::try_unwrap(from_vtable).map_err(|_| { SbroadError::FailedTo( @@ -310,26 +310,23 @@ impl ExecutionPlan { if !node.is_motion() { return Err(SbroadError::Invalid( Entity::Relational, - Some(format!("current node ({node_id}) is not motion").into()), + Some(format_smolstr!("current node ({node_id}) is not motion")), )); } let children = self.plan.get_relational_children(node_id)?.ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("that is Motion {node_id} child(ren)").into(), + format_smolstr!("that is Motion {node_id} child(ren)"), ) })?; if children.len() != 1 { - return Err(SbroadError::UnexpectedNumberOfValues( - format!( - "Motion node ({}) must have a single child only (actual {})", - node_id, - children.len() - ) - .into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Motion node ({}) must have a single child only (actual {})", + node_id, + children.len() + ))); } let child_id = children.first().ok_or_else(|| { @@ -349,26 +346,23 @@ impl ExecutionPlan { if !node.is_subquery() { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("current node ({node_id}) is not sub query").to_smolstr()), + Some(format_smolstr!("current node ({node_id}) is not sub query")), )); } let children = self.plan.get_relational_children(node_id)?.ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("that is Subquery {node_id} child(ren)").into(), + format_smolstr!("that is Subquery {node_id} child(ren)"), ) })?; if children.len() != 1 { - return Err(SbroadError::UnexpectedNumberOfValues( - format!( - "Sub query node ({}) must have a single child only (actual {})", - node_id, - children.len() - ) - .into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Sub query node ({}) must have a single child only (actual {})", + node_id, + children.len() + ))); } let child_id = children.first().ok_or_else(|| { @@ -395,7 +389,7 @@ impl ExecutionPlan { } else { return Err(SbroadError::Invalid( Entity::Relational, - Some(format!("node ({motion_id}) is not motion").into()), + Some(format_smolstr!("node ({motion_id}) is not motion")), )); } Ok(()) @@ -442,7 +436,7 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!("could not find data node id {data} in the map").into(), + format_smolstr!("could not find data node id {data} in the map"), ) })?; } @@ -469,8 +463,9 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!("could not find child node id {child_id} in the map") - .into(), + format_smolstr!( + "could not find child node id {child_id} in the map" + ), ) })?; } @@ -482,7 +477,7 @@ impl ExecutionPlan { let new_col_id = *translation.get(col_id).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("grouping column {col_id} in translation map").into(), + format_smolstr!("grouping column {col_id} in translation map"), ) })?; new_plan.replace_parent_in_subtree(new_col_id, None, Some(next_id))?; @@ -495,7 +490,7 @@ impl ExecutionPlan { *rel.mut_output() = *translation.get(&output).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("as output node {output} in relational node {rel:?}").into(), + format_smolstr!("as output node {output} in relational node {rel:?}"), ) })?; new_plan.replace_parent_in_subtree(rel.output(), None, Some(next_id))?; @@ -524,9 +519,9 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!( + format_smolstr!( "could not find filter/condition node id {undo_expr_id} in the map" - ).into(), + ), ) })?; new_plan.replace_parent_in_subtree(*expr_id, None, Some(next_id))?; @@ -544,10 +539,9 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!( + format_smolstr!( "could not find relation {relation} in the original plan" - ) - .into(), + ), ) })? .clone(); @@ -563,7 +557,7 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!("could not find child node id {child} in the map").into(), + format_smolstr!("could not find child node id {child} in the map"), ) })?; } @@ -586,16 +580,18 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!("could not find left child node id {left} in the map") - .into(), + format_smolstr!( + "could not find left child node id {left} in the map" + ), ) })?; *right = *translation.get(right).ok_or_else(|| { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!("could not find right child node id {right} in the map") - .into(), + format_smolstr!( + "could not find right child node id {right} in the map" + ), ) })?; } @@ -615,8 +611,9 @@ impl ExecutionPlan { SbroadError::FailedTo( Action::Build, Some(Entity::SubTree), - format!("could not find child node id {child} in the map") - .into(), + format_smolstr!( + "could not find child node id {child} in the map" + ), ) })?; } @@ -698,11 +695,10 @@ impl ExecutionPlan { return Err(SbroadError::FailedTo( Action::Build, Some(Entity::Plan), - format!( + format_smolstr!( "cannot build execution plan for DML query with multiple engines: {:?}", self.get_ir_plan().relations.tables - ) - .into(), + ), )); } } diff --git a/sbroad-core/src/executor/lru.rs b/sbroad-core/src/executor/lru.rs index f81dc86d7..ac9d53923 100644 --- a/sbroad-core/src/executor/lru.rs +++ b/sbroad-core/src/executor/lru.rs @@ -1,4 +1,4 @@ -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use crate::error; use crate::errors::{Action, Entity, SbroadError}; @@ -104,7 +104,7 @@ where fn get_node(&self, key: &Option<Key>) -> Result<&LRUNode<Key, Value>, SbroadError> { self.map.get(key).ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("(LRU) with key {key:?}").into()) + SbroadError::NotFound(Entity::Node, format_smolstr!("(LRU) with key {key:?}")) }) } @@ -112,7 +112,7 @@ where self.map.get_mut(key).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(mutable LRU) with key {key:?}").into(), + format_smolstr!("(mutable LRU) with key {key:?}"), ) }) } @@ -184,7 +184,7 @@ where let head_prev = map.get_mut(&head_prev_id).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(mutable LRU) with key {:?}", &head_prev_id).into(), + format_smolstr!("(mutable LRU) with key {:?}", &head_prev_id), ) })?; evict_fn(&mut head_prev.value)?; @@ -274,7 +274,7 @@ where Err(SbroadError::FailedTo( Action::Retrieve, Some(Entity::Value), - format!("from the LRU cache for a key {key:?}").into(), + format_smolstr!("from the LRU cache for a key {key:?}"), )) } } diff --git a/sbroad-core/src/executor/lru/tests.rs b/sbroad-core/src/executor/lru/tests.rs index 44c97a907..18435172d 100644 --- a/sbroad-core/src/executor/lru/tests.rs +++ b/sbroad-core/src/executor/lru/tests.rs @@ -2,7 +2,7 @@ use super::{Cache, LRUCache}; use crate::errors::SbroadError; use crate::ir::Plan; use pretty_assertions::assert_eq; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; #[test] fn lru1() { @@ -27,9 +27,9 @@ fn lru3() { let evict_fn = Box::new(|value: &mut String| { let value_old = value.clone(); value.push_str("_old"); - Err(SbroadError::UnexpectedNumberOfValues( - format!("changed {value_old} to {value} during cache eviction").into(), - )) + Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "changed {value_old} to {value} during cache eviction" + ))) }); let mut cache: LRUCache<usize, String> = LRUCache::new(1, Some(evict_fn)).unwrap(); cache.put(1, "one".to_string()).unwrap(); diff --git a/sbroad-core/src/executor/protocol.rs b/sbroad-core/src/executor/protocol.rs index 91431e8b0..de3aae95e 100644 --- a/sbroad-core/src/executor/protocol.rs +++ b/sbroad-core/src/executor/protocol.rs @@ -1,6 +1,6 @@ use opentelemetry::Context; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::collections::HashMap; use tarantool::tlua::{self, AsLua, PushGuard, PushInto, PushOneInto, Void}; @@ -123,7 +123,7 @@ impl TryFrom<RequiredData> for Vec<u8> { SbroadError::FailedTo( Action::Serialize, Some(Entity::RequiredData), - format!("to binary: {e:?}").into(), + format_smolstr!("to binary: {e:?}"), ) }) } @@ -137,7 +137,7 @@ impl TryFrom<&[u8]> for RequiredData { SbroadError::FailedTo( Action::Deserialize, Some(Entity::RequiredData), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) }) } @@ -223,7 +223,7 @@ impl TryFrom<OptionalData> for Vec<u8> { SbroadError::FailedTo( Action::Serialize, Some(Entity::RequiredData), - format!("to binary: {e:?}").into(), + format_smolstr!("to binary: {e:?}"), ) }) } @@ -237,7 +237,7 @@ impl TryFrom<&[u8]> for OptionalData { SbroadError::FailedTo( Action::Deserialize, Some(Entity::RequiredData), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) }) } @@ -258,7 +258,7 @@ impl OptionalData { SbroadError::FailedTo( Action::Serialize, Some(Entity::RequiredData), - format!("to binary: {e:?}").into(), + format_smolstr!("to binary: {e:?}"), ) }) } @@ -272,7 +272,7 @@ impl OptionalData { SbroadError::FailedTo( Action::Deserialize, Some(Entity::OptionalData), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) }) } diff --git a/sbroad-core/src/executor/result.rs b/sbroad-core/src/executor/result.rs index 1c9918751..b2c02b6f8 100644 --- a/sbroad-core/src/executor/result.rs +++ b/sbroad-core/src/executor/result.rs @@ -12,7 +12,7 @@ use core::fmt::Debug; use serde::ser::{Serialize, SerializeMap, Serializer}; use serde::Deserialize; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use tarantool::tlua::{self, LuaRead}; use tarantool::tuple::Encode; @@ -108,7 +108,7 @@ impl TryInto<Column> for &MetadataColumn { )), _ => Err(SbroadError::Unsupported( Entity::Type, - Some(format!("column type {}", self.r#type).into()), + Some(format_smolstr!("column type {}", self.r#type)), )), } } diff --git a/sbroad-core/src/executor/tests/frontend.rs b/sbroad-core/src/executor/tests/frontend.rs index ffca9d9be..92f7a828e 100644 --- a/sbroad-core/src/executor/tests/frontend.rs +++ b/sbroad-core/src/executor/tests/frontend.rs @@ -69,7 +69,7 @@ fn front_explain_select_sql1() { let metadata = &RouterRuntimeMock::new(); let mut query = Query::new(metadata, sql, vec![]).unwrap(); - let expected_explain = String::from( + let expected_explain = SmolStr::from( r#"projection ("t"."identification_number"::integer -> "c1", "t"."product_code"::string -> "product_code") scan "hash_testing" -> "t" execution options: @@ -78,7 +78,7 @@ vtable_max_rows = 5000 "#, ); - if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<String>() { + if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<SmolStr>() { assert_eq!(expected_explain, *actual_explain); } else { panic!("Explain must be string") @@ -94,7 +94,7 @@ fn front_explain_select_sql2() { let metadata = &RouterRuntimeMock::new(); let mut query = Query::new(metadata, sql, vec![]).unwrap(); - let expected_explain = format!( + let expected_explain: SmolStr = format_smolstr!( "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n", r#"union all"#, r#" projection ("t"."identification_number"::integer -> "c1", "t"."product_code"::string -> "product_code")"#, @@ -106,7 +106,7 @@ fn front_explain_select_sql2() { r#"vtable_max_rows = 5000"#, ); - if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<String>() { + if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<SmolStr>() { assert_eq!(expected_explain, *actual_explain); } else { panic!("Explain must be string") @@ -122,7 +122,7 @@ fn front_explain_select_sql3() { let metadata = &RouterRuntimeMock::new(); let mut query = Query::new(metadata, sql, vec![]).unwrap(); - let expected_explain = format!( + let expected_explain: SmolStr = format_smolstr!( "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n", r#"projection ("q1"."a"::string -> "a")"#, r#" join on ROW("q1"."a"::string) = ROW("q2"."a2"::string)"#, @@ -137,7 +137,7 @@ fn front_explain_select_sql3() { r#"vtable_max_rows = 5000"#, ); - if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<String>() { + if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<SmolStr>() { assert_eq!(expected_explain, *actual_explain); } else { panic!("explain must be string") @@ -153,7 +153,7 @@ fn front_explain_select_sql4() { let metadata = &RouterRuntimeMock::new(); let mut query = Query::new(metadata, sql, vec![]).unwrap(); - let expected_explain = format!( + let expected_explain: SmolStr = format_smolstr!( "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n", r#"projection ("q2"."a"::string -> "a")"#, r#" join on ROW("q1"."a"::string) = ROW("q2"."a"::string)"#, @@ -168,7 +168,7 @@ fn front_explain_select_sql4() { r#"vtable_max_rows = 5000"#, ); - if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<String>() { + if let Ok(actual_explain) = query.dispatch().unwrap().downcast::<SmolStr>() { assert_eq!(expected_explain, *actual_explain); } else { panic!("explain must be string") diff --git a/sbroad-core/src/executor/vtable.rs b/sbroad-core/src/executor/vtable.rs index 9b3b376a4..5c20eed44 100644 --- a/sbroad-core/src/executor/vtable.rs +++ b/sbroad-core/src/executor/vtable.rs @@ -5,7 +5,7 @@ use std::vec; use ahash::AHashSet; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use crate::errors::{Entity, SbroadError}; use crate::executor::engine::helpers::{TupleBuilderCommand, TupleBuilderPattern}; @@ -213,12 +213,9 @@ impl VirtualTable { let tuple = self.tuples.get(*pointer).ok_or_else(|| { SbroadError::Invalid( Entity::VirtualTable, - Some( - format!( - "Tuple with position {pointer} in the bucket index not found" - ) - .into(), - ), + Some(format_smolstr!( + "Tuple with position {pointer} in the bucket index not found" + )), ) })?; result.tuples.push(tuple.clone()); @@ -250,9 +247,9 @@ impl VirtualTable { let part = tuple.get(*col_idx).ok_or_else(|| { SbroadError::NotFound( Entity::DistributionKey, - format!( + format_smolstr!( "failed to find a distribution key column {pos} in the tuple {tuple:?}." - ).into(), + ), ) })?; shard_key_tuple.push(part); @@ -286,11 +283,10 @@ impl VirtualTable { if pos >= &self.columns.len() { return Err(SbroadError::NotFound( Entity::Column, - format!( + format_smolstr!( "primary key in the virtual table {:?} contains invalid position {pos}.", self.name - ) - .into(), + ), )); } } @@ -337,13 +333,10 @@ impl VirtualTable { let value = insert_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::TupleBuilderCommand, - Some( - format!( - "expected position {pos} with tuple len: {}", - insert_tuple.len() - ) - .into(), - ), + Some(format_smolstr!( + "expected position {pos} with tuple len: {}", + insert_tuple.len() + )), ) })?; if let Some(elem) = delete_tuple.get_mut(idx) { @@ -358,10 +351,9 @@ impl VirtualTable { let Some(v) = insert_tuple.pop() else { return Err(SbroadError::Invalid( Entity::MotionOpcode, - Some( - format!("invalid number of old shard columns: {old_shard_columns_len}") - .into(), - ), + Some(format_smolstr!( + "invalid number of old shard columns: {old_shard_columns_len}" + )), )); }; old_shard_key.push(v); @@ -439,13 +431,10 @@ impl VirtualTable { let value = update_tuple.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::TupleBuilderCommand, - Some( - format!( - "invalid pos: {pos} for update tuple with len: {}", - update_tuple.len() - ) - .into(), - ), + Some(format_smolstr!( + "invalid pos: {pos} for update tuple with len: {}", + update_tuple.len() + )), ) })?; update_tuple_shard_key.push(value); diff --git a/sbroad-core/src/frontend/sql.rs b/sbroad-core/src/frontend/sql.rs index 9709b81e9..4e10e6498 100644 --- a/sbroad-core/src/frontend/sql.rs +++ b/sbroad-core/src/frontend/sql.rs @@ -90,26 +90,20 @@ fn get_timeout(ast: &AbstractSyntaxTree, node_id: usize) -> Result<Decimal, Sbro if duration_node.rule != Rule::Duration { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST table option duration node {:?} contains unexpected children", - duration_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST table option duration node {:?} contains unexpected children", + duration_node, + )), )); } if let Some(duration_value) = duration_node.value.as_ref() { let res = Decimal::from_str(duration_value).map_err(|_| { SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST table duration node {:?} contains invalid value", - duration_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST table duration node {:?} contains invalid value", + duration_node, + )), ) })?; return Ok(res); @@ -555,13 +549,10 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST column type node {:?} has unexpected type", - type_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST column type node {:?} has unexpected type", + type_node, + )), )); } } @@ -578,31 +569,28 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!( + Some(format_smolstr!( "Expected NotFlag node, got: {:?}", not_flag_node, - ).into()))) + )))) } } _ => return Err(SbroadError::Invalid( Entity::Node, - Some(format!( + Some(format_smolstr!( "AST column null node {:?} contains unexpected children", def_child_node, - ).into()), + )), )), } } _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST column def node {:?} contains unexpected children", - def_child_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST column def node {:?} contains unexpected children", + def_child_node, + )), )); } } @@ -631,7 +619,9 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, if !column_found { return Err(SbroadError::Invalid( Entity::Column, - Some(format!("Primary key column {pk_col_name} not found.").into()), + Some(format_smolstr!( + "Primary key column {pk_col_name} not found." + )), )); } pk_keys.push(pk_col_name); @@ -654,26 +644,20 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST table engine node {:?} contains unexpected children", - engine_type_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST table engine node {:?} contains unexpected children", + engine_type_node, + )), )); } } } else { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST table engine node {:?} contains unexpected children", - child_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST table engine node {:?} contains unexpected children", + child_node, + )), )); } } @@ -695,12 +679,9 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, if !column_found { return Err(SbroadError::Invalid( Entity::Column, - Some( - format!( - "Sharding key column {shard_col_name} not found." - ) - .into(), - ), + Some(format_smolstr!( + "Sharding key column {shard_col_name} not found." + )), )); } @@ -710,26 +691,20 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( + Some(format_smolstr!( "AST table distribution node {:?} contains unexpected children", distribution_type_node, - ) - .into(), - ), + )), )); } } } else { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST table distribution node {:?} contains unexpected children", - child_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST table distribution node {:?} contains unexpected children", + child_node, + )), )); } } @@ -739,13 +714,10 @@ fn parse_create_table(ast: &AbstractSyntaxTree, node: &ParseNode) -> Result<Ddl, _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST create table node {:?} contains unexpected children", - child_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST create table node {:?} contains unexpected children", + child_node, + )), )); } } @@ -823,10 +795,9 @@ fn parse_grant_revoke( _ => { return Err(SbroadError::Invalid( Entity::Privilege, - Some( - format!("Expected to see Privilege node. Got: {privilege_node:?}") - .into(), - ), + Some(format_smolstr!( + "Expected to see Privilege node. Got: {privilege_node:?}" + )), )) } }; @@ -874,12 +845,9 @@ fn parse_grant_revoke( _ => { return Err(SbroadError::Invalid( Entity::ParseNode, - Some( - format!( - "Expected specific priv block, got: {inner_privilege_block_node:?}" - ) - .into(), - ), + Some(format_smolstr!( + "Expected specific priv block, got: {inner_privilege_block_node:?}" + )), )) } } @@ -895,7 +863,9 @@ fn parse_grant_revoke( _ => { return Err(SbroadError::Invalid( Entity::ParseNode, - Some(format!("Expected specific priv block, got: {privilege_block_node:?}").into()), + Some(format_smolstr!( + "Expected specific priv block, got: {privilege_block_node:?}" + )), )) } }; @@ -1008,9 +978,9 @@ fn parse_option<M: Metadata>( str_value.parse::<u64>().map_err(|_| { SbroadError::Invalid( Entity::Query, - Some( - format!("option value is not unsigned integer: {str_value}").into(), - ), + Some(format_smolstr!( + "option value is not unsigned integer: {str_value}" + )), ) })? } else { @@ -1027,7 +997,9 @@ fn parse_option<M: Metadata>( _ => { return Err(SbroadError::Invalid( AST, - Some(format!("unexpected child of option. id: {option_node_id}").into()), + Some(format_smolstr!( + "unexpected child of option. id: {option_node_id}" + )), )) } }; @@ -1508,7 +1480,7 @@ impl ParseExpression { // Later this code block should handle other function behaviors. return Err(SbroadError::Invalid( Entity::SQLFunction, - Some(format!("function {name} is not stable.").into()), + Some(format_smolstr!("function {name} is not stable.")), )); } } @@ -1644,9 +1616,9 @@ where if "count" != normalized_name.as_str() { return Err(SbroadError::Invalid( Entity::Query, - Some(format!( + Some(format_smolstr!( "\"*\" is allowed only inside \"count\" aggregate function. Got: {normalized_name}", - ).into()) + )) )); } let count_asterisk_plan_id = plan.nodes.push(Node::Expression(Expression::CountAsterisk)); @@ -1715,9 +1687,9 @@ where let ref_id = if present_in_left && present_in_right { return Err(SbroadError::Invalid( Entity::Column, - Some(format!( + Some(format_smolstr!( "column name '{col_name}' is present in both join children", - ).into()), + )), )); } else if present_in_left { let col_with_scan = ColumnWithScan::new(&col_name, scan_name.as_deref()); @@ -1736,7 +1708,7 @@ where } else { return Err(SbroadError::NotFound( Entity::Column, - format!("'{col_name}' in the join children",).into(), + format_smolstr!("'{col_name}' in the join children",), )); }; (ref_id, true) @@ -1745,7 +1717,7 @@ where let Ok(col_position) = left_child_col_position else { return Err(SbroadError::NotFound( Entity::Column, - format!("with name {col_name}").into(), + format_smolstr!("with name {col_name}"), )); }; let child = plan.get_relation_node(*plan_left_id)?; @@ -1840,7 +1812,7 @@ where .map_err(|e| { SbroadError::ParsingError( Entity::Value, - format!("failed to parse varchar length: {e:?}").into(), + format_smolstr!("failed to parse varchar length: {e:?}"), ) })?; Ok(CastType::Varchar(len)) @@ -1943,7 +1915,7 @@ where /// Generate an alias for the unnamed projection expressions. #[must_use] pub fn get_unnamed_column_alias(pos: usize) -> SmolStr { - format!("COL_{pos}").to_smolstr() + format_smolstr!("COL_{pos}") } /// Map of { `AbstractSyntaxTree` node id -> parsing pairs copy, corresponding to ast node }. @@ -2000,7 +1972,7 @@ impl AbstractSyntaxTree { Err(e) => { return Err(SbroadError::ParsingError( Entity::Rule, - format!("{e}").into(), + format_smolstr!("{e}"), )) } }; @@ -2205,13 +2177,10 @@ impl AbstractSyntaxTree { _ => { return Err(SbroadError::Invalid( Entity::AST, - Some( - format!( - "expected join kind node as 1 child of join. Got: {:?}", - ast_kind_node, - ) - .into(), - ), + Some(format_smolstr!( + "expected join kind node as 1 child of join. Got: {:?}", + ast_kind_node, + )), )) } }; @@ -2399,10 +2368,10 @@ impl AbstractSyntaxTree { _ => { return Err(SbroadError::Invalid( Entity::Type, - Some(format!( + Some(format_smolstr!( "expected a Column, Asterisk, ArithmeticExprAlias in projection, got {:?}.", ast_column.rule - ).into()), + )), )); } } @@ -2467,7 +2436,7 @@ impl AbstractSyntaxTree { .ok_or_else(|| { SbroadError::NotFound( Entity::Table, - format!("{scan_relation} among plan relations").into(), + format_smolstr!("{scan_relation} among plan relations"), ) })? .clone(); @@ -2514,25 +2483,19 @@ impl AbstractSyntaxTree { if pk_positions.contains(pos) { return Err(SbroadError::Invalid( Entity::Query, - Some( - format!( - "it is illegal to update primary key column: {}", - col_name - ) - .into(), - ), + Some(format_smolstr!( + "it is illegal to update primary key column: {}", + col_name + )), )); } if update_defs.contains_key(pos) { return Err(SbroadError::Invalid( Entity::Query, - Some( - format!( + Some(format_smolstr!( "The same column is specified twice in update list: {}", col_name - ) - .into(), - ), + )), )); } update_defs.insert(*pos, expr_plan_node_id); @@ -2541,7 +2504,7 @@ impl AbstractSyntaxTree { return Err(SbroadError::FailedTo( Action::Update, Some(Entity::Column), - format!("system column {col_name} cannot be updated").into(), + format_smolstr!("system column {col_name} cannot be updated"), )) } None => { @@ -2606,13 +2569,10 @@ impl AbstractSyntaxTree { _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST delete node {:?} contains unexpected children", - first_child_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST delete node {:?} contains unexpected children", + first_child_node, + )), )); } }; @@ -2624,13 +2584,11 @@ impl AbstractSyntaxTree { let column: &Column = table.columns.get(*pos).ok_or_else(|| { SbroadError::Invalid( Entity::Table, - Some( - format!( - "{} {} {pos}", - "primary key refers to non-existing column", "at position", - ) - .into(), - ), + Some(format_smolstr!( + "{} {} {pos}", + "primary key refers to non-existing column", + "at position", + )), ) })?; let col_with_scan = ColumnWithScan::new(column.name.as_str(), None); @@ -2677,13 +2635,10 @@ impl AbstractSyntaxTree { _ => { return Err(SbroadError::Invalid( Entity::AST, - Some( - format!( - "expected conflict strategy on \ + Some(format_smolstr!( + "expected conflict strategy on \ AST id ({child_id}). Got: {rule:?}" - ) - .into(), - ), + )), )) } }; @@ -2702,7 +2657,7 @@ impl AbstractSyntaxTree { let rel = plan.relations.get(&relation).ok_or_else(|| { SbroadError::NotFound( Entity::Table, - format!("{relation} among plan relations").into(), + format_smolstr!("{relation} among plan relations"), ) })?; for column in &rel.columns { @@ -2712,10 +2667,10 @@ impl AbstractSyntaxTree { if !column.is_nullable && !selected_col_names.contains(&column.name) { return Err(SbroadError::Invalid( Entity::Column, - Some( - format!("NonNull column {} must be specified", column.name) - .into(), - ), + Some(format_smolstr!( + "NonNull column {} must be specified", + column.name + )), )); } } @@ -2840,13 +2795,10 @@ impl AbstractSyntaxTree { _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "AST drop table node {:?} contains unexpected children", - child_node, - ) - .into(), - ), + Some(format_smolstr!( + "AST drop table node {:?} contains unexpected children", + child_node, + )), )); } } @@ -2978,12 +2930,9 @@ impl AbstractSyntaxTree { _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "ACL node contains unexpected child: {child_node:?}", - ) - .into(), - ), + Some(format_smolstr!( + "ACL node contains unexpected child: {child_node:?}", + )), )); } } diff --git a/sbroad-core/src/frontend/sql/ast.rs b/sbroad-core/src/frontend/sql/ast.rs index 5432fd49c..18dfa7324 100644 --- a/sbroad-core/src/frontend/sql/ast.rs +++ b/sbroad-core/src/frontend/sql/ast.rs @@ -9,7 +9,7 @@ use std::collections::{HashMap, HashSet}; use std::mem::swap; use pest::iterators::Pair; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use crate::errors::{Entity, SbroadError}; @@ -58,7 +58,10 @@ impl ParseNodes { /// - Failed to get a node from arena. pub fn get_node(&self, node: usize) -> Result<&ParseNode, SbroadError> { self.arena.get(node).ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("from arena with index {node}").into()) + SbroadError::NotFound( + Entity::Node, + format_smolstr!("from arena with index {node}"), + ) }) } @@ -70,7 +73,7 @@ impl ParseNodes { self.arena.get_mut(node).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(mutable) from arena with index {node}").into(), + format_smolstr!("(mutable) from arena with index {node}"), ) }) } @@ -140,7 +143,7 @@ impl ParseNodes { let parent_node = self.arena.get_mut(parent).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(mutable) from arena with index {parent}").into(), + format_smolstr!("(mutable) from arena with index {parent}"), ) })?; parent_node.children.insert(0, child); @@ -156,7 +159,7 @@ impl ParseNodes { let node = self.arena.get_mut(node).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(mutable) from arena with index {node}").into(), + format_smolstr!("(mutable) from arena with index {node}"), ) })?; node.value = value; @@ -240,7 +243,7 @@ impl AbstractSyntaxTree { } else { return Err(SbroadError::Invalid( Entity::ParseNode, - Some(format!("expected join parse node, got: {node:?}").into()), + Some(format_smolstr!("expected join parse node, got: {node:?}")), )); } Ok(()) @@ -398,10 +401,9 @@ impl AbstractSyntaxTree { if filter_node.rule != Rule::DeleteFilter { return Err(SbroadError::Invalid( Entity::ParseNode, - Some( - format!("expected delete filter as a second child, got: {filter_node:?}") - .into(), - ), + Some(format_smolstr!( + "expected delete filter as a second child, got: {filter_node:?}" + )), )); } let mut new_filter_children = Vec::with_capacity(filter_node.children.len() + 1); @@ -450,7 +452,7 @@ impl AbstractSyntaxTree { let child_id = *parent.children.get(children_pos).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("at expected position {children_pos}").into(), + format_smolstr!("at expected position {children_pos}"), ) })?; let child = self.nodes.get_node(child_id)?; diff --git a/sbroad-core/src/frontend/sql/ir.rs b/sbroad-core/src/frontend/sql/ir.rs index 5cf6824f0..8bc901b60 100644 --- a/sbroad-core/src/frontend/sql/ir.rs +++ b/sbroad-core/src/frontend/sql/ir.rs @@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet}; use ahash::AHashMap; use pest::iterators::Pair; +use smol_str::format_smolstr; use tarantool::decimal::Decimal; use crate::errors::{Action, Entity, SbroadError}; @@ -35,7 +36,7 @@ impl Value { .map_err(|e| { SbroadError::ParsingError( Entity::Value, - format!("i64 parsing error {e}").into(), + format_smolstr!("i64 parsing error {e}"), ) })? .into()), @@ -44,7 +45,7 @@ impl Value { .map_err(|e| { SbroadError::ParsingError( Entity::Value, - format!("decimal parsing error {e:?}").into(), + format_smolstr!("decimal parsing error {e:?}"), ) })? .into()), @@ -53,7 +54,7 @@ impl Value { .map_err(|e| { SbroadError::ParsingError( Entity::Value, - format!("double parsing error {e}").into(), + format_smolstr!("double parsing error {e}"), ) })? .into()), @@ -62,7 +63,7 @@ impl Value { .map_err(|e| { SbroadError::ParsingError( Entity::Value, - format!("u64 parsing error {e}").into(), + format_smolstr!("u64 parsing error {e}"), ) })? .into()), @@ -99,7 +100,7 @@ impl Translation { self.map.get(&old).copied().ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(parse node) [{old}] in translation map").into(), + format_smolstr!("(parse node) [{old}] in translation map"), ) }) } @@ -307,7 +308,7 @@ impl Plan { | Expression::Cast { ref mut child, .. } | Expression::Unary { ref mut child, .. } => { *child = *map.get(child).ok_or_else(|| { - SbroadError::NotFound(Entity::SubTree, format!("(id {id})").into()) + SbroadError::NotFound(Entity::SubTree, format_smolstr!("(id {id})")) })?; } Expression::Bool { @@ -326,10 +327,10 @@ impl Plan { .. } => { *left = *map.get(left).ok_or_else(|| { - SbroadError::NotFound(Entity::SubTree, format!("(id {id})").into()) + SbroadError::NotFound(Entity::SubTree, format_smolstr!("(id {id})")) })?; *right = *map.get(right).ok_or_else(|| { - SbroadError::NotFound(Entity::SubTree, format!("(id {id})").into()) + SbroadError::NotFound(Entity::SubTree, format_smolstr!("(id {id})")) })?; } Expression::Row { @@ -341,7 +342,7 @@ impl Plan { } => { for child in children { *child = *map.get(child).ok_or_else(|| { - SbroadError::NotFound(Entity::SubTree, format!("(id {id})").into()) + SbroadError::NotFound(Entity::SubTree, format_smolstr!("(id {id})")) })?; } } @@ -374,7 +375,7 @@ impl SubtreeCloner { .ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some(format!("new node not found for old id: {old_id}").into()), + Some(format_smolstr!("new node not found for old id: {old_id}")), ) }) .copied() @@ -642,9 +643,9 @@ impl SubtreeCloner { _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!("clone: expected relational or expression on id: {id}").into(), - ), + Some(format_smolstr!( + "clone: expected relational or expression on id: {id}" + )), )) } }; @@ -653,12 +654,9 @@ impl SubtreeCloner { if let Some(old_new_id) = old { return Err(SbroadError::Invalid( Entity::Plan, - Some( - format!( - "clone: node with id {id} was mapped twice: {old_new_id}, {new_id}" - ) - .into(), - ), + Some(format_smolstr!( + "clone: node with id {id} was mapped twice: {old_new_id}, {new_id}" + )), )); } } @@ -671,7 +669,9 @@ impl SubtreeCloner { .ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some(format!("invalid subtree traversal with top: {top_id}").into()), + Some(format_smolstr!( + "invalid subtree traversal with top: {top_id}" + )), ) }) .copied()?; diff --git a/sbroad-core/src/frontend/sql/ir/tests/join.rs b/sbroad-core/src/frontend/sql/ir/tests/join.rs index 0f418a40c..9c0777e53 100644 --- a/sbroad-core/src/frontend/sql/ir/tests/join.rs +++ b/sbroad-core/src/frontend/sql/ir/tests/join.rs @@ -1,5 +1,4 @@ use crate::ir::transformation::helpers::sql_to_optimized_ir; -use crate::ir::value::Value; use pretty_assertions::assert_eq; #[test] diff --git a/sbroad-core/src/ir.rs b/sbroad-core/src/ir.rs index 352c0ea70..dd6fd90fc 100644 --- a/sbroad-core/src/ir.rs +++ b/sbroad-core/src/ir.rs @@ -4,7 +4,7 @@ use base64ct::{Base64, Encoding}; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::collections::hash_map::IntoIter; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; @@ -96,7 +96,7 @@ impl Nodes { match self.arena.get(id) { None => Err(SbroadError::NotFound( Entity::Node, - format!("from arena with index {id}").into(), + format_smolstr!("from arena with index {id}"), )), Some(node) => Ok(node), } @@ -106,7 +106,7 @@ impl Nodes { match self.arena.get_mut(id) { None => Err(SbroadError::NotFound( Entity::Node, - format!("from arena with index {id}").into(), + format_smolstr!("from arena with index {id}"), )), Some(node) => Ok(node), } @@ -166,9 +166,9 @@ impl Nodes { /// - The node with the given position doesn't exist. pub fn replace(&mut self, id: usize, node: Node) -> Result<Node, SbroadError> { if id >= self.arena.len() { - return Err(SbroadError::UnexpectedNumberOfValues( - format!("can't replace node with id {id} as it is out of arena bounds").into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "can't replace node with id {id} as it is out of arena bounds" + ))); } let old_node = std::mem::replace(&mut self.arena[id], node); Ok(old_node) @@ -511,7 +511,10 @@ impl Plan { if !used_options.insert(opt.kind.clone()) { return Err(SbroadError::Invalid( Query, - Some(format!("option {} specified more than once!", opt.kind).into()), + Some(format_smolstr!( + "option {} specified more than once!", + opt.kind + )), )); } let OptionParamValue::Value { val } = opt.val else { @@ -530,10 +533,10 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::OptionSpec, - Some( - format!("expected option {} to be unsigned got: {val:?}", opt.kind) - .into(), - ), + Some(format_smolstr!( + "expected option {} to be unsigned got: {val:?}", + opt.kind + )), )); } } @@ -541,20 +544,20 @@ impl Plan { if let Value::Unsigned(limit) = val { if let Some(vtable_rows_count) = values_count { if limit < vtable_rows_count as u64 { - return Err(SbroadError::UnexpectedNumberOfValues(format!( + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( "Exceeded maximum number of rows ({limit}) in virtual table: {}", vtable_rows_count - ).into())); + ))); } } self.options.vtable_max_rows = limit; } else { return Err(SbroadError::Invalid( Entity::OptionSpec, - Some( - format!("expected option {} to be unsigned got: {val:?}", opt.kind) - .into(), - ), + Some(format_smolstr!( + "expected option {} to be unsigned got: {val:?}", + opt.kind + )), )); } } @@ -578,7 +581,7 @@ impl Plan { match self.nodes.arena.get(id) { None => Err(SbroadError::NotFound( Entity::Node, - format!("from arena with index {id}").into(), + format_smolstr!("from arena with index {id}"), )), Some(node) => Ok(node), } @@ -593,7 +596,7 @@ impl Plan { match self.nodes.arena.get_mut(id) { None => Err(SbroadError::NotFound( Entity::Node, - format!("(mutable) from arena with index {id}").into(), + format_smolstr!("(mutable) from arena with index {id}"), )), Some(node) => Ok(node), } @@ -619,9 +622,9 @@ impl Plan { /// # Errors /// - no relation with given name pub fn get_relation_or_error(&self, name: &str) -> Result<&Table, SbroadError> { - self.relations - .get(name) - .ok_or_else(|| SbroadError::NotFound(Entity::Table, format!("with name {name}").into())) + self.relations.get(name).ok_or_else(|| { + SbroadError::NotFound(Entity::Table, format_smolstr!("with name {name}")) + }) } /// Get relation of a scan node @@ -635,7 +638,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected scan node, got: {node:?}").into()), + Some(format_smolstr!("expected scan node, got: {node:?}")), )) } @@ -655,9 +658,9 @@ impl Plan { .ok_or_else(|| { SbroadError::Invalid( Entity::Column, - Some( - format!("invalid column position {col_idx} for table {table_name}").into(), - ), + Some(format_smolstr!( + "invalid column position {col_idx} for table {table_name}" + )), ) }) } @@ -751,7 +754,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not Relational type: {n:?}").into()), + Some(format_smolstr!("node is not Relational type: {n:?}")), )) } @@ -872,7 +875,7 @@ impl Plan { | Node::Acl(..) | Node::Block(..) => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not Relational type: {node:?}").into()), + Some(format_smolstr!("node is not Relational type: {node:?}")), )), } } @@ -942,7 +945,9 @@ impl Plan { | Node::Acl(..) | Node::Block(..) => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node ({node_id}) is not expression type: {node:?}").into()), + Some(format_smolstr!( + "node ({node_id}) is not expression type: {node:?}" + )), )), } } @@ -1034,7 +1039,7 @@ impl Plan { Err(SbroadError::FailedTo( Action::Replace, Some(Entity::Expression), - format!("parent expression ({parent_id}) has no child with id {old_id}").into(), + format_smolstr!("parent expression ({parent_id}) has no child with id {old_id}"), )) } @@ -1047,15 +1052,15 @@ impl Plan { let node = self.get_relation_node(groupby_id)?; if let Relational::GroupBy { gr_cols, .. } = node { let col_id = gr_cols.get(col_idx).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("groupby column index out of range. Node: {node:?}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "groupby column index out of range. Node: {node:?}" + )) })?; return Ok(*col_id); } Err(SbroadError::Invalid( Entity::Node, - Some(format!("Expected GroupBy node. Got: {node:?}").into()), + Some(format_smolstr!("Expected GroupBy node. Got: {node:?}")), )) } @@ -1068,15 +1073,15 @@ impl Plan { let node = self.get_relation_node(proj_id)?; if let Relational::Projection { output, .. } = node { let col_id = self.get_row_list(*output)?.get(col_idx).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("projection column index out of range. Node: {node:?}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "projection column index out of range. Node: {node:?}" + )) })?; return Ok(*col_id); } Err(SbroadError::Invalid( Entity::Node, - Some(format!("Expected Projection node. Got: {node:?}").into()), + Some(format_smolstr!("Expected Projection node. Got: {node:?}")), )) } @@ -1091,7 +1096,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("Expected GroupBy node. Got: {node:?}").into()), + Some(format_smolstr!("Expected GroupBy node. Got: {node:?}")), )) } @@ -1111,7 +1116,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("Expected GroupBy node. Got: {node:?}").into()), + Some(format_smolstr!("Expected GroupBy node. Got: {node:?}")), )) } @@ -1174,7 +1179,7 @@ impl Plan { .ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("type Column with index {column_index_in_list}").into(), + format_smolstr!("type Column with index {column_index_in_list}"), ) })?; @@ -1188,7 +1193,7 @@ impl Plan { .ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!("at position {position} in row list").into(), + format_smolstr!("at position {position} in row list"), ) })?; @@ -1237,7 +1242,7 @@ impl Plan { SbroadError::FailedTo( Action::Serialize, None, - format!("plan nodes to binary: {e:?}").into(), + format_smolstr!("plan nodes to binary: {e:?}"), ) })?; let hash = Base64::encode_string(blake3::hash(&bytes).to_hex().as_bytes()).to_smolstr(); @@ -1309,10 +1314,9 @@ impl Plan { let child_id = children.get(*target).ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some( - format!("invalid target ({target}) in reference with id: {ref_id}") - .into(), - ), + Some(format_smolstr!( + "invalid target ({target}) in reference with id: {ref_id}" + )), ) })?; let Some(candidates) = memo.get(child_id) else { diff --git a/sbroad-core/src/ir/acl.rs b/sbroad-core/src/ir/acl.rs index a9df2534b..b2c295995 100644 --- a/sbroad-core/src/ir/acl.rs +++ b/sbroad-core/src/ir/acl.rs @@ -1,6 +1,6 @@ use crate::ir::{Entity, Node, Plan, SbroadError}; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use tarantool::decimal::Decimal; use super::ddl::ParamDef; @@ -64,7 +64,7 @@ fn check_privilege(privilege: Privilege, accepted: &[Privilege]) -> Result<(), S if !accepted.contains(&privilege) { return Err(SbroadError::Invalid( Entity::Privilege, - Some(format!("Supported privileges are: {accepted:?}").into()), + Some(format_smolstr!("Supported privileges are: {accepted:?}")), )); } Ok(()) @@ -244,7 +244,7 @@ impl Acl { .map_err(|e| { SbroadError::Invalid( Entity::SpaceMetadata, - Some(format!("timeout parsing error {e:?}").into()), + Some(format_smolstr!("timeout parsing error {e:?}")), ) }) } @@ -262,7 +262,7 @@ impl Plan { Node::Acl(acl) => Ok(acl), _ => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not ACL type: {node:?}").into()), + Some(format_smolstr!("node is not ACL type: {node:?}")), )), } } @@ -278,7 +278,7 @@ impl Plan { Node::Acl(acl) => Ok(acl), _ => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not ACL type: {node:?}").into()), + Some(format_smolstr!("node is not ACL type: {node:?}")), )), } } @@ -296,7 +296,7 @@ impl Plan { Node::Acl(acl) => Ok(acl), _ => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not ACL type: {node:?}").into()), + Some(format_smolstr!("node is not ACL type: {node:?}")), )), } } diff --git a/sbroad-core/src/ir/aggregates.rs b/sbroad-core/src/ir/aggregates.rs index 4f45b4cb6..4694764a7 100644 --- a/sbroad-core/src/ir/aggregates.rs +++ b/sbroad-core/src/ir/aggregates.rs @@ -1,4 +1,4 @@ -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use crate::errors::{Entity, SbroadError}; use crate::ir::expression::cast::Type; @@ -100,12 +100,9 @@ impl AggregateKind { (_, _) => { return Err(SbroadError::Invalid( Entity::Aggregate, - Some( - format!( + Some(format_smolstr!( "invalid local aggregate {local_aggregate} for original aggregate: {self}" - ) - .into(), - ), + )), )) } }; @@ -184,7 +181,9 @@ impl SimpleAggregate { let local_alias = self.lagg_alias.get(&self.kind).ok_or_else(|| { SbroadError::Invalid( Entity::Aggregate, - Some(format!("missing local alias for distinct aggregate: {self:?}").into()), + Some(format_smolstr!( + "missing local alias for distinct aggregate: {self:?}" + )), ) })?; let position = alias_to_pos.get(local_alias)?; @@ -196,12 +195,9 @@ impl SimpleAggregate { let local_alias = self.lagg_alias.get(&aggr_kind).ok_or_else(|| { SbroadError::Invalid( Entity::Aggregate, - Some( - format!( - "missing local alias for local aggregate ({aggr_kind}): {self:?}" - ) - .into(), - ), + Some(format_smolstr!( + "missing local alias for local aggregate ({aggr_kind}): {self:?}" + )), ) })?; let position = alias_to_pos.get(local_alias)?; @@ -277,10 +273,10 @@ impl SimpleAggregate { } else { return Err(SbroadError::Invalid( Entity::Aggregate, - Some( - format!("fun_id ({}) points to other expression node", self.fun_id) - .into(), - ), + Some(format_smolstr!( + "fun_id ({}) points to other expression node", + self.fun_id + )), )); } } @@ -335,7 +331,9 @@ impl SimpleAggregate { _ => { return Err(SbroadError::Unsupported( Entity::Aggregate, - Some(format!("aggregate with multiple final aggregates: {self:?}").into()), + Some(format_smolstr!( + "aggregate with multiple final aggregates: {self:?}" + )), )) } } diff --git a/sbroad-core/src/ir/api/constant.rs b/sbroad-core/src/ir/api/constant.rs index 20a731fab..65356e0f9 100644 --- a/sbroad-core/src/ir/api/constant.rs +++ b/sbroad-core/src/ir/api/constant.rs @@ -1,3 +1,5 @@ +use smol_str::format_smolstr; + use crate::errors::{Entity, SbroadError}; use crate::ir::expression::Expression; use crate::ir::value::Value; @@ -80,9 +82,9 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!( + Some(format_smolstr!( "Restoring parameters filed: node {const_node:?} (id: {id}) is not of a constant type" - ).into()), + )), )); } self.nodes.replace(id, const_node)?; diff --git a/sbroad-core/src/ir/api/parameter.rs b/sbroad-core/src/ir/api/parameter.rs index 9d43df2eb..e95c1509f 100644 --- a/sbroad-core/src/ir/api/parameter.rs +++ b/sbroad-core/src/ir/api/parameter.rs @@ -9,6 +9,7 @@ use crate::otm::child_span; use sbroad_proc::otm_child_span; use ahash::RandomState; +use smol_str::format_smolstr; use std::collections::{HashMap, HashSet}; impl Plan { @@ -81,12 +82,9 @@ impl Plan { let invalid_idx = |param_id: usize, value_idx: usize| { SbroadError::Invalid( Entity::Plan, - Some( - format!( - "out of bounds value index {value_idx} for pg parameter {param_id}" - ) - .into(), - ), + Some(format_smolstr!( + "out of bounds value index {value_idx} for pg parameter {param_id}" + )), ) }; @@ -100,9 +98,9 @@ impl Plan { } let value_idx = *pg_params_map.get(param_id).ok_or(SbroadError::Invalid( Entity::Plan, - Some( - format!("value index not found for parameter with id: {param_id}",).into(), - ), + Some(format_smolstr!( + "value index not found for parameter with id: {param_id}", + )), ))?; if used_values.get(value_idx).copied().unwrap_or(true) { let Some(value) = values.get(value_idx) else { @@ -137,14 +135,11 @@ impl Plan { if tnt_params_style && non_binded_params_len > value_ids.len() { return Err(SbroadError::Invalid( Entity::Value, - Some( - format!( - "Expected at least {} values for parameters. Got {}.", - non_binded_params_len, - value_ids.len() - ) - .into(), - ), + Some(format_smolstr!( + "Expected at least {} values for parameters. Got {}.", + non_binded_params_len, + value_ids.len() + )), )); } @@ -164,17 +159,16 @@ impl Plan { - *pg_params_map.get(¶m_id).ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some( - format!("value index not found for parameter with id: {param_id}",) - .into(), - ), + Some(format_smolstr!( + "value index not found for parameter with id: {param_id}", + )), ) })? }; let val_id = value_ids.get(value_idx).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("(Parameter) in position {value_idx}").into(), + format_smolstr!("(Parameter) in position {value_idx}"), ) })?; Ok(*val_id) @@ -280,7 +274,10 @@ impl Plan { // Closure to retrieve a corresponding row for a parameter node. let get_row = |param_id: usize| -> Result<usize, SbroadError> { let row_id = row_ids.get(¶m_id).ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("(Row) at position {param_id}").into()) + SbroadError::NotFound( + Entity::Node, + format_smolstr!("(Row) at position {param_id}"), + ) })?; Ok(*row_id) }; @@ -431,18 +428,17 @@ impl Plan { let value_idx = *self.pg_params_map.get(¶m_id).ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some( - format!("no value idx in map for option parameter: {opt:?}").into(), - ), + Some(format_smolstr!( + "no value idx in map for option parameter: {opt:?}" + )), ) })?; let value = values.get(value_idx).ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some( - format!("invalid value idx {value_idx}, for option: {opt:?}") - .into(), - ), + Some(format_smolstr!( + "invalid value idx {value_idx}, for option: {opt:?}" + )), ) })?; opt.val = OptionParamValue::Value { val: value.clone() }; @@ -452,9 +448,10 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Query, - Some( - format!("no parameter value specified for option: {}", opt.kind).into(), - ), + Some(format_smolstr!( + "no parameter value specified for option: {}", + opt.kind + )), )); } } diff --git a/sbroad-core/src/ir/block.rs b/sbroad-core/src/ir/block.rs index 700f6802e..df483d3b0 100644 --- a/sbroad-core/src/ir/block.rs +++ b/sbroad-core/src/ir/block.rs @@ -3,7 +3,7 @@ use crate::errors::{Entity, SbroadError}; use crate::ir::{Node, NodeId, Plan}; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub enum Block { @@ -40,7 +40,9 @@ impl Plan { | Node::Acl(..) | Node::Parameter => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node {node:?} (id {node_id}) is not Block type").into()), + Some(format_smolstr!( + "node {node:?} (id {node_id}) is not Block type" + )), )), } } @@ -59,7 +61,9 @@ impl Plan { | Node::Acl(..) | Node::Parameter => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node {node:?} (id {node_id}) is not Block type").into()), + Some(format_smolstr!( + "node {node:?} (id {node_id}) is not Block type" + )), )), } } diff --git a/sbroad-core/src/ir/ddl.rs b/sbroad-core/src/ir/ddl.rs index 4a8cf1a7e..350c6d1f6 100644 --- a/sbroad-core/src/ir/ddl.rs +++ b/sbroad-core/src/ir/ddl.rs @@ -3,7 +3,7 @@ use crate::{ ir::{relation::Type, Node, Plan}, }; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use tarantool::space::SpaceEngineType; use tarantool::{ decimal::Decimal, @@ -114,7 +114,7 @@ impl Ddl { .map_err(|e| { SbroadError::Invalid( Entity::SpaceMetadata, - Some(format!("timeout parsing error {e:?}").into()), + Some(format_smolstr!("timeout parsing error {e:?}")), ) }) } @@ -132,7 +132,7 @@ impl Plan { Node::Ddl(ddl) => Ok(ddl), _ => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not DDL type: {node:?}").into()), + Some(format_smolstr!("node is not DDL type: {node:?}")), )), } } @@ -148,7 +148,7 @@ impl Plan { Node::Ddl(ddl) => Ok(ddl), _ => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not DDL type: {node:?}").into()), + Some(format_smolstr!("node is not DDL type: {node:?}")), )), } } @@ -166,7 +166,7 @@ impl Plan { Node::Ddl(ddl) => Ok(ddl), _ => Err(SbroadError::Invalid( Entity::Node, - Some(format!("node is not DDL type: {node:?}").into()), + Some(format_smolstr!("node is not DDL type: {node:?}")), )), } } diff --git a/sbroad-core/src/ir/distribution.rs b/sbroad-core/src/ir/distribution.rs index 7e0d77610..88888f1dd 100644 --- a/sbroad-core/src/ir/distribution.rs +++ b/sbroad-core/src/ir/distribution.rs @@ -1,7 +1,7 @@ //! Tuple distribution module. use ahash::{AHashMap, RandomState}; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use std::collections::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; @@ -49,13 +49,15 @@ impl Key { SbroadError::FailedTo( Action::Create, Some(Entity::Column), - format!("column {name} not found at position {pos}").into(), + format_smolstr!("column {name} not found at position {pos}"), ) })?; if !column.r#type.is_scalar() { return Err(SbroadError::Invalid( Entity::Column, - Some(format!("column {name} at position {pos} is not scalar",).into()), + Some(format_smolstr!( + "column {name} at position {pos} is not scalar" + )), )); } Ok(pos) @@ -87,7 +89,7 @@ impl TryFrom<&MotionKey> for KeySet { return Err(SbroadError::FailedTo( Action::Create, Some(Entity::DistributionKey), - format!("found value target in motion key: {v}").into(), + format_smolstr!("found value target in motion key: {v}"), )); } } @@ -161,7 +163,7 @@ impl Distribution { (Distribution::Single, _) | (_, Distribution::Single) => { return Err(SbroadError::Invalid( Entity::Distribution, - Some(format!("union child has unexpected distribution Single. Left: {left:?}, right: {right:?}").into()))); + Some(format_smolstr!("union child has unexpected distribution Single. Left: {left:?}, right: {right:?}")))); } ( Distribution::Segment { @@ -194,7 +196,7 @@ impl Distribution { (Distribution::Single, _) | (_, Distribution::Single) => { return Err(SbroadError::Invalid( Entity::Distribution, - Some(format!("union/except child has unexpected distribution Single. Left: {left:?}, right: {right:?}").into()))); + Some(format_smolstr!("union/except child has unexpected distribution Single. Left: {left:?}, right: {right:?}")))); } (Distribution::Any, _) | (_, Distribution::Any) => Distribution::Any, ( @@ -228,7 +230,7 @@ impl Distribution { (Distribution::Single, _) | (_, Distribution::Single) => { return Err(SbroadError::Invalid( Entity::Distribution, - Some(format!("join child has unexpected distribution Single. Left: {left:?}, right: {right:?}").into()))); + Some(format_smolstr!("join child has unexpected distribution Single. Left: {left:?}, right: {right:?}")))); } (Distribution::Global, Distribution::Global) => { // this case is handled by `dist_from_subqueries`` @@ -419,7 +421,7 @@ impl Plan { ) { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected projection on id: {proj_id}").into()), + Some(format_smolstr!("expected projection on id: {proj_id}")), )); }; @@ -453,7 +455,9 @@ impl Plan { let children = self.get_relational_children(proj_id)?.ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some(format!("projection node ({proj_id}) has no children").into()), + Some(format_smolstr!( + "projection node ({proj_id}) has no children" + )), ) })?; let ref_info = ReferenceInfo::new(output_id, self, children)?; @@ -637,7 +641,9 @@ impl Plan { // distribution. return Err(SbroadError::Invalid( Entity::Distribution, - Some(format!("expected Motion(Full) for subquery child ({sq_id})").into()), + Some(format_smolstr!( + "expected Motion(Full) for subquery child ({sq_id})" + )), )); } Distribution::Single | Distribution::Global => {} diff --git a/sbroad-core/src/ir/explain.rs b/sbroad-core/src/ir/explain.rs index 03d193db5..06f67eeba 100644 --- a/sbroad-core/src/ir/explain.rs +++ b/sbroad-core/src/ir/explain.rs @@ -4,7 +4,7 @@ use std::mem::take; use itertools::Itertools; use serde::Serialize; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use crate::errors::{Entity, SbroadError}; use crate::ir::expression::cast::Type as CastType; @@ -173,7 +173,7 @@ impl ColExpr { while len > 0 { let (arg, _) = stack.pop().ok_or_else(|| { SbroadError::UnexpectedNumberOfValues( - format!("stack is empty, expected to pop {len} element while processing STABLE FUNCTION expression").into(), + format_smolstr!("stack is empty, expected to pop {len} element while processing STABLE FUNCTION expression"), ) })?; args.push(arg); @@ -194,7 +194,7 @@ impl ColExpr { while len > 0 { let expr = stack.pop().ok_or_else(|| { SbroadError::UnexpectedNumberOfValues( - format!("stack is empty, expected to pop {len} element while processing ROW expression").into(), + format_smolstr!("stack is empty, expected to pop {len} element while processing ROW expression"), ) })?; row.push(expr); @@ -406,7 +406,7 @@ impl Update { let table = plan.relations.get(rel).ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some(format!("invalid table {rel} in Update node").into()), + Some(format_smolstr!("invalid table {rel} in Update node")), ) })?; let output_list = plan.get_row_list(*output_id)?; @@ -418,19 +418,18 @@ impl Update { .ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some(format!("invalid column index {col_idx} in Update node").into()), + Some(format_smolstr!( + "invalid column index {col_idx} in Update node" + )), ) })?; let proj_alias = { let alias_id = *output_list.get(*proj_col).ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some( - format!( - "invalid update projection position {proj_col} in Update node" - ) - .into(), - ), + Some(format_smolstr!( + "invalid update projection position {proj_col} in Update node" + )), ) })?; let node = plan.get_expression_node(alias_id)?; @@ -439,10 +438,9 @@ impl Update { } else { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!("expected alias as top in Update output, got: {node:?}") - .into(), - ), + Some(format_smolstr!( + "expected alias as top in Update output, got: {node:?}" + )), )); } }; @@ -456,7 +454,9 @@ impl Update { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("explain: expected Update node on id: {update_id}").into()), + Some(format_smolstr!( + "explain: expected Update node on id: {update_id}" + )), )) } } @@ -580,19 +580,16 @@ impl Row { let sq_offset = sq_ref_map.get(&rel_id).ok_or_else(|| { SbroadError::NotFound( Entity::SubQuery, - format!("with index {rel_id} in the map").into(), + format_smolstr!("with index {rel_id} in the map"), ) })?; row.add_col(RowVal::SqRef(Ref::new(*sq_offset))); } else { return Err(SbroadError::Invalid( Entity::Plan, - Some( - format!( + Some(format_smolstr!( "additional child ({rel_id}) is not SQ or Motion: {rel_node:?}" - ) - .into(), - ), + )), )); } } else { @@ -760,22 +757,24 @@ enum ExplainNode { impl Display for ExplainNode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let s = match &self { - ExplainNode::Delete(s) => format!("delete {s}"), - ExplainNode::Except => "except".to_string(), - ExplainNode::InnerJoin(i) => i.to_string(), - ExplainNode::ValueRow(r) => format!("value row (data={r})"), - ExplainNode::Value => "values".to_string(), - ExplainNode::Insert(s, conflict) => format!("insert {s} on conflict: {conflict}"), - ExplainNode::Projection(e) => e.to_string(), - ExplainNode::GroupBy(p) => p.to_string(), - ExplainNode::Scan(s) => s.to_string(), - ExplainNode::Selection(s) => format!("selection {s}"), - ExplainNode::Having(s) => format!("having {s}"), - ExplainNode::UnionAll => "union all".to_string(), - ExplainNode::Intersect => "intersect".to_string(), - ExplainNode::Update(u) => u.to_string(), - ExplainNode::SubQuery(s) => s.to_string(), - ExplainNode::Motion(m) => m.to_string(), + ExplainNode::Delete(s) => format_smolstr!("delete {s}"), + ExplainNode::Except => "except".to_smolstr(), + ExplainNode::InnerJoin(i) => i.to_smolstr(), + ExplainNode::ValueRow(r) => format_smolstr!("value row (data={r})"), + ExplainNode::Value => "values".to_smolstr(), + ExplainNode::Insert(s, conflict) => { + format_smolstr!("insert {s} on conflict: {conflict}") + } + ExplainNode::Projection(e) => e.to_smolstr(), + ExplainNode::GroupBy(p) => p.to_smolstr(), + ExplainNode::Scan(s) => s.to_smolstr(), + ExplainNode::Selection(s) => format_smolstr!("selection {s}"), + ExplainNode::Having(s) => format_smolstr!("having {s}"), + ExplainNode::UnionAll => "union all".to_smolstr(), + ExplainNode::Intersect => "intersect".to_smolstr(), + ExplainNode::Update(u) => u.to_smolstr(), + ExplainNode::SubQuery(s) => s.to_smolstr(), + ExplainNode::Motion(m) => m.to_smolstr(), }; write!(f, "{s}") @@ -1019,7 +1018,7 @@ impl FullExplain { let col_id = *col_list.get(*pos).ok_or_else(|| { SbroadError::NotFound( Entity::Target, - format!("reference with position {pos}").into(), + format_smolstr!("reference with position {pos}"), ) })?; let col_name = ir @@ -1182,10 +1181,10 @@ impl Plan { /// # Errors /// - Failed to get top node /// - Failed to build explain - pub fn as_explain(&self) -> Result<String, SbroadError> { + pub fn as_explain(&self) -> Result<SmolStr, SbroadError> { let top_id = self.get_top()?; let explain = FullExplain::new(self, top_id)?; - Ok(explain.to_string()) + Ok(explain.to_smolstr()) } } diff --git a/sbroad-core/src/ir/expression.rs b/sbroad-core/src/ir/expression.rs index 570733b14..9cded1277 100644 --- a/sbroad-core/src/ir/expression.rs +++ b/sbroad-core/src/ir/expression.rs @@ -8,7 +8,7 @@ use ahash::RandomState; use serde::{Deserialize, Serialize}; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::collections::{BTreeMap, HashSet}; use std::hash::{Hash, Hasher}; use std::ops::Bound::Included; @@ -386,13 +386,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}").into(), + format_smolstr!("(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}").into(), + format_smolstr!("(right child of boolean node) from arena with index {right}"), ) })?; Ok(self.push(Node::Expression(Expression::Bool { left, op, right }))) @@ -411,13 +411,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}").into(), + format_smolstr!("(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}").into(), + format_smolstr!("(right child of Arithmetic node) from arena with index {right}"), ) })?; Ok(self.push(Node::Expression(Expression::Arithmetic { left, op, right }))) @@ -457,7 +457,7 @@ impl Nodes { self.arena.get(child).ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("from arena with index {child}").into(), + format_smolstr!("from arena with index {child}"), ) })?; Ok(self.push(Node::Expression(Expression::Unary { op, child }))) @@ -854,9 +854,9 @@ impl ColumnPositionMap { // } // // So that given just a column name we can't say what column to refer to. - (Some(..), Some(..)) => Err(SbroadError::DuplicatedValue( - format!("column name {column} is ambiguous").into(), - )), + (Some(..), Some(..)) => Err(SbroadError::DuplicatedValue(format_smolstr!( + "column name {column} is ambiguous" + ))), // Map contains single value for the given `column`. (Some((_, position)), None) => { if let Positions::Single(pos) = position { @@ -865,13 +865,13 @@ impl ColumnPositionMap { // In case we have query like // `select "a", "a" from (select "a" from t)` // where single column is met on several positions. - Err(SbroadError::DuplicatedValue( - format!("column name {column} is ambiguous").into(), - )) + Err(SbroadError::DuplicatedValue(format_smolstr!( + "column name {column} is ambiguous" + ))) } _ => Err(SbroadError::NotFound( Entity::Column, - format!("with name {column}").into(), + format_smolstr!("with name {column}"), )), } } @@ -893,13 +893,13 @@ impl ColumnPositionMap { // // Even given `scan` we can't identify which of these two columns do we need to // refer to. - return Err(SbroadError::DuplicatedValue( - format!("column name {column} is ambiguous").into(), - )); + return Err(SbroadError::DuplicatedValue(format_smolstr!( + "column name {column} is ambiguous" + ))); } Err(SbroadError::NotFound( Entity::Column, - format!("with name {column} and scan {scan:?}").into(), + format_smolstr!("with name {column} and scan {scan:?}"), )) } @@ -920,9 +920,9 @@ impl ColumnPositionMap { if let Positions::Single(pos) = positions { res.push(*pos); } else { - return Err(SbroadError::DuplicatedValue( - format!("column name for {target_scan_name} scan name is ambiguous").into(), - )); + return Err(SbroadError::DuplicatedValue(format_smolstr!( + "column name for {target_scan_name} scan name is ambiguous" + ))); } } @@ -1193,7 +1193,7 @@ impl Plan { let mut result_row_list: Vec<usize> = Vec::with_capacity(filtered_children_row_list.len()); for (pos, alias_node_id, new_targets) in filtered_children_row_list { let alias_expr = self.get_expression_node(alias_node_id)?; - let alias_name = String::from(alias_expr.get_alias_name()?); + let alias_name = SmolStr::from(alias_expr.get_alias_name()?); let col_type = alias_expr.calculate_type(self)?; let r_id = self.nodes.add_ref(None, Some(new_targets), pos, col_type); @@ -1353,9 +1353,9 @@ impl Plan { parent: Option<usize>, ) -> Result<usize, SbroadError> { let sq_id = *children.get(target).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid target index: {target} (children: {children:?})",).into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid target index: {target} (children: {children:?})", + )) })?; let sq_rel = self.get_relation_node(sq_id)?; let sq_output_id = sq_rel.output(); @@ -1447,7 +1447,7 @@ impl Plan { let Some(referred_rel_id) = parent else { return Err(SbroadError::NotFound( Entity::Node, - format!("that is Reference ({ref_id}) parent").into(), + format_smolstr!("that is Reference ({ref_id}) parent"), )); }; let rel = self.get_relation_node(*referred_rel_id)?; @@ -1473,9 +1473,9 @@ impl Plan { if let Relational::Motion { .. } = rel { return Ok(referred_rel_id); } - return Err(SbroadError::UnexpectedNumberOfValues( - format!("Relational node {rel:?} has no children").into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Relational node {rel:?} has no children" + ))); } _ => { return Err(SbroadError::UnexpectedNumberOfValues( @@ -1534,7 +1534,7 @@ impl Plan { let referred_rel_id = parent.ok_or_else(|| { SbroadError::NotFound( Entity::Node, - format!("that is Reference ({id}) parent").into(), + format_smolstr!("that is Reference ({id}) parent"), ) })?; let rel = self.get_relation_node(referred_rel_id)?; @@ -1637,7 +1637,7 @@ impl Plan { let node = self.get_expression_node(row_id)?; if let Expression::Row { list, .. } = node { let const_node_id = list.get(child_num).ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("{child_num}").into()) + SbroadError::NotFound(Entity::Node, format_smolstr!("{child_num}")) })?; let v = self.get_expression_node(*const_node_id)?.as_const_value()?; diff --git a/sbroad-core/src/ir/expression/cast.rs b/sbroad-core/src/ir/expression/cast.rs index 2a6dcf9cd..94e6a40de 100644 --- a/sbroad-core/src/ir/expression/cast.rs +++ b/sbroad-core/src/ir/expression/cast.rs @@ -6,7 +6,7 @@ use crate::ir::expression::Expression; use crate::ir::relation::Type as RelationType; use crate::ir::{Node, Plan}; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)] pub enum Type { @@ -46,7 +46,7 @@ impl TryFrom<&Rule> for Type { Rule::TypeUnsigned => Ok(Type::Unsigned), _ => Err(SbroadError::Unsupported( Entity::Type, - Some(format!("{ast_type:?}").into()), + Some(format_smolstr!("{ast_type:?}")), )), } } @@ -91,7 +91,7 @@ impl From<&Type> for SmolStr { Type::Text => "text".to_smolstr(), Type::Uuid => "uuid".to_smolstr(), Type::Unsigned => "unsigned".to_smolstr(), - Type::Varchar(length) => format!("varchar({length})").to_smolstr(), + Type::Varchar(length) => format_smolstr!("varchar({length})"), } } } diff --git a/sbroad-core/src/ir/expression/types.rs b/sbroad-core/src/ir/expression/types.rs index 2bd4bde3a..23669fbbb 100644 --- a/sbroad-core/src/ir/expression/types.rs +++ b/sbroad-core/src/ir/expression/types.rs @@ -1,4 +1,4 @@ -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use crate::{ errors::{Entity, SbroadError}, @@ -11,7 +11,9 @@ impl Plan { Node::Expression(expr) => expr.calculate_type(self), Node::Relational(relational) => Err(SbroadError::Invalid( Entity::Node, - Some(format!("relational node {relational:?} has no type").into()), + Some(format_smolstr!( + "relational node {relational:?} has no type" + )), )), // Parameter nodes must recalculate their type during // binding (see `bind_params` function). @@ -60,8 +62,8 @@ impl Expression { (Type::Unsigned, Type::Unsigned) => Ok(Type::Unsigned), _ => Err(SbroadError::Invalid( Entity::Expression, - Some(format!("types {left_type} and {right_type} are not supported for arithmetic expression ({:?} {op:?} {:?})", - plan.get_node(*left)?, plan.get_node(*right)?).into()), + Some(format_smolstr!("types {left_type} and {right_type} are not supported for arithmetic expression ({:?} {op:?} {:?})", + plan.get_node(*left)?, plan.get_node(*right)?)), )), } } @@ -126,12 +128,9 @@ impl Expression { let target_rel_id = *target_children.get(*target).ok_or_else(|| { SbroadError::Invalid( Entity::Expression, - Some( - format!( - "reference expression has no target relation at position {target}" - ) - .into(), - ), + Some(format_smolstr!( + "reference expression has no target relation at position {target}" + )), ) })?; let target_rel = plan.get_relation_node(target_rel_id)?; @@ -139,12 +138,9 @@ impl Expression { let column_id = *columns.get(*position).ok_or_else(|| { SbroadError::Invalid( Entity::Expression, - Some( - format!( - "reference expression has no target column at position {position}" - ) - .into(), - ), + Some(format_smolstr!( + "reference expression has no target column at position {position}" + )), ) })?; let col_expr = plan.get_expression_node(column_id)?; diff --git a/sbroad-core/src/ir/function.rs b/sbroad-core/src/ir/function.rs index f0caa4677..289867c78 100644 --- a/sbroad-core/src/ir/function.rs +++ b/sbroad-core/src/ir/function.rs @@ -4,7 +4,7 @@ use crate::ir::expression::Expression; use crate::ir::relation::Type; use crate::ir::{Node, Plan}; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use super::expression::FunctionFeature; @@ -61,7 +61,7 @@ impl Plan { if !function.is_stable() { return Err(SbroadError::Invalid( Entity::SQLFunction, - Some(format!("function {} is not stable", function.name).into()), + Some(format_smolstr!("function {} is not stable", function.name)), )); } let func_expr = Expression::StableFunction { @@ -90,17 +90,17 @@ impl Plan { if children.len() > 2 || children.is_empty() { return Err(SbroadError::Invalid( Entity::Query, - Some(format!( + Some(format_smolstr!( "GROUP_CONCAT aggregate function can have one or two arguments at most. Got: {} arguments", children.len() - ).into()), + )), )); } if is_distinct && children.len() == 2 { return Err(SbroadError::Invalid( Entity::Query, - Some(format!( + Some(format_smolstr!( "distinct GROUP_CONCAT aggregate function has only one argument. Got: {} arguments", children.len() - ).into()), + )), )); } } @@ -108,7 +108,9 @@ impl Plan { if children.len() != 1 { return Err(SbroadError::Invalid( Entity::Query, - Some(format!("Expected one argument for aggregate: {function}.").into()), + Some(format_smolstr!( + "Expected one argument for aggregate: {function}." + )), )); } } diff --git a/sbroad-core/src/ir/operator.rs b/sbroad-core/src/ir/operator.rs index bef2d1409..5aadde4f5 100644 --- a/sbroad-core/src/ir/operator.rs +++ b/sbroad-core/src/ir/operator.rs @@ -7,7 +7,7 @@ use ahash::RandomState; use crate::collection; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; @@ -155,9 +155,9 @@ impl Unary { "exists" => Ok(Unary::Exists), _ => Err(SbroadError::Invalid( Entity::Operator, - Some( - format!("expected `is null` or `is not null`, got unary operator `{s}`").into(), - ), + Some(format_smolstr!( + "expected `is null` or `is not null`, got unary operator `{s}`" + )), )), } } @@ -712,10 +712,9 @@ impl Relational { let col_id = *list.get(output_alias_position).ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!( + format_smolstr!( "at position {output_alias_position} of Row, {self:?}, {output_row:?}" - ) - .into(), + ), ) })?; let col_node = plan.get_expression_node(col_id)?; @@ -725,9 +724,9 @@ impl Relational { let rel_id = *plan.get_relational_from_reference_node(*child)?; let rel_node = plan.get_relation_node(rel_id)?; if rel_node == self { - return Err(SbroadError::DuplicatedValue(format!( + return Err(SbroadError::DuplicatedValue(format_smolstr!( "Reference to the same node {rel_node:?} at position {output_alias_position}" - ).into())); + ))); } return rel_node.scan_name(plan, *pos); } @@ -830,9 +829,9 @@ impl Plan { let left_row_len = child_row_len(left, self)?; let right_row_len = child_row_len(right, self)?; if left_row_len != right_row_len { - return Err(SbroadError::UnexpectedNumberOfValues(format!( + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( "children tuples have mismatching amount of columns in except node: left {left_row_len}, right {right_row_len}" - ).into())); + ))); } let output = self.add_row_for_union_except(left, right)?; @@ -919,13 +918,19 @@ impl Plan { let col: &Column = table.columns.get(col_pos).ok_or_else(|| { SbroadError::Invalid( Entity::Table, - Some(format!("expected to have at least {} columns", col_pos + 1).into()), + Some(format_smolstr!( + "expected to have at least {} columns", + col_pos + 1 + )), ) })?; let output_pos = *table_position_map.get(&col_pos).ok_or_else(|| { SbroadError::Invalid( Entity::Plan, - Some(format!("Expected {} column in update child output", &col.name).into()), + Some(format_smolstr!( + "Expected {} column in update child output", + &col.name + )), ) })?; let col_type = col.r#type.clone(); @@ -1003,9 +1008,9 @@ impl Plan { for i in 0..shard_key_len { let table = self.get_relation_or_error(relation)?; let col_pos = *table.get_sk()?.get(i).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid shard col position {i}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid shard col position {i}" + )) })?; let shard_col_expr_id = create_ref_from_column(self, relation, &child_map, col_pos)?; @@ -1116,7 +1121,7 @@ impl Plan { let rel = self.relations.get(relation).ok_or_else(|| { SbroadError::NotFound( Entity::Table, - format!("{relation} among plan relations").into(), + format_smolstr!("{relation} among plan relations"), ) })?; let columns: Vec<usize> = if columns.is_empty() { @@ -1140,7 +1145,7 @@ impl Plan { return Err(SbroadError::FailedTo( Action::Insert, Some(Entity::Column), - format!("system column {name} cannot be inserted").into(), + format_smolstr!("system column {name} cannot be inserted"), )) } None => { @@ -1161,15 +1166,12 @@ impl Plan { )); }; if child_output_list_len != columns.len() { - return Err(SbroadError::UnexpectedNumberOfValues( - format!( - "invalid number of values: {}. Table {} expects {} column(s).", - child_output_list_len, - relation, - columns.len() - ) - .into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid number of values: {}. Table {} expects {} column(s).", + child_output_list_len, + relation, + columns.len() + ))); } let mut refs: Vec<usize> = Vec::with_capacity(rel.columns.len()); @@ -1223,7 +1225,7 @@ impl Plan { } Err(SbroadError::NotFound( Entity::Table, - format!("{table} among the plan relations").into(), + format_smolstr!("{table} among the plan relations"), )) } @@ -1372,10 +1374,9 @@ impl Plan { MotionPolicy::None => { return Err(SbroadError::Invalid( Entity::Motion, - Some( - format!("add_motion: got MotionPolicy::None for child_id: {child_id}") - .into(), - ), + Some(format_smolstr!( + "add_motion: got MotionPolicy::None for child_id: {child_id}" + )), )) } MotionPolicy::Segment(key) | MotionPolicy::LocalSegment(key) => { @@ -1581,9 +1582,9 @@ impl Plan { let left_row_len = child_row_len(left, self)?; let right_row_len = child_row_len(right, self)?; if left_row_len != right_row_len { - return Err(SbroadError::UnexpectedNumberOfValues(format!( + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( "children tuples have mismatching amount of columns in union all node: left {left_row_len}, right {right_row_len}" - ).into())); + ))); } let output = self.add_row_for_union_except(left, right)?; @@ -1683,9 +1684,9 @@ impl Plan { let columns = last_output.clone_row_list()?; for (pos, name) in names.iter().enumerate() { let col_id = *columns.get(pos).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("Values node has no column at position {pos}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Values node has no column at position {pos}" + )) })?; let col_expr = self.get_expression_node(col_id)?; let col_type = col_expr.calculate_type(self)?; @@ -1741,7 +1742,9 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected output of Relational node {rel_id} to be Row").into()), + Some(format_smolstr!( + "expected output of Relational node {rel_id} to be Row" + )), )) } @@ -1776,22 +1779,24 @@ impl Plan { let child_id = *children.get(child_idx).ok_or_else(|| { SbroadError::Invalid( Entity::Relational, - Some( - format!("rel node {rel:?} has no child with idx ({child_idx})").into(), - ), + Some(format_smolstr!( + "rel node {rel:?} has no child with idx ({child_idx})" + )), ) })?; Ok(child_id) } else { Err(SbroadError::Invalid( Entity::Relational, - Some(format!("rel node {rel:?} has no children. Id: ({rel_id})").into()), + Some(format_smolstr!( + "rel node {rel:?} has no children. Id: ({rel_id})" + )), )) }; } Err(SbroadError::NotFound( Entity::Relational, - format!("with id ({rel_id})").into(), + format_smolstr!("with id ({rel_id})"), )) } @@ -1809,7 +1814,9 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected Join, Having or Selection on id ({node_id})").into()), + Some(format_smolstr!( + "expected Join, Having or Selection on id ({node_id})" + )), )) } }; @@ -1850,7 +1857,7 @@ impl Plan { let Some(children) = node.mut_children() else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("node ({parent_id}) has no children").into()), + Some(format_smolstr!("node ({parent_id}) has no children")), )); }; for child_id in children { @@ -1862,7 +1869,9 @@ impl Plan { Err(SbroadError::Invalid( Entity::Node, - Some(format!("node ({parent_id}) has no child with id ({old_child_id})").into()), + Some(format_smolstr!( + "node ({parent_id}) has no child with id ({old_child_id})" + )), )) } @@ -1908,7 +1917,7 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("Expected a values row: {values_row:?}").into()), + Some(format_smolstr!("Expected a values row: {values_row:?}")), )); }; let data = self.get_expression_node(data_id)?; @@ -1917,7 +1926,7 @@ impl Plan { let output_list = output.clone_row_list()?; for (pos, alias_id) in output_list.iter().enumerate() { let new_child_id = *data_list.get(pos).ok_or_else(|| { - SbroadError::NotFound(Entity::Node, format!("at position {pos}").into()) + SbroadError::NotFound(Entity::Node, format_smolstr!("at position {pos}")) })?; let alias = self.get_mut_expression_node(*alias_id)?; if let Expression::Alias { ref mut child, .. } = alias { @@ -1925,7 +1934,7 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("expected an alias: {alias:?}").into()), + Some(format_smolstr!("expected an alias: {alias:?}")), )); } } @@ -2014,7 +2023,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected Motion, got: {node:?}").into()), + Some(format_smolstr!("expected Motion, got: {node:?}")), )) } } diff --git a/sbroad-core/src/ir/relation.rs b/sbroad-core/src/ir/relation.rs index b8d960243..b92cd3f7a 100644 --- a/sbroad-core/src/ir/relation.rs +++ b/sbroad-core/src/ir/relation.rs @@ -8,7 +8,7 @@ //! * Relation, representing named tables (`Relations` as a map of { name -> table }) use ahash::AHashMap; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::fmt::{self, Formatter}; @@ -170,7 +170,7 @@ impl Type { "any" => Ok(Type::Any), v => Err(SbroadError::Invalid( Entity::Type, - Some(format!("Unexpected type {v} met during ").into()), + Some(format_smolstr!("Unexpected type {v} met during ")), )), } } @@ -450,7 +450,7 @@ impl TryFrom<&str> for SpaceEngine { _ => Err(SbroadError::FailedTo( Action::Deserialize, Some(Entity::SpaceEngine), - format!("unsupported space engine type: {value}").into(), + format_smolstr!("unsupported space engine type: {value}"), )), } } @@ -470,13 +470,13 @@ impl<'column> ColumnPositions<'column> { for (pos, col) in columns.iter().enumerate() { let name = col.name.as_str(); if let Some(old_pos) = map.insert(name, pos) { - return Err(SbroadError::DuplicatedValue( - format!( - r#"Table "{}" has a duplicating column "{}" at positions {} and {}"#, - table, name, old_pos, pos, - ) - .into(), - )); + return Err(SbroadError::DuplicatedValue(format_smolstr!( + r#"Table "{}" has a duplicating column "{}" at positions {} and {}"#, + table, + name, + old_pos, + pos, + ))); } } map.shrink_to_fit(); @@ -532,7 +532,7 @@ fn table_new_impl<'column>( SbroadError::FailedTo( Action::Create, Some(Entity::Column), - format!("column {name} not found at position {pos}").into(), + format_smolstr!("column {name} not found at position {pos}"), ) })?; Ok(pos) @@ -636,7 +636,7 @@ impl Table { return Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Table), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), )) } }; @@ -661,7 +661,10 @@ impl Table { if !in_range { return Err(SbroadError::Invalid( Entity::Value, - Some(format!("key positions must be less than {}", cols.len()).into()), + Some(format_smolstr!( + "key positions must be less than {}", + cols.len() + )), )); } } @@ -690,9 +693,10 @@ impl Table { Ordering::Greater => Err(SbroadError::UnexpectedNumberOfValues( "Table has more than one bucket_id column".into(), )), - Ordering::Less => Err(SbroadError::UnexpectedNumberOfValues( - format!("Table {} has no bucket_id columns", self.name).into(), - )), + Ordering::Less => Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Table {} has no bucket_id columns", + self.name + ))), } } @@ -723,11 +727,11 @@ impl Table { .ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!( + format_smolstr!( "(distribution column) at position {} for Table {}", - *pos, self.name - ) - .into(), + *pos, + self.name + ), ) })? .name @@ -749,7 +753,10 @@ impl Table { } => Ok(&shard_key.positions), TableKind::GlobalSpace | TableKind::SystemSpace => Err(SbroadError::Invalid( Entity::Table, - Some(format!("expected sharded table. Name: {}", self.name).into()), + Some(format_smolstr!( + "expected sharded table. Name: {}", + self.name + )), )), } } @@ -765,17 +772,17 @@ impl Table { let column = self.columns.get(*pos).ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!( + format_smolstr!( "(distribution column) at position {} for Table {}", - *pos, self.name - ) - .into(), + *pos, + self.name + ), ) })?; let field_no = u32::try_from(*pos).map_err(|e| { SbroadError::Invalid( Entity::Table, - Some(format!("sharding key (position {pos}) error: {e}").into()), + Some(format_smolstr!("sharding key (position {pos}) error: {e}")), ) })?; let part = KeyDefPart { @@ -842,16 +849,19 @@ pub fn space_pk_columns( let tuple = index .get(&[space.id(), 0]) .map_err(|e| { - SbroadError::FailedTo(Action::Get, Some(Entity::Index), format!("{e}").into()) + SbroadError::FailedTo(Action::Get, Some(Entity::Index), format_smolstr!("{e}")) })? .ok_or_else(|| { - SbroadError::NotFound(Entity::PrimaryKey, format!("for space {space_name}").into()) + SbroadError::NotFound( + Entity::PrimaryKey, + format_smolstr!("for space {space_name}"), + ) })?; let pk_meta = tuple.decode::<IndexMetadata>().map_err(|e| { SbroadError::FailedTo( Action::Decode, Some(Entity::PrimaryKey), - format!("{e}").into(), + format_smolstr!("{e}"), ) })?; let mut primary_key = Vec::with_capacity(pk_meta.parts.len()); @@ -861,7 +871,9 @@ pub fn space_pk_columns( } else { return Err(SbroadError::Invalid( Entity::PrimaryKey, - Some(format!("part of {space_name} has unexpected format: {part:?}").into()), + Some(format_smolstr!( + "part of {space_name} has unexpected format: {part:?}" + )), )); }; let col = space_columns @@ -869,10 +881,9 @@ pub fn space_pk_columns( .ok_or_else(|| { SbroadError::Invalid( Entity::PrimaryKey, - Some( - format!("{space_name} part referes to unknown column position: {col_pos}") - .into(), - ), + Some(format_smolstr!( + "{space_name} part referes to unknown column position: {col_pos}" + )), ) })? .name diff --git a/sbroad-core/src/ir/relation/tests.rs b/sbroad-core/src/ir/relation/tests.rs index 3881c8cc3..7873286bf 100644 --- a/sbroad-core/src/ir/relation/tests.rs +++ b/sbroad-core/src/ir/relation/tests.rs @@ -65,9 +65,9 @@ fn table_seg_duplicate_columns() { SpaceEngine::Memtx, ) .unwrap_err(), - SbroadError::DuplicatedValue( - format!(r#"Table "t" has a duplicating column "a" at positions 0 and 3"#,).into() - ) + SbroadError::DuplicatedValue(format_smolstr!( + r#"Table "t" has a duplicating column "a" at positions 0 and 3"#, + )) ); } @@ -87,9 +87,10 @@ fn table_seg_dno_bucket_id_column() { .unwrap(); assert_eq!( - SbroadError::UnexpectedNumberOfValues( - format!("Table {} has no bucket_id columns", "t").into() - ), + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Table {} has no bucket_id columns", + "t" + )), t1.get_bucket_id_position().unwrap_err() ); diff --git a/sbroad-core/src/ir/transformation.rs b/sbroad-core/src/ir/transformation.rs index 7821f7108..10c563a74 100644 --- a/sbroad-core/src/ir/transformation.rs +++ b/sbroad-core/src/ir/transformation.rs @@ -10,6 +10,8 @@ pub mod not_push_down; pub mod redistribution; pub mod split_columns; +use smol_str::format_smolstr; + use super::tree::traversal::{PostOrder, PostOrderWithFilter, EXPR_CAPACITY}; use crate::errors::{Entity, SbroadError}; use crate::ir::expression::Expression; @@ -42,25 +44,19 @@ impl Plan { if !self.is_trivalent(left_expr_id)? { return Err(SbroadError::Invalid( Entity::Expression, - Some( - format!( - "Left expression is not a boolean expression or NULL: {:?}", - self.get_expression_node(left_expr_id)? - ) - .into(), - ), + Some(format_smolstr!( + "Left expression is not a boolean expression or NULL: {:?}", + self.get_expression_node(left_expr_id)? + )), )); } if !self.is_trivalent(right_expr_id)? { return Err(SbroadError::Invalid( Entity::Expression, - Some( - format!( - "Right expression is not a boolean expression or NULL: {:?}", - self.get_expression_node(right_expr_id)? - ) - .into(), - ), + Some(format_smolstr!( + "Right expression is not a boolean expression or NULL: {:?}", + self.get_expression_node(right_expr_id)? + )), )); } self.add_cond(left_expr_id, Bool::And, right_expr_id) @@ -78,25 +74,19 @@ impl Plan { if !self.is_trivalent(left_expr_id)? { return Err(SbroadError::Invalid( Entity::Expression, - Some( - format!( - "left expression is not a boolean expression or NULL: {:?}", - self.get_expression_node(left_expr_id)? - ) - .into(), - ), + Some(format_smolstr!( + "left expression is not a boolean expression or NULL: {:?}", + self.get_expression_node(left_expr_id)? + )), )); } if !self.is_trivalent(right_expr_id)? { return Err(SbroadError::Invalid( Entity::Expression, - Some( - format!( - "right expression is not a boolean expression or NULL: {:?}", - self.get_expression_node(right_expr_id)? - ) - .into(), - ), + Some(format_smolstr!( + "right expression is not a boolean expression or NULL: {:?}", + self.get_expression_node(right_expr_id)? + )), )); } self.add_cond(left_expr_id, Bool::Or, right_expr_id) diff --git a/sbroad-core/src/ir/transformation/bool_in.rs b/sbroad-core/src/ir/transformation/bool_in.rs index 1104f59f0..191cfbb7d 100644 --- a/sbroad-core/src/ir/transformation/bool_in.rs +++ b/sbroad-core/src/ir/transformation/bool_in.rs @@ -17,6 +17,7 @@ use crate::ir::transformation::OldNewTopIdPair; use crate::ir::Plan; use crate::otm::child_span; use sbroad_proc::otm_child_span; +use smol_str::format_smolstr; /// Replace IN operator with the chain of the OR-ed equalities in the expression tree. fn call_expr_tree_replace_in( @@ -44,7 +45,9 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("Node is not a boolean IN expression: {top_expr:?}").into()), + Some(format_smolstr!( + "Node is not a boolean IN expression: {top_expr:?}" + )), )); } }; diff --git a/sbroad-core/src/ir/transformation/merge_tuples.rs b/sbroad-core/src/ir/transformation/merge_tuples.rs index 7b3463dce..bb2fb2f83 100644 --- a/sbroad-core/src/ir/transformation/merge_tuples.rs +++ b/sbroad-core/src/ir/transformation/merge_tuples.rs @@ -20,7 +20,7 @@ use crate::ir::tree::traversal::EXPR_CAPACITY; use crate::ir::Plan; use crate::otm::child_span; use sbroad_proc::otm_child_span; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use std::collections::{hash_map::Entry, HashMap, HashSet}; fn call_expr_tree_merge_tuples( @@ -74,7 +74,9 @@ impl Chain { // We don't expect nested AND/OR expressions in DNF. return Err(SbroadError::Unsupported( Entity::Operator, - Some(format!("AND/OR expressions are not supported: {bool_expr:?}").into()), + Some(format_smolstr!( + "AND/OR expressions are not supported: {bool_expr:?}" + )), )); } @@ -317,7 +319,7 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("expected alias expression: {expr_mut:?}").into()), + Some(format_smolstr!("expected alias expression: {expr_mut:?}")), )); } } @@ -343,9 +345,9 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some( - format!("expected boolean expression: {expr_mut:?}").into(), - ), + Some(format_smolstr!( + "expected boolean expression: {expr_mut:?}" + )), )); } } @@ -372,10 +374,9 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some( - format!("expected Arithmetic expression: {expr_mut:?}") - .into(), - ), + Some(format_smolstr!( + "expected Arithmetic expression: {expr_mut:?}" + )), )); } } @@ -392,14 +393,14 @@ impl Plan { if let Some(child_id) = list.get_mut(pos) { *child_id = new_child_id; } else { - return Err(SbroadError::UnexpectedNumberOfValues(format!( + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( "expected a column at position {pos} in the row {expr_mut:?}" - ).into())); + ))); } } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("expected row expression: {expr_mut:?}").into()), + Some(format_smolstr!("expected row expression: {expr_mut:?}")), )); } } diff --git a/sbroad-core/src/ir/transformation/not_push_down.rs b/sbroad-core/src/ir/transformation/not_push_down.rs index 1c9604a2e..920474232 100644 --- a/sbroad-core/src/ir/transformation/not_push_down.rs +++ b/sbroad-core/src/ir/transformation/not_push_down.rs @@ -13,7 +13,7 @@ use crate::ir::value::Value; use crate::ir::{Node, Plan}; use crate::otm::child_span; use sbroad_proc::otm_child_span; -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use std::collections::HashMap; /// Enum representing status of Not push down traversal. @@ -205,9 +205,9 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!("Unexpected constant node under Not: {expr:?}").into(), - ), + Some(format_smolstr!( + "Unexpected constant node under Not: {expr:?}" + )), )); } } diff --git a/sbroad-core/src/ir/transformation/redistribution.rs b/sbroad-core/src/ir/transformation/redistribution.rs index 8e2e70849..cbaa2647a 100644 --- a/sbroad-core/src/ir/transformation/redistribution.rs +++ b/sbroad-core/src/ir/transformation/redistribution.rs @@ -2,7 +2,7 @@ use ahash::{AHashMap, AHashSet, RandomState}; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use std::cmp::Ordering; use std::collections::{hash_map::Entry, HashMap, HashSet}; @@ -384,9 +384,9 @@ impl Plan { match sq_set.len().cmp(&1) { Ordering::Equal | Ordering::Greater => sq_set.iter().next().map_or_else( || { - Err(SbroadError::UnexpectedNumberOfValues(format!( + Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( "Failed to get the first sub-query node from the list of relational nodes: {rel_nodes:?}." - ).into())) + ))) }, |sq_id| Ok(Some(*sq_id)), ), @@ -478,21 +478,17 @@ impl Plan { let targets = targets.as_ref().ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some( - format!("ref ({ref_id}) in join condition with no targets: {node:?}") - .into(), - ), + Some(format_smolstr!( + "ref ({ref_id}) in join condition with no targets: {node:?}" + )), ) })?; let child_idx = targets.first().ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some( - format!( - "ref ({ref_id}) in join condition with empty targets: {node:?}" - ) - .into(), - ), + Some(format_smolstr!( + "ref ({ref_id}) in join condition with empty targets: {node:?}" + )), ) })?; let child_id = self.get_relational_child(rel_id, *child_idx)?; @@ -713,7 +709,9 @@ impl Plan { let Expression::Unary { child, op } = unary_op_expr else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("Expected Unary expression, got {unary_op_expr:?}").into()), + Some(format_smolstr!( + "Expected Unary expression, got {unary_op_expr:?}" + )), )); }; @@ -747,7 +745,7 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("Expected Not operator, got {not_node:?}").into()), + Some(format_smolstr!("Expected Not operator, got {not_node:?}")), )); } } @@ -822,7 +820,7 @@ impl Plan { let column_id = *row_map.get(pos).ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!("{pos} in row map {row_map:?}").into(), + format_smolstr!("{pos} in row map {row_map:?}"), ) })?; if let Expression::Reference { targets, .. } = self.get_expression_node(column_id)? { @@ -831,7 +829,7 @@ impl Plan { let child_id = *join_children.get(*target).ok_or_else(|| { SbroadError::NotFound( Entity::Target, - format!("{target} in join children {join_children:?}").into(), + format_smolstr!("{target} in join children {join_children:?}"), ) })?; children_set.insert(child_id); @@ -949,7 +947,7 @@ impl Plan { let column_id = *condition_row_map.get(pos).ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!("{pos} in row map {condition_row_map:?}").into(), + format_smolstr!("{pos} in row map {condition_row_map:?}"), ) })?; if let Expression::Reference { @@ -1574,20 +1572,20 @@ impl Plan { let (outer_id, inner_id) = if let Some(children) = self.get_relational_children(join_id)? { ( *children.first().ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("join {join_id} has no children!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "join {join_id} has no children!" + )) })?, *children.get(1).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("join {join_id} has one child!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "join {join_id} has one child!" + )) })?, ) } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("join {join_id} has no children!").into()), + Some(format_smolstr!("join {join_id} has no children!")), )); }; let outer_dist = self.get_distribution(self.get_relational_output(outer_id)?)?; @@ -1605,9 +1603,9 @@ impl Plan { let subqueries = self .get_relational_children(join_id)? .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("join {join_id} has no children!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "join {join_id} has no children!" + )) })? .split_at(2) .1; @@ -1687,7 +1685,9 @@ impl Plan { ) { return Err(SbroadError::Invalid( Entity::Update, - Some(format!("expected Projection under Update ({update_id})").into()), + Some(format_smolstr!( + "expected Projection under Update ({update_id})" + )), )); } match kind { @@ -1718,13 +1718,10 @@ impl Plan { if !keys.iter().any(|key| *key == expected_key) { return Err(SbroadError::Invalid( Entity::Update, - Some( - format!( + Some(format_smolstr!( "expected sharded update child to be \ always distributed on old sharding key. Child dist: {child_dist:?}" - ) - .into(), - ), + )), )); } } else { @@ -1768,9 +1765,9 @@ impl Plan { .ok_or_else(|| { SbroadError::Invalid( Entity::Table, - Some( - format!("invalid shar key position: {pos}").into(), - ), + Some(format_smolstr!( + "invalid shar key position: {pos}" + )), ) })? .name; @@ -1782,25 +1779,19 @@ impl Plan { if !keys.iter().any(|key| key.positions == expected_positions) { return Err(SbroadError::Invalid( Entity::Update, - Some( - format!( - "for local update expected children below \ + Some(format_smolstr!( + "for local update expected children below \ Projection to have update table dist. Got: {pr_child_dist:?}" - ) - .into(), - ), + )), )); } } else { return Err(SbroadError::Invalid( Entity::Update, - Some( - format!( - "expected child below projection to have Segment dist,\ + Some(format_smolstr!( + "expected child below projection to have Segment dist,\ got: {pr_child_dist:?}" - ) - .into(), - ), + )), )); } @@ -1811,7 +1802,7 @@ impl Plan { } else { Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected Update node on id {update_id}").into()), + Some(format_smolstr!("expected Update node on id {update_id}")), )) } } @@ -1822,9 +1813,10 @@ impl Plan { let space = self.dml_node_table(rel_id)?; let pk_len = space.primary_key.positions.len(); if pk_len == 0 { - return Err(SbroadError::UnexpectedNumberOfValues( - format!("empty primary key for space {}", space.name()).into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "empty primary key for space {}", + space.name() + ))); } // We expect that the columns in the child projection of the DELETE operator let pk_pos: Vec<usize> = (0..pk_len).collect(); @@ -1968,13 +1960,11 @@ impl Plan { let key = keys.iter().next().ok_or_else(|| { SbroadError::Invalid( Entity::Distribution, - Some( - format!( - "{} {} {right_id}", - "Segment distribution with no keys.", "Except right child:" - ) - .into(), - ), + Some(format_smolstr!( + "{} {} {right_id}", + "Segment distribution with no keys.", + "Except right child:" + )), ) })?; (MotionPolicy::Segment(key.into()), MotionPolicy::None) @@ -2079,14 +2069,11 @@ impl Plan { let left_output_row = self.get_expression_node(left_output_id)?.get_row_list()?; let right_output_row = self.get_expression_node(right_output_id)?.get_row_list()?; if left_output_row.len() != right_output_row.len() { - return Err(SbroadError::UnexpectedNumberOfValues( - format!( - "Except node children have different row lengths: left {}, right {}", - left_output_row.len(), - right_output_row.len() - ) - .into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Except node children have different row lengths: left {}, right {}", + left_output_row.len(), + right_output_row.len() + ))); } } diff --git a/sbroad-core/src/ir/transformation/redistribution/dml.rs b/sbroad-core/src/ir/transformation/redistribution/dml.rs index 82b0840f5..29afb5da0 100644 --- a/sbroad-core/src/ir/transformation/redistribution/dml.rs +++ b/sbroad-core/src/ir/transformation/redistribution/dml.rs @@ -4,7 +4,7 @@ use crate::ir::relation::{Column, Table}; use crate::ir::transformation::redistribution::MotionOpcode; use crate::ir::Plan; use ahash::AHashMap; -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use super::{MotionKey, Target}; @@ -30,7 +30,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("dml node with id {dml_node_id}").into()), + Some(format_smolstr!("dml node with id {dml_node_id}")), )) } @@ -51,7 +51,9 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("INSERT with id {insert_id} (conflict strategy))").into()), + Some(format_smolstr!( + "INSERT with id {insert_id} (conflict strategy))" + )), )) } @@ -73,16 +75,13 @@ impl Plan { if columns.len() != child_row.len() { return Err(SbroadError::Invalid( Entity::Node, - Some( - format!( - "INSERT with id {} has {} columns, but the child node with id {} has {}", - insert_id, - columns.len(), - child_id, - child_row.len() - ) - .into(), - ), + Some(format_smolstr!( + "INSERT with id {} has {} columns, but the child node with id {} has {}", + insert_id, + columns.len(), + child_id, + child_row.len() + )), )); } @@ -99,7 +98,7 @@ impl Plan { table.columns.get(*pos).ok_or_else(|| { SbroadError::NotFound( Entity::Column, - format!("in the table {table:?} at position {pos}").into(), + format_smolstr!("in the table {table:?} at position {pos}"), ) })?; // We need a default value for the key column. @@ -122,7 +121,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected insert node on id {insert_id}").into()), + Some(format_smolstr!("expected insert node on id {insert_id}")), )) } @@ -140,7 +139,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("DML node with id {node_id}").into()), + Some(format_smolstr!("DML node with id {node_id}")), )) } @@ -167,7 +166,7 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected sharded Update, got: {node:?}").into()), + Some(format_smolstr!("expected sharded Update, got: {node:?}")), )); } Ok(()) @@ -194,7 +193,9 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected sharded Update with delete len, got: {node:?}").into()), + Some(format_smolstr!( + "expected sharded Update with delete len, got: {node:?}" + )), )) } @@ -213,13 +214,13 @@ impl Plan { if let Some(op) = program.0.get(opcode_idx) { return Ok(op); } - return Err(SbroadError::UnexpectedNumberOfValues( - format!("Invalid motion opcode index: {opcode_idx}").into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Invalid motion opcode index: {opcode_idx}" + ))); } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected Motion, got: {node:?}").into()), + Some(format_smolstr!("expected Motion, got: {node:?}")), )) } @@ -235,7 +236,7 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Node, - Some(format!("expected Update node, got: {node:?}").into()), + Some(format_smolstr!("expected Update node, got: {node:?}")), )) } } diff --git a/sbroad-core/src/ir/transformation/redistribution/groupby.rs b/sbroad-core/src/ir/transformation/redistribution/groupby.rs index cfd129713..a6718934f 100644 --- a/sbroad-core/src/ir/transformation/redistribution/groupby.rs +++ b/sbroad-core/src/ir/transformation/redistribution/groupby.rs @@ -1,4 +1,4 @@ -use smol_str::ToSmolStr; +use smol_str::{format_smolstr, ToSmolStr}; use crate::errors::{Entity, SbroadError}; use crate::ir::aggregates::{generate_local_alias_for_aggr, AggregateKind, SimpleAggregate}; @@ -320,7 +320,9 @@ impl<'plan> ExpressionMapper<'plan> { }; return Err(SbroadError::Invalid( Entity::Query, - Some(format!("column {column_name} is not found in grouping expressions!").into()), + Some(format_smolstr!( + "column {column_name} is not found in grouping expressions!" + )), )); } for child in self.plan.nodes.aggregate_iter(current, false) { @@ -552,7 +554,7 @@ impl Plan { if Expression::is_aggregate_name(name) { return Err(SbroadError::Invalid( Entity::Query, - Some(format!("aggregate functions are not allowed inside grouping expression. Got aggregate: {name}").into()) + Some(format_smolstr!("aggregate functions are not allowed inside grouping expression. Got aggregate: {name}")) )); } } @@ -562,7 +564,7 @@ impl Plan { if !contains_at_least_one_col { return Err(SbroadError::Invalid( Entity::Query, - Some(format!("grouping expression must contain at least one column. Invalid expression number: {pos}").into()) + Some(format_smolstr!("grouping expression must contain at least one column. Invalid expression number: {pos}")) )); } } @@ -625,7 +627,9 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("unexpected relational node ({node_id}): {node:?}").into()), + Some(format_smolstr!( + "unexpected relational node ({node_id}): {node:?}" + )), )) } } @@ -674,15 +678,15 @@ impl Plan { let c = *self .get_relational_children(rel_id)? .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("expected relation node ({rel_id}) to have children!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "expected relation node ({rel_id}) to have children!" + )) })? .first() .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("expected relation node ({rel_id}) to have children!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "expected relation node ({rel_id}) to have children!" + )) })?; Ok(c) }; @@ -699,7 +703,10 @@ impl Plan { } Err(SbroadError::Invalid( Entity::Plan, - Some(format!("too many nodes ({}) in Reduce stage", finals.len()).into()), + Some(format_smolstr!( + "too many nodes ({}) in Reduce stage", + finals.len() + )), )) } @@ -835,7 +842,7 @@ impl Plan { Err(e) => e.to_smolstr(), }; return Err(SbroadError::Invalid(Entity::Query, - Some(format!("found column reference ({alias}) outside aggregate function").into()))); + Some(format_smolstr!("found column reference ({alias}) outside aggregate function")))); } } } @@ -1070,14 +1077,14 @@ impl Plan { .expr_iter(info.aggr.fun_id, false) .collect::<Vec<usize>>(); if args.len() > 1 && !matches!(info.aggr.kind, AggregateKind::GRCONCAT) { - return Err(SbroadError::UnexpectedNumberOfValues( - format!("aggregate ({info:?}) have more than one argument").into(), - )); + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "aggregate ({info:?}) have more than one argument" + ))); } *args.first().ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("Aggregate function has no children: {info:?}").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "Aggregate function has no children: {info:?}" + )) })? }; let expr = GroupingExpression::new(argument, self); @@ -1128,13 +1135,13 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("missing position for local GroupBy column with local alias: {local_alias}").into()) + Some(format_smolstr!("missing position for local GroupBy column with local alias: {local_alias}")) )); } } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("invalid map with unique grouping expressions. Could not find grouping expression with id: {expr_id}").into()))); + Some(format_smolstr!("invalid map with unique grouping expressions. Could not find grouping expression with id: {expr_id}")))); } } let child_id = self @@ -1160,9 +1167,9 @@ impl Plan { HashSet::with_hasher(RepeatableState); for pos in 0..aggr_infos.len() { let info = aggr_infos.get(pos).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid idx of aggregate infos ({pos})").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid idx of aggregate infos ({pos})" + )) })?; if info.is_distinct { continue; @@ -1175,7 +1182,7 @@ impl Plan { } else { return Err(SbroadError::Invalid( Entity::Aggregate, - Some(format!("invalid fun_id: {}", info.aggr.fun_id).into()), + Some(format_smolstr!("invalid fun_id: {}", info.aggr.fun_id)), )); } }; @@ -1189,9 +1196,9 @@ impl Plan { if let Some(sig) = unique_local_aggregates.get(&signature) { if let Some(alias) = &sig.local_alias { let info = aggr_infos.get_mut(pos).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid idx of aggregate infos ({pos})").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid idx of aggregate infos ({pos})" + )) })?; info.aggr.lagg_alias.insert(kind, alias.clone()); } else { @@ -1202,9 +1209,9 @@ impl Plan { } } else { let info = aggr_infos.get_mut(pos).ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("invalid idx of aggregate infos ({pos})").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "invalid idx of aggregate infos ({pos})" + )) })?; let alias = Rc::new(generate_local_alias_for_aggr( &kind, @@ -1266,7 +1273,9 @@ impl Plan { let Some(local_alias) = local_aliases_map.get(expr_id) else { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("could not find local alias for GroupBy expr ({expr_id})").into()), + Some(format_smolstr!( + "could not find local alias for GroupBy expr ({expr_id})" + )), )); }; let position = child_map.get(local_alias)?; @@ -1274,12 +1283,9 @@ impl Plan { if !col_type.is_scalar() { return Err(SbroadError::Invalid( Entity::Type, - Some( - format!( + Some(format_smolstr!( "add_final_groupby: GroupBy expr ({expr_id}) is not scalar ({col_type})!" - ) - .into(), - ), + )), )); } let new_col = Expression::Reference { @@ -1349,15 +1355,15 @@ impl Plan { let child_id = *self .get_relational_children(rel_id)? .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("expected relation node ({rel_id}) to have children!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "expected relation node ({rel_id}) to have children!" + )) })? .first() .ok_or_else(|| { - SbroadError::UnexpectedNumberOfValues( - format!("expected relation node ({rel_id}) to have children!").into(), - ) + SbroadError::UnexpectedNumberOfValues(format_smolstr!( + "expected relation node ({rel_id}) to have children!" + )) })?; let alias_to_pos_map = ColumnPositionMap::new(self, child_id)?; let mut nodes = Vec::with_capacity(group.len()); @@ -1365,12 +1371,9 @@ impl Plan { let Some(local_alias) = local_aliases_map.get(&gr_expr_id) else { return Err(SbroadError::Invalid( Entity::Plan, - Some( - format!( - "failed to find local alias for groupby expression {gr_expr_id}" - ) - .into(), - ), + Some(format_smolstr!( + "failed to find local alias for groupby expression {gr_expr_id}" + )), )); }; let position = alias_to_pos_map.get(local_alias)?; @@ -1378,10 +1381,9 @@ impl Plan { if !col_type.is_scalar() { return Err(SbroadError::Invalid( Entity::Type, - Some( - format!("patch_finals: expected scalar expression, found: {col_type}") - .into(), - ), + Some(format_smolstr!( + "patch_finals: expected scalar expression, found: {col_type}" + )), )); }; let new_ref = Expression::Reference { @@ -1401,15 +1403,12 @@ impl Plan { Relational::Projection { .. } => { return Err(SbroadError::Invalid( Entity::Plan, - Some( - format!( - "{} {gr_expr_id} {} {expr_id} {}", - "invalid mapping between group by expression", - "and projection one: expression", - "has no parent", - ) - .into(), - ), + Some(format_smolstr!( + "{} {gr_expr_id} {} {expr_id} {}", + "invalid mapping between group by expression", + "and projection one: expression", + "has no parent", + )), )) } Relational::Having { filter, .. } => { @@ -1418,7 +1417,7 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("unexpected node in Reduce stage: {rel_id}").into()), + Some(format_smolstr!("unexpected node in Reduce stage: {rel_id}")), )) } } @@ -1479,7 +1478,7 @@ impl Plan { let child_id = *children.first().ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some(format!("Having ({node_id}) has no children!").into()), + Some(format_smolstr!("Having ({node_id}) has no children!")), ) })?; let output = self.add_row_for_output(child_id, &[], true)?; @@ -1489,7 +1488,7 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("Unexpected node in reduce stage: {node:?}").into()), + Some(format_smolstr!("Unexpected node in reduce stage: {node:?}")), )) } } @@ -1510,19 +1509,17 @@ impl Plan { *children.first().ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some( - format!("patch aggregates: rel node ({parent}) has no children!") - .into(), - ), + Some(format_smolstr!( + "patch aggregates: rel node ({parent}) has no children!" + )), ) })? } else { return Err(SbroadError::Invalid( Entity::Plan, - Some( - format!("patch aggregates: rel node on id: {parent} has no children!") - .into(), - ), + Some(format_smolstr!( + "patch aggregates: rel node on id: {parent} has no children!" + )), )); }; let alias_to_pos_map = ColumnPositionMap::new(self, child_id)?; @@ -1546,12 +1543,9 @@ impl Plan { let node = self.get_mut_relation_node(parent)?; return Err(SbroadError::Invalid( Entity::Aggregate, - Some( - format!( - "aggregate info for {node:?} that hat no parent! Info: {info:?}" - ) - .into(), - ), + Some(format_smolstr!( + "aggregate info for {node:?} that hat no parent! Info: {info:?}" + )), )); } } @@ -1593,18 +1587,17 @@ impl Plan { *children.first().ok_or_else(|| { SbroadError::Invalid( Entity::Node, - Some(format!("final GroupBy ({motion_parent}) has no children!").into()), + Some(format_smolstr!( + "final GroupBy ({motion_parent}) has no children!" + )), ) })? } else { return Err(SbroadError::Invalid( Entity::Plan, - Some( - format!( - "expected to have GroupBy under reduce nodes on id: {motion_parent}" - ) - .into(), - ), + Some(format_smolstr!( + "expected to have GroupBy under reduce nodes on id: {motion_parent}" + )), )); }; let mut strategy = Strategy::new(motion_parent); diff --git a/sbroad-core/src/ir/transformation/redistribution/left_join.rs b/sbroad-core/src/ir/transformation/redistribution/left_join.rs index 5888a9d9b..0e6691ba1 100644 --- a/sbroad-core/src/ir/transformation/redistribution/left_join.rs +++ b/sbroad-core/src/ir/transformation/redistribution/left_join.rs @@ -1,7 +1,7 @@ //! Left Join trasformation logic when outer child has Global distribution //! and inner child has Segment or Any distribution. -use smol_str::SmolStr; +use smol_str::{format_smolstr, SmolStr}; use crate::{ errors::{Entity, SbroadError}, @@ -42,7 +42,7 @@ impl Plan { let Some(parent_id) = self.find_parent_rel(join_id)? else { return Err(SbroadError::Invalid( Entity::Plan, - Some(format!("join ({join_id}) has no parent!").into()), + Some(format_smolstr!("join ({join_id}) has no parent!")), )); }; let projection_id = create_projection(self, join_id)?; @@ -99,7 +99,9 @@ fn collect_projection_columns( } else { return Err(SbroadError::Invalid( Entity::Node, - Some(format!("node ({join_id}) output columns is not alias").into()), + Some(format_smolstr!( + "node ({join_id}) output columns is not alias" + )), )); } } diff --git a/sbroad-core/src/ir/transformation/split_columns.rs b/sbroad-core/src/ir/transformation/split_columns.rs index e27c9bbda..4b707001c 100644 --- a/sbroad-core/src/ir/transformation/split_columns.rs +++ b/sbroad-core/src/ir/transformation/split_columns.rs @@ -19,6 +19,7 @@ use crate::ir::transformation::OldNewTopIdPair; use crate::ir::Plan; use crate::otm::child_span; use sbroad_proc::otm_child_span; +use smol_str::format_smolstr; fn call_expr_tree_split_columns( plan: &mut Plan, @@ -59,7 +60,9 @@ impl Plan { _ => { return Err(SbroadError::Invalid( Entity::Expression, - Some(format!("node is not a boolean expression: {top_expr:?}").into()), + Some(format_smolstr!( + "node is not a boolean expression: {top_expr:?}" + )), )); } }; @@ -75,9 +78,9 @@ impl Plan { ) = (left_expr, right_expr) { if left_list.len() != right_list.len() { - return Err(SbroadError::UnexpectedNumberOfValues(format!( + return Err(SbroadError::UnexpectedNumberOfValues(format_smolstr!( "left and right rows have different number of columns: {left_expr:?}, {right_expr:?}" - ).into())); + ))); } let pairs = left_list .iter() diff --git a/sbroad-core/src/ir/value.rs b/sbroad-core/src/ir/value.rs index 1456bea40..869ae1222 100644 --- a/sbroad-core/src/ir/value.rs +++ b/sbroad-core/src/ir/value.rs @@ -7,7 +7,7 @@ use std::num::NonZeroI32; use std::str::FromStr; use serde::{Deserialize, Serialize}; -use smol_str::{SmolStr, ToSmolStr}; +use smol_str::{format_smolstr, SmolStr, ToSmolStr}; use tarantool::decimal::Decimal; use tarantool::tlua::{self, LuaRead}; use tarantool::tuple::{FieldType, KeyDefPart}; @@ -29,8 +29,8 @@ impl Display for Tuple { "[{}]", self.0 .iter() - .map(ToString::to_string) - .collect::<Vec<String>>() + .map(ToSmolStr::to_smolstr) + .collect::<Vec<SmolStr>>() .join(",") ) } @@ -308,16 +308,16 @@ pub(crate) fn value_to_decimal_or_error(value: &Value) -> Result<Decimal, Sbroad } else { Err(SbroadError::Invalid( Entity::Value, - Some(format!("Can't cast {value:?} to decimal").into()), + Some(format_smolstr!("Can't cast {value:?} to decimal")), )) } } Value::Decimal(s) => Ok(*s), _ => Err(SbroadError::Invalid( Entity::Value, - Some( - format!("Only numerical values can be casted to Decimal. {value:?} was met").into(), - ), + Some(format_smolstr!( + "Only numerical values can be casted to Decimal. {value:?} was met" + )), )), } } @@ -371,7 +371,7 @@ impl Value { if other_decimal == 0 { Err(SbroadError::Invalid( Entity::Value, - Some(format!("Can not divide {self:?} by zero {other:?}").into()), + Some(format_smolstr!("Can not divide {self:?} by zero {other:?}")), )) } else { Ok(Value::from(self_decimal / other_decimal)) @@ -398,7 +398,9 @@ impl Value { let (Value::String(s), Value::String(o)) = (self, other) else { return Err(SbroadError::Invalid( Entity::Value, - Some(format!("{self:?} and {other:?} must be strings to be concatenated").into()), + Some(format_smolstr!( + "{self:?} and {other:?} must be strings to be concatenated" + )), )); }; @@ -414,12 +416,9 @@ impl Value { let (Value::Boolean(s), Value::Boolean(o)) = (self, other) else { return Err(SbroadError::Invalid( Entity::Value, - Some( - format!( - "{self:?} and {other:?} must be booleans to be applied to AND operation" - ) - .into(), - ), + Some(format_smolstr!( + "{self:?} and {other:?} must be booleans to be applied to AND operation" + )), )); }; @@ -435,12 +434,9 @@ impl Value { let (Value::Boolean(s), Value::Boolean(o)) = (self, other) else { return Err(SbroadError::Invalid( Entity::Value, - Some( - format!( - "{self:?} and {other:?} must be booleans to be applied to OR operation" - ) - .into(), - ), + Some(format_smolstr!( + "{self:?} and {other:?} must be booleans to be applied to OR operation" + )), )); }; @@ -731,7 +727,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into map").into(), + format_smolstr!("{self:?} into map"), )), }, Type::Array => match self { @@ -739,7 +735,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into array").into(), + format_smolstr!("{self:?} into array"), )), }, Type::Boolean => match self { @@ -748,7 +744,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into boolean").into(), + format_smolstr!("{self:?} into boolean"), )), }, Type::Decimal => match self { @@ -758,7 +754,7 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{e:?}").into(), + format_smolstr!("{e:?}"), ) })?, ) @@ -769,7 +765,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into decimal").into(), + format_smolstr!("{self:?} into decimal"), )), }, Type::Double => match self { @@ -781,7 +777,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into double").into(), + format_smolstr!("{self:?} into double"), )), }, Type::Integer => match self { @@ -790,7 +786,7 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into integer").into(), + format_smolstr!("{self:?} into integer"), ) })?) .into()), @@ -810,7 +806,7 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("u64 {v} into i64: {e}").into(), + format_smolstr!("u64 {v} into i64: {e}"), ) })?) .into()), @@ -818,14 +814,14 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into integer").into(), + format_smolstr!("{self:?} into integer"), )), }, Type::Scalar => match self { Value::Tuple(_) => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into scalar").into(), + format_smolstr!("{self:?} into scalar"), )), _ => Ok(self.into()), }, @@ -835,7 +831,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into string").into(), + format_smolstr!("{self:?} into string"), )), }, Type::Uuid => match self { @@ -844,7 +840,7 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("uuid {v} into string: {e}").into(), + format_smolstr!("uuid {v} into string: {e}"), ) })?) .into()), @@ -852,7 +848,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into uuid").into(), + format_smolstr!("{self:?} into uuid"), )), }, Type::Number => match self { @@ -863,7 +859,7 @@ impl Value { _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into number").into(), + format_smolstr!("{self:?} into number"), )), }, Type::Unsigned => match self { @@ -872,7 +868,7 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("i64 {v} into u64: {e}").into(), + format_smolstr!("i64 {v} into u64: {e}"), ) })?) .into()), @@ -880,7 +876,7 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into unsigned").into(), + format_smolstr!("{self:?} into unsigned"), ) })?) .into()), @@ -893,14 +889,14 @@ impl Value { SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into unsigned").into(), + format_smolstr!("{self:?} into unsigned"), ) }), Value::Null => Ok(Value::Null.into()), _ => Err(SbroadError::FailedTo( Action::Serialize, Some(Entity::Value), - format!("{self:?} into unsigned").into(), + format_smolstr!("{self:?} into unsigned"), )), }, } diff --git a/sbroad-core/src/ir/value/double.rs b/sbroad-core/src/ir/value/double.rs index 467225a8e..69e675d7a 100644 --- a/sbroad-core/src/ir/value/double.rs +++ b/sbroad-core/src/ir/value/double.rs @@ -7,6 +7,7 @@ use std::str::FromStr; use crate::errors::{Entity, SbroadError}; use serde::{Deserialize, Serialize}; +use smol_str::format_smolstr; use tarantool::tlua; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] @@ -56,7 +57,7 @@ impl FromStr for Double { fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Double { value: s.parse::<f64>().map_err(|_| { - SbroadError::ParsingError(Entity::Value, format!("{s} is not a valid f64").into()) + SbroadError::ParsingError(Entity::Value, format_smolstr!("{s} is not a valid f64")) })?, }) } diff --git a/sbroad-core/src/otm.rs b/sbroad-core/src/otm.rs index 26dc30fc2..b25cd59ba 100644 --- a/sbroad-core/src/otm.rs +++ b/sbroad-core/src/otm.rs @@ -19,6 +19,7 @@ use opentelemetry::sdk::trace::Span; use opentelemetry::trace::{SpanBuilder, SpanKind, TraceContextExt, Tracer}; #[allow(unused_imports)] use opentelemetry::{Context, KeyValue}; +use smol_str::{SmolStr, ToSmolStr}; use std::cell::RefCell; use std::collections::HashMap; @@ -280,8 +281,8 @@ pub fn current_id() -> Option<String> { #[inline] #[must_use] -pub fn query_id(pattern: &str) -> String { - Base64::encode_string(blake3::hash(pattern.as_bytes()).to_hex().as_bytes()) +pub fn query_id(pattern: &str) -> SmolStr { + Base64::encode_string(blake3::hash(pattern.as_bytes()).to_hex().as_bytes()).to_smolstr() } #[allow(unused_variables)] -- GitLab