From b31dbb28fe8bce95598c2fa4d44604590bf96dfd Mon Sep 17 00:00:00 2001 From: Finn Bear Date: Thu, 22 Sep 2022 16:54:53 -0700 Subject: [PATCH] Miscellaneous performance optimizations and code cleanup (#240) --- lib/src/dbs/executor.rs | 4 +- lib/src/dbs/options.rs | 4 +- lib/src/dbs/session.rs | 8 +-- lib/src/doc/document.rs | 8 +-- lib/src/fnc/array.rs | 65 +++++++----------- lib/src/fnc/cast.rs | 56 ++++++++-------- lib/src/fnc/geo.rs | 71 +++++++------------- lib/src/fnc/http.rs | 95 ++++++-------------------- lib/src/fnc/is.rs | 9 +-- lib/src/fnc/math.rs | 144 ++++++++++++++++++++-------------------- lib/src/fnc/parse.rs | 18 ++--- lib/src/fnc/rand.rs | 9 +-- lib/src/fnc/string.rs | 2 +- lib/src/fnc/time.rs | 38 +++++------ lib/src/kvs/cache.rs | 28 ++++---- lib/src/kvs/tx.rs | 90 ++++++++++++------------- lib/src/sql/uuid.rs | 10 +-- 17 files changed, 278 insertions(+), 381 deletions(-) diff --git a/lib/src/dbs/executor.rs b/lib/src/dbs/executor.rs index 8246d524..2130f24a 100644 --- a/lib/src/dbs/executor.rs +++ b/lib/src/dbs/executor.rs @@ -118,14 +118,14 @@ impl<'a> Executor<'a> { let mut session = ctx.value("session").unwrap_or(&Value::None).clone(); session.put(NS.as_ref(), ns.to_owned().into()); ctx.add_value(String::from("session"), session); - opt.ns = Some(Arc::new(ns.to_owned())); + opt.ns = Some(ns.into()); } async fn set_db(&self, ctx: &mut Context<'_>, opt: &mut Options, db: &str) { let mut session = ctx.value("session").unwrap_or(&Value::None).clone(); session.put(DB.as_ref(), db.to_owned().into()); ctx.add_value(String::from("session"), session); - opt.db = Some(Arc::new(db.to_owned())); + opt.db = Some(db.into()); } pub async fn execute( diff --git a/lib/src/dbs/options.rs b/lib/src/dbs/options.rs index 1d90dbb5..86c677b8 100644 --- a/lib/src/dbs/options.rs +++ b/lib/src/dbs/options.rs @@ -14,9 +14,9 @@ use std::sync::Arc; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Options { // Currently selected NS - pub ns: Option>, + pub ns: Option>, // Currently selected DB - pub db: Option>, + pub db: Option>, // Connection authentication data pub auth: Arc, // How many subqueries have we gone into? diff --git a/lib/src/dbs/session.rs b/lib/src/dbs/session.rs index c31223aa..0a4ce053 100644 --- a/lib/src/dbs/session.rs +++ b/lib/src/dbs/session.rs @@ -83,12 +83,12 @@ impl Session { self } /// Retrieves the selected namespace - pub(crate) fn ns(&self) -> Option> { - self.ns.to_owned().map(Arc::new) + pub(crate) fn ns(&self) -> Option> { + self.ns.as_deref().map(Into::into) } /// Retrieves the selected database - pub(crate) fn db(&self) -> Option> { - self.db.to_owned().map(Arc::new) + pub(crate) fn db(&self) -> Option> { + self.db.as_deref().map(Into::into) } /// Convert a session into a runtime pub(crate) fn context<'a>(&self, mut ctx: Context<'a>) -> Context<'a> { diff --git a/lib/src/doc/document.rs b/lib/src/doc/document.rs index f8f74db0..77fbc626 100644 --- a/lib/src/doc/document.rs +++ b/lib/src/doc/document.rs @@ -83,7 +83,7 @@ impl<'a> Document<'a> { &self, opt: &Options, txn: &Transaction, - ) -> Result>, Error> { + ) -> Result, Error> { // Get the record id let id = self.id.as_ref().unwrap(); // Get the table definitions @@ -94,7 +94,7 @@ impl<'a> Document<'a> { &self, opt: &Options, txn: &Transaction, - ) -> Result>, Error> { + ) -> Result, Error> { // Get the record id let id = self.id.as_ref().unwrap(); // Get the event definitions @@ -105,7 +105,7 @@ impl<'a> Document<'a> { &self, opt: &Options, txn: &Transaction, - ) -> Result>, Error> { + ) -> Result, Error> { // Get the record id let id = self.id.as_ref().unwrap(); // Get the field definitions @@ -116,7 +116,7 @@ impl<'a> Document<'a> { &self, opt: &Options, txn: &Transaction, - ) -> Result>, Error> { + ) -> Result, Error> { // Get the record id let id = self.id.as_ref().unwrap(); // Get the index definitions diff --git a/lib/src/fnc/array.rs b/lib/src/fnc/array.rs index d5755f1c..e13134d8 100644 --- a/lib/src/fnc/array.rs +++ b/lib/src/fnc/array.rs @@ -7,34 +7,25 @@ use crate::sql::array::Union; use crate::sql::array::Uniq; use crate::sql::value::Value; -pub fn concat((left, right): (Value, Value)) -> Result { - match left { - Value::Array(v) => match right { - Value::Array(w) => Ok(v.concat(w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn concat(arrays: (Value, Value)) -> Result { + Ok(match arrays { + (Value::Array(v), Value::Array(w)) => v.concat(w).into(), + _ => Value::None, + }) } -pub fn combine((left, right): (Value, Value)) -> Result { - match left { - Value::Array(v) => match right { - Value::Array(w) => Ok(v.combine(w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn combine(arrays: (Value, Value)) -> Result { + Ok(match arrays { + (Value::Array(v), Value::Array(w)) => v.combine(w).into(), + _ => Value::None, + }) } -pub fn difference((left, right): (Value, Value)) -> Result { - match left { - Value::Array(v) => match right { - Value::Array(w) => Ok(v.difference(w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn difference(arrays: (Value, Value)) -> Result { + Ok(match arrays { + (Value::Array(v), Value::Array(w)) => v.difference(w).into(), + _ => Value::None, + }) } pub fn distinct((arg,): (Value,)) -> Result { @@ -44,14 +35,11 @@ pub fn distinct((arg,): (Value,)) -> Result { } } -pub fn intersect((left, right): (Value, Value)) -> Result { - match left { - Value::Array(v) => match right { - Value::Array(w) => Ok(v.intersect(w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn intersect(arrays: (Value, Value)) -> Result { + Ok(match arrays { + (Value::Array(v), Value::Array(w)) => v.intersect(w).into(), + _ => Value::None, + }) } pub fn len((arg,): (Value,)) -> Result { @@ -94,14 +82,11 @@ pub fn sort((array, order): (Value, Option)) -> Result { } } -pub fn union((left, right): (Value, Value)) -> Result { - match left { - Value::Array(v) => match right { - Value::Array(w) => Ok(v.union(w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn union(arrays: (Value, Value)) -> Result { + Ok(match arrays { + (Value::Array(v), Value::Array(w)) => v.union(w).into(), + _ => Value::None, + }) } pub mod sort { diff --git a/lib/src/fnc/cast.rs b/lib/src/fnc/cast.rs index 9422a6f1..7146c3cb 100644 --- a/lib/src/fnc/cast.rs +++ b/lib/src/fnc/cast.rs @@ -22,50 +22,50 @@ pub fn bool(val: Value) -> Result { } pub fn int(val: Value) -> Result { - match val { - Value::Number(Number::Int(_)) => Ok(val), - _ => Ok(Value::Number(Number::Int(val.as_int()))), - } + Ok(match val { + Value::Number(Number::Int(_)) => val, + _ => Value::Number(Number::Int(val.as_int())), + }) } pub fn float(val: Value) -> Result { - match val { - Value::Number(Number::Float(_)) => Ok(val), - _ => Ok(Value::Number(Number::Float(val.as_float()))), - } + Ok(match val { + Value::Number(Number::Float(_)) => val, + _ => Value::Number(Number::Float(val.as_float())), + }) } pub fn number(val: Value) -> Result { - match val { - Value::Number(Number::Decimal(_)) => Ok(val), - _ => Ok(Value::Number(Number::Decimal(val.as_decimal()))), - } + Ok(match val { + Value::Number(Number::Decimal(_)) => val, + _ => Value::Number(Number::Decimal(val.as_decimal())), + }) } pub fn decimal(val: Value) -> Result { - match val { - Value::Number(Number::Decimal(_)) => Ok(val), - _ => Ok(Value::Number(Number::Decimal(val.as_decimal()))), - } + Ok(match val { + Value::Number(Number::Decimal(_)) => val, + _ => Value::Number(Number::Decimal(val.as_decimal())), + }) } pub fn string(val: Value) -> Result { - match val { - Value::Strand(_) => Ok(val), - _ => Ok(Value::Strand(val.as_strand())), - } + Ok(match val { + Value::Strand(_) => val, + _ => Value::Strand(val.as_strand()), + }) } pub fn datetime(val: Value) -> Result { - match val { - Value::Datetime(_) => Ok(val), - _ => Ok(Value::Datetime(val.as_datetime())), - } + Ok(match val { + Value::Datetime(_) => val, + _ => Value::Datetime(val.as_datetime()), + }) } pub fn duration(val: Value) -> Result { - match val { - Value::Duration(_) => Ok(val), - _ => Ok(Value::Duration(val.as_duration())), - } + Ok(match val { + Value::Duration(_) => val, + _ => Value::Duration(val.as_duration()), + }) } diff --git a/lib/src/fnc/geo.rs b/lib/src/fnc/geo.rs index 8ca90c4f..69d4f508 100644 --- a/lib/src/fnc/geo.rs +++ b/lib/src/fnc/geo.rs @@ -23,59 +23,38 @@ pub fn area((arg,): (Value,)) -> Result { } } -pub fn bearing((a, b): (Value, Value)) -> Result { - match a { - Value::Geometry(Geometry::Point(v)) => match b { - Value::Geometry(Geometry::Point(w)) => Ok(v.bearing(w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn bearing(points: (Value, Value)) -> Result { + Ok(match points { + (Value::Geometry(Geometry::Point(v)), Value::Geometry(Geometry::Point(w))) => { + v.bearing(w).into() + } + _ => Value::None, + }) } pub fn centroid((arg,): (Value,)) -> Result { - match arg { + let centroid = match arg { Value::Geometry(v) => match v { - Geometry::Point(v) => Ok(v.centroid().into()), - Geometry::Line(v) => match v.centroid() { - Some(x) => Ok(x.into()), - None => Ok(Value::None), - }, - Geometry::Polygon(v) => match v.centroid() { - Some(x) => Ok(x.into()), - None => Ok(Value::None), - }, - Geometry::MultiPoint(v) => match v.centroid() { - Some(x) => Ok(x.into()), - None => Ok(Value::None), - }, - Geometry::MultiLine(v) => match v.centroid() { - Some(x) => Ok(x.into()), - None => Ok(Value::None), - }, - Geometry::MultiPolygon(v) => match v.centroid() { - Some(x) => Ok(x.into()), - None => Ok(Value::None), - }, - Geometry::Collection(v) => { - match v.into_iter().collect::>().centroid() { - Some(x) => Ok(x.into()), - None => Ok(Value::None), - } - } + Geometry::Point(v) => Some(v.centroid()), + Geometry::Line(v) => v.centroid(), + Geometry::Polygon(v) => v.centroid(), + Geometry::MultiPoint(v) => v.centroid(), + Geometry::MultiLine(v) => v.centroid(), + Geometry::MultiPolygon(v) => v.centroid(), + Geometry::Collection(v) => v.into_iter().collect::>().centroid(), }, - _ => Ok(Value::None), - } + _ => None, + }; + Ok(centroid.map(Into::into).unwrap_or(Value::None)) } -pub fn distance((from, to): (Value, Value)) -> Result { - match from { - Value::Geometry(Geometry::Point(v)) => match to { - Value::Geometry(Geometry::Point(w)) => Ok(v.haversine_distance(&w).into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), - } +pub fn distance(points: (Value, Value)) -> Result { + Ok(match points { + (Value::Geometry(Geometry::Point(v)), Value::Geometry(Geometry::Point(w))) => { + v.haversine_distance(&w).into() + } + _ => Value::None, + }) } pub mod hash { diff --git a/lib/src/fnc/http.rs b/lib/src/fnc/http.rs index 1ada5d22..a6528d58 100644 --- a/lib/src/fnc/http.rs +++ b/lib/src/fnc/http.rs @@ -1,6 +1,6 @@ use crate::err::Error; use crate::sql::value::Value; -use crate::sql::Strand; +use crate::sql::{Object, Strand}; #[cfg(not(feature = "http"))] pub async fn head((_, _): (Value, Option)) -> Result { @@ -43,57 +43,39 @@ fn try_as_uri(fn_name: &str, value: Value) -> Result { } } +fn try_as_opts( + fn_name: &str, + error_message: &str, + value: Option, +) -> Result, Error> { + match value { + Some(Value::Object(opts)) => Ok(Some(opts)), + None => Ok(None), + Some(_) => Err(Error::InvalidArguments { + name: fn_name.to_owned(), + message: error_message.to_owned(), + }), + } +} + #[cfg(feature = "http")] pub async fn head((uri, opts): (Value, Option)) -> Result { let uri = try_as_uri("http::head", uri)?; - - let opts = match opts { - Some(Value::Object(opts)) => Some(opts), - None => None, - Some(_) => { - return Err(Error::InvalidArguments { - name: String::from("http::head"), - message: String::from("The second argument should be an object."), - }) - } - }; - + let opts = try_as_opts("http::head", "The second argument should be an object.", opts)?; crate::fnc::util::http::head(uri, opts).await } #[cfg(feature = "http")] pub async fn get((uri, opts): (Value, Option)) -> Result { let uri = try_as_uri("http::get", uri)?; - - let opts = match opts { - Some(Value::Object(opts)) => Some(opts), - None => None, - Some(_) => { - return Err(Error::InvalidArguments { - name: String::from("http::get"), - message: String::from("The second argument should be an object."), - }) - } - }; - + let opts = try_as_opts("http::get", "The second argument should be an object.", opts)?; crate::fnc::util::http::get(uri, opts).await } #[cfg(feature = "http")] pub async fn put((uri, body, opts): (Value, Option, Option)) -> Result { let uri = try_as_uri("http::put", uri)?; - - let opts = match opts { - Some(Value::Object(opts)) => Some(opts), - None => None, - Some(_) => { - return Err(Error::InvalidArguments { - name: String::from("http::put"), - message: String::from("The third argument should be an object."), - }) - } - }; - + let opts = try_as_opts("http::put", "The third argument should be an object.", opts)?; crate::fnc::util::http::put(uri, body.unwrap_or(Value::Null), opts).await } @@ -102,18 +84,7 @@ pub async fn post( (uri, body, opts): (Value, Option, Option), ) -> Result { let uri = try_as_uri("http::post", uri)?; - - let opts = match opts { - Some(Value::Object(opts)) => Some(opts), - None => None, - Some(_) => { - return Err(Error::InvalidArguments { - name: String::from("http::post"), - message: String::from("The third argument should be an object."), - }) - } - }; - + let opts = try_as_opts("http::post", "The third argument should be an object.", opts)?; crate::fnc::util::http::post(uri, body.unwrap_or(Value::Null), opts).await } @@ -122,35 +93,13 @@ pub async fn patch( (uri, body, opts): (Value, Option, Option), ) -> Result { let uri = try_as_uri("http::patch", uri)?; - - let opts = match opts { - Some(Value::Object(opts)) => Some(opts), - None => None, - Some(_) => { - return Err(Error::InvalidArguments { - name: String::from("http::patch"), - message: String::from("The third argument should be an object."), - }) - } - }; - + let opts = try_as_opts("http::patch", "The third argument should be an object.", opts)?; crate::fnc::util::http::patch(uri, body.unwrap_or(Value::Null), opts).await } #[cfg(feature = "http")] pub async fn delete((uri, opts): (Value, Option)) -> Result { let uri = try_as_uri("http::delete", uri)?; - - let opts = match opts { - Some(Value::Object(opts)) => Some(opts), - None => None, - Some(_) => { - return Err(Error::InvalidArguments { - name: String::from("http::delete"), - message: String::from("The second argument should be an object."), - }) - } - }; - + let opts = try_as_opts("http::delete", "The second argument should be an object.", opts)?; crate::fnc::util::http::delete(uri, opts).await } diff --git a/lib/src/fnc/is.rs b/lib/src/fnc/is.rs index 96b826d1..02ec86df 100644 --- a/lib/src/fnc/is.rs +++ b/lib/src/fnc/is.rs @@ -62,10 +62,11 @@ pub fn semver((arg,): (String,)) -> Result { #[inline] pub fn uuid((arg,): (Value,)) -> Result { Ok(match arg { - Value::Strand(v) => Uuid::parse_str(v.as_string().as_str()).is_ok().into(), - Value::Uuid(_) => true.into(), - _ => false.into(), - }) + Value::Strand(v) => Uuid::parse_str(v.as_string().as_str()).is_ok(), + Value::Uuid(_) => true, + _ => false, + } + .into()) } #[cfg(test)] diff --git a/lib/src/fnc/math.rs b/lib/src/fnc/math.rs index 68a00c6d..c22f07fb 100644 --- a/lib/src/fnc/math.rs +++ b/lib/src/fnc/math.rs @@ -20,10 +20,10 @@ pub fn abs((arg,): (Number,)) -> Result { } pub fn bottom((array, c): (Value, i64)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().bottom(c).into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().bottom(c).into(), + _ => Value::None, + }) } pub fn ceil((arg,): (Number,)) -> Result { @@ -46,85 +46,85 @@ pub fn floor((arg,): (Number,)) -> Result { } pub fn interquartile((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().interquartile().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().interquartile().into(), + _ => Value::None, + }) } pub fn max((array,): (Value,)) -> Result { - match array { + Ok(match array { Value::Array(v) => match v.as_numbers().into_iter().max() { - Some(v) => Ok(v.into()), - None => Ok(Value::None), + Some(v) => v.into(), + None => Value::None, }, - v => Ok(v), - } + v => v, + }) } pub fn mean((array,): (Value,)) -> Result { - match array { + Ok(match array { Value::Array(v) => match v.is_empty() { - true => Ok(Value::None), - false => Ok(v.as_numbers().mean().into()), + true => Value::None, + false => v.as_numbers().mean().into(), }, - _ => Ok(Value::None), - } + _ => Value::None, + }) } pub fn median((array,): (Value,)) -> Result { - match array { + Ok(match array { Value::Array(v) => match v.is_empty() { - true => Ok(Value::None), - false => Ok(v.as_numbers().median().into()), + true => Value::None, + false => v.as_numbers().median().into(), }, - _ => Ok(Value::None), - } + _ => Value::None, + }) } pub fn midhinge((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().midhinge().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().midhinge().into(), + _ => Value::None, + }) } pub fn min((array,): (Value,)) -> Result { - match array { + Ok(match array { Value::Array(v) => match v.as_numbers().into_iter().min() { - Some(v) => Ok(v.into()), - None => Ok(Value::None), + Some(v) => v.into(), + None => Value::None, }, - v => Ok(v), - } + v => v, + }) } pub fn mode((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().mode().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().mode().into(), + _ => Value::None, + }) } pub fn nearestrank((array, n): (Value, Number)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().nearestrank(n).into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().nearestrank(n).into(), + _ => Value::None, + }) } pub fn percentile((array, n): (Value, Number)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().percentile(n).into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().percentile(n).into(), + _ => Value::None, + }) } pub fn product((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().into_iter().product::().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().into_iter().product::().into(), + _ => Value::None, + }) } pub fn round((arg,): (Number,)) -> Result { @@ -132,10 +132,10 @@ pub fn round((arg,): (Number,)) -> Result { } pub fn spread((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().spread().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().spread().into(), + _ => Value::None, + }) } pub fn sqrt((arg,): (Number,)) -> Result { @@ -146,36 +146,36 @@ pub fn sqrt((arg,): (Number,)) -> Result { } pub fn stddev((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().deviation().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().deviation().into(), + _ => Value::None, + }) } pub fn sum((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().into_iter().sum::().into()), - v => Ok(v.as_number().into()), - } + Ok(match array { + Value::Array(v) => v.as_numbers().into_iter().sum::().into(), + v => v.as_number().into(), + }) } pub fn top((array, c): (Value, i64)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().top(c).into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().top(c).into(), + _ => Value::None, + }) } pub fn trimean((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().trimean().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().trimean().into(), + _ => Value::None, + }) } pub fn variance((array,): (Value,)) -> Result { - match array { - Value::Array(v) => Ok(v.as_numbers().variance().into()), - _ => Ok(Value::None), - } + Ok(match array { + Value::Array(v) => v.as_numbers().variance().into(), + _ => Value::None, + }) } diff --git a/lib/src/fnc/parse.rs b/lib/src/fnc/parse.rs index 3a20d727..f7411568 100644 --- a/lib/src/fnc/parse.rs +++ b/lib/src/fnc/parse.rs @@ -6,23 +6,23 @@ pub mod email { pub fn host((string,): (String,)) -> Result { // Parse the email address - match addr::parse_email_address(&string) { + Ok(match addr::parse_email_address(&string) { // Return the host part Ok(v) => match v.host() { - Host::Domain(name) => Ok(name.as_str().into()), - Host::IpAddr(ip_addr) => Ok(ip_addr.to_string().into()), + Host::Domain(name) => name.as_str().into(), + Host::IpAddr(ip_addr) => ip_addr.to_string().into(), }, - Err(_) => Ok(Value::None), - } + Err(_) => Value::None, + }) } pub fn user((string,): (String,)) -> Result { // Parse the email address - match addr::parse_email_address(&string) { + Ok(match addr::parse_email_address(&string) { // Return the user part - Ok(v) => Ok(v.user().into()), - Err(_) => Ok(Value::None), - } + Ok(v) => v.user().into(), + Err(_) => Value::None, + }) } #[cfg(test)] diff --git a/lib/src/fnc/rand.rs b/lib/src/fnc/rand.rs index 71cfae0e..e15d81e4 100644 --- a/lib/src/fnc/rand.rs +++ b/lib/src/fnc/rand.rs @@ -4,7 +4,7 @@ use crate::sql::datetime::Datetime; use crate::sql::uuid::Uuid; use crate::sql::value::Value; use nanoid::nanoid; -use rand::distributions::Alphanumeric; +use rand::distributions::{Alphanumeric, DistString}; use rand::prelude::IteratorRandom; use rand::Rng; @@ -103,12 +103,7 @@ pub fn string((arg1, arg2): (Option, Option)) -> Result 32 }; - Ok(rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(len) - .map(char::from) - .collect::() - .into()) + Ok(Alphanumeric.sample_string(&mut rand::thread_rng(), len).into()) } pub fn time((range,): (Option<(i64, i64)>,)) -> Result { diff --git a/lib/src/fnc/string.rs b/lib/src/fnc/string.rs index 1bb689c0..ac06cc38 100644 --- a/lib/src/fnc/string.rs +++ b/lib/src/fnc/string.rs @@ -12,7 +12,7 @@ pub fn ends_with((val, chr): (String, String)) -> Result { pub fn join(args: Vec) -> Result { let mut args = args.into_iter().map(Value::as_string); - let chr = args.next().ok_or(Error::InvalidArguments { + let chr = args.next().ok_or_else(|| Error::InvalidArguments { name: String::from("string::join"), message: String::from("Expected at least one argument"), })?; diff --git a/lib/src/fnc/time.rs b/lib/src/fnc/time.rs index 3c97ca70..823e3752 100644 --- a/lib/src/fnc/time.rs +++ b/lib/src/fnc/time.rs @@ -18,19 +18,16 @@ pub fn day((datetime,): (Option,)) -> Result { } pub fn floor((datetime, duration): (Value, Value)) -> Result { - match datetime { - Value::Datetime(v) => match duration { - Value::Duration(w) => match chrono::Duration::from_std(*w) { - Ok(d) => match v.duration_trunc(d) { - Ok(v) => Ok(v.into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), + Ok(match (datetime, duration) { + (Value::Datetime(v), Value::Duration(w)) => match chrono::Duration::from_std(*w) { + Ok(d) => match v.duration_trunc(d) { + Ok(v) => v.into(), + _ => Value::None, }, - _ => Ok(Value::None), + _ => Value::None, }, - _ => Ok(Value::None), - } + _ => Value::None, + }) } pub fn group((datetime, strand): (Value, Value)) -> Result { @@ -111,19 +108,16 @@ pub fn now(_: ()) -> Result { } pub fn round((datetime, duration): (Value, Value)) -> Result { - match datetime { - Value::Datetime(v) => match duration { - Value::Duration(w) => match chrono::Duration::from_std(*w) { - Ok(d) => match v.duration_round(d) { - Ok(v) => Ok(v.into()), - _ => Ok(Value::None), - }, - _ => Ok(Value::None), + Ok(match (datetime, duration) { + (Value::Datetime(v), Value::Duration(w)) => match chrono::Duration::from_std(*w) { + Ok(d) => match v.duration_round(d) { + Ok(v) => v.into(), + _ => Value::None, }, - _ => Ok(Value::None), + _ => Value::None, }, - _ => Ok(Value::None), - } + _ => Value::None, + }) } pub fn secs((datetime,): (Option,)) -> Result { diff --git a/lib/src/kvs/cache.rs b/lib/src/kvs/cache.rs index 63dc0326..7fa295ec 100644 --- a/lib/src/kvs/cache.rs +++ b/lib/src/kvs/cache.rs @@ -17,20 +17,20 @@ pub enum Entry { Ns(Arc), Db(Arc), Tb(Arc), - Nss(Arc>), - Nls(Arc>), - Nts(Arc>), - Dbs(Arc>), - Dls(Arc>), - Dts(Arc>), - Scs(Arc>), - Sts(Arc>), - Tbs(Arc>), - Evs(Arc>), - Fds(Arc>), - Ixs(Arc>), - Fts(Arc>), - Lvs(Arc>), + Nss(Arc<[DefineNamespaceStatement]>), + Nls(Arc<[DefineLoginStatement]>), + Nts(Arc<[DefineTokenStatement]>), + Dbs(Arc<[DefineDatabaseStatement]>), + Dls(Arc<[DefineLoginStatement]>), + Dts(Arc<[DefineTokenStatement]>), + Scs(Arc<[DefineScopeStatement]>), + Sts(Arc<[DefineTokenStatement]>), + Tbs(Arc<[DefineTableStatement]>), + Evs(Arc<[DefineEventStatement]>), + Fds(Arc<[DefineFieldStatement]>), + Ixs(Arc<[DefineIndexStatement]>), + Fts(Arc<[DefineTableStatement]>), + Lvs(Arc<[LiveStatement]>), } #[derive(Default)] diff --git a/lib/src/kvs/tx.rs b/lib/src/kvs/tx.rs index 612dd9bf..246205d5 100644 --- a/lib/src/kvs/tx.rs +++ b/lib/src/kvs/tx.rs @@ -612,7 +612,7 @@ impl Transaction { Ok(()) } /// Retrieve all namespace definitions in a datastore. - pub async fn all_ns(&mut self) -> Result>, Error> { + pub async fn all_ns(&mut self) -> Result, Error> { let key = crate::key::ns::prefix(); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -623,14 +623,14 @@ impl Transaction { let beg = crate::key::ns::prefix(); let end = crate::key::ns::suffix(); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Nss(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Nss(Arc::clone(&val))); Ok(val) } } } /// Retrieve all namespace login definitions for a specific namespace. - pub async fn all_nl(&mut self, ns: &str) -> Result>, Error> { + pub async fn all_nl(&mut self, ns: &str) -> Result, Error> { let key = crate::key::nl::prefix(ns); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -641,14 +641,14 @@ impl Transaction { let beg = crate::key::nl::prefix(ns); let end = crate::key::nl::suffix(ns); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Nls(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Nls(Arc::clone(&val))); Ok(val) } } } /// Retrieve all namespace token definitions for a specific namespace. - pub async fn all_nt(&mut self, ns: &str) -> Result>, Error> { + pub async fn all_nt(&mut self, ns: &str) -> Result, Error> { let key = crate::key::nt::prefix(ns); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -659,14 +659,14 @@ impl Transaction { let beg = crate::key::nt::prefix(ns); let end = crate::key::nt::suffix(ns); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Nts(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Nts(Arc::clone(&val))); Ok(val) } } } /// Retrieve all database definitions for a specific namespace. - pub async fn all_db(&mut self, ns: &str) -> Result>, Error> { + pub async fn all_db(&mut self, ns: &str) -> Result, Error> { let key = crate::key::db::prefix(ns); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -677,8 +677,8 @@ impl Transaction { let beg = crate::key::db::prefix(ns); let end = crate::key::db::suffix(ns); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Dbs(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Dbs(Arc::clone(&val))); Ok(val) } } @@ -688,7 +688,7 @@ impl Transaction { &mut self, ns: &str, db: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::dl::prefix(ns, db); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -699,8 +699,8 @@ impl Transaction { let beg = crate::key::dl::prefix(ns, db); let end = crate::key::dl::suffix(ns, db); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Dls(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Dls(Arc::clone(&val))); Ok(val) } } @@ -710,7 +710,7 @@ impl Transaction { &mut self, ns: &str, db: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::dt::prefix(ns, db); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -721,8 +721,8 @@ impl Transaction { let beg = crate::key::dt::prefix(ns, db); let end = crate::key::dt::suffix(ns, db); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Dts(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Dts(Arc::clone(&val))); Ok(val) } } @@ -732,7 +732,7 @@ impl Transaction { &mut self, ns: &str, db: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::sc::prefix(ns, db); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -743,8 +743,8 @@ impl Transaction { let beg = crate::key::sc::prefix(ns, db); let end = crate::key::sc::suffix(ns, db); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Scs(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Scs(Arc::clone(&val))); Ok(val) } } @@ -755,7 +755,7 @@ impl Transaction { ns: &str, db: &str, sc: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::st::prefix(ns, db, sc); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -766,8 +766,8 @@ impl Transaction { let beg = crate::key::st::prefix(ns, db, sc); let end = crate::key::st::suffix(ns, db, sc); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Sts(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Sts(Arc::clone(&val))); Ok(val) } } @@ -777,7 +777,7 @@ impl Transaction { &mut self, ns: &str, db: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::tb::prefix(ns, db); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -788,8 +788,8 @@ impl Transaction { let beg = crate::key::tb::prefix(ns, db); let end = crate::key::tb::suffix(ns, db); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Tbs(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Tbs(Arc::clone(&val))); Ok(val) } } @@ -800,7 +800,7 @@ impl Transaction { ns: &str, db: &str, tb: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::ev::prefix(ns, db, tb); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -811,8 +811,8 @@ impl Transaction { let beg = crate::key::ev::prefix(ns, db, tb); let end = crate::key::ev::suffix(ns, db, tb); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Evs(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Evs(Arc::clone(&val))); Ok(val) } } @@ -823,7 +823,7 @@ impl Transaction { ns: &str, db: &str, tb: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::fd::prefix(ns, db, tb); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -834,8 +834,8 @@ impl Transaction { let beg = crate::key::fd::prefix(ns, db, tb); let end = crate::key::fd::suffix(ns, db, tb); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Fds(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Fds(Arc::clone(&val))); Ok(val) } } @@ -846,7 +846,7 @@ impl Transaction { ns: &str, db: &str, tb: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::ix::prefix(ns, db, tb); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -857,8 +857,8 @@ impl Transaction { let beg = crate::key::ix::prefix(ns, db, tb); let end = crate::key::ix::suffix(ns, db, tb); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Ixs(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Ixs(Arc::clone(&val))); Ok(val) } } @@ -869,7 +869,7 @@ impl Transaction { ns: &str, db: &str, tb: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::ft::prefix(ns, db, tb); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -880,8 +880,8 @@ impl Transaction { let beg = crate::key::ft::prefix(ns, db, tb); let end = crate::key::ft::suffix(ns, db, tb); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Fts(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Fts(Arc::clone(&val))); Ok(val) } } @@ -892,7 +892,7 @@ impl Transaction { ns: &str, db: &str, tb: &str, - ) -> Result>, Error> { + ) -> Result, Error> { let key = crate::key::lv::prefix(ns, db, tb); match self.cache.exi(&key) { true => match self.cache.get(&key) { @@ -903,8 +903,8 @@ impl Transaction { let beg = crate::key::lv::prefix(ns, db, tb); let end = crate::key::lv::suffix(ns, db, tb); let val = self.getr(beg..end, u32::MAX).await?; - let val = Arc::new(val.convert()); - self.cache.set(key, Entry::Lvs(val.clone())); + let val = val.convert().into(); + self.cache.set(key, Entry::Lvs(Arc::clone(&val))); Ok(val) } } @@ -1074,7 +1074,7 @@ impl Transaction { _ => { let val = self.get(key.clone()).await?.ok_or(Error::NsNotFound)?; let val: Arc = Arc::new(val.into()); - self.cache.set(key, Entry::Ns(val.clone())); + self.cache.set(key, Entry::Ns(Arc::clone(&val))); Ok(val) } } @@ -1094,7 +1094,7 @@ impl Transaction { _ => { let val = self.get(key.clone()).await?.ok_or(Error::DbNotFound)?; let val: Arc = Arc::new(val.into()); - self.cache.set(key, Entry::Db(val.clone())); + self.cache.set(key, Entry::Db(Arc::clone(&val))); Ok(val) } } @@ -1115,7 +1115,7 @@ impl Transaction { _ => { let val = self.get(key.clone()).await?.ok_or(Error::TbNotFound)?; let val: Arc = Arc::new(val.into()); - self.cache.set(key, Entry::Tb(val.clone())); + self.cache.set(key, Entry::Tb(Arc::clone(&val))); Ok(val) } } diff --git a/lib/src/sql/uuid.rs b/lib/src/sql/uuid.rs index 1c1f4872..0814ca1e 100644 --- a/lib/src/sql/uuid.rs +++ b/lib/src/sql/uuid.rs @@ -20,19 +20,13 @@ pub struct Uuid(pub uuid::Uuid); impl From<&str> for Uuid { fn from(s: &str) -> Self { - match uuid::Uuid::try_parse(s) { - Ok(v) => Uuid(v), - _ => Uuid::default(), - } + uuid::Uuid::try_parse(s).map(Uuid).unwrap_or_default() } } impl From for Uuid { fn from(s: String) -> Self { - match uuid::Uuid::try_parse(&s) { - Ok(v) => Uuid(v), - _ => Uuid::default(), - } + Self::from(s.as_str()) } }