Apply cargo clippy lint recommendations

This commit is contained in:
Tobie Morgan Hitchcock 2022-03-04 16:01:32 +00:00
parent bcd8d4f2a7
commit d1c2daaee4
88 changed files with 535 additions and 633 deletions

View file

@ -127,18 +127,12 @@ impl Context {
// Check if the context is not ok to continue, because it timed out. // Check if the context is not ok to continue, because it timed out.
pub fn is_timedout(&self) -> bool { pub fn is_timedout(&self) -> bool {
match self.done() { matches!(self.done(), Some(Reason::Timedout))
Some(Reason::Timedout) => true,
_ => false,
}
} }
// Check if the context is not ok to continue, because it was cancelled. // Check if the context is not ok to continue, because it was cancelled.
pub fn is_cancelled(&self) -> bool { pub fn is_cancelled(&self) -> bool {
match self.done() { matches!(self.done(), Some(Reason::Canceled))
Some(Reason::Canceled) => true,
_ => false,
}
} }
// Check if the status of the context. This will return a Result, with an Ok // Check if the status of the context. This will return a Result, with an Ok

View file

@ -25,35 +25,11 @@ impl Default for Auth {
impl Auth { impl Auth {
pub fn check(&self, level: Level) -> bool { pub fn check(&self, level: Level) -> bool {
match self { match self {
Auth::No => match level { Auth::No => matches!(level, Level::No),
Level::No => true, Auth::Kv => matches!(level, Level::No | Level::Kv),
_ => false, Auth::Ns(_) => matches!(level, Level::No | Level::Kv | Level::Ns),
}, Auth::Db(_, _) => matches!(level, Level::No | Level::Kv | Level::Ns | Level::Db),
Auth::Kv => match level { Auth::Sc(_, _, _) => true,
Level::No => true,
Level::Kv => true,
_ => false,
},
Auth::Ns(_) => match level {
Level::No => true,
Level::Kv => true,
Level::Ns => true,
_ => false,
},
Auth::Db(_, _) => match level {
Level::No => true,
Level::Kv => true,
Level::Ns => true,
Level::Db => true,
_ => false,
},
Auth::Sc(_, _, _) => match level {
Level::No => true,
Level::Kv => true,
Level::Ns => true,
Level::Db => true,
Level::Sc => true,
},
} }
} }
} }

View file

@ -3,7 +3,6 @@ use crate::dbs::Options;
use crate::dbs::Runtime; use crate::dbs::Runtime;
use crate::dbs::Transaction; use crate::dbs::Transaction;
use crate::err::Error; use crate::err::Error;
use crate::key::thing;
use crate::sql::array::Array; use crate::sql::array::Array;
use crate::sql::model::Model; use crate::sql::model::Model;
use crate::sql::table::Table; use crate::sql::table::Table;
@ -95,10 +94,10 @@ impl Model {
impl Thing { impl Thing {
pub async fn process( pub async fn process(
self, self,
ctx: &Runtime, _ctx: &Runtime,
opt: &Options, _opt: &Options,
txn: &Transaction, _txn: &Transaction,
chn: &Sender<(Option<Thing>, Value)>, _chn: &Sender<(Option<Thing>, Value)>,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())
} }
@ -107,10 +106,10 @@ impl Thing {
impl Table { impl Table {
pub async fn process( pub async fn process(
self, self,
ctx: &Runtime, _ctx: &Runtime,
opt: &Options, _opt: &Options,
txn: &Transaction, _txn: &Transaction,
chn: &Sender<(Option<Thing>, Value)>, _chn: &Sender<(Option<Thing>, Value)>,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())
} }

View file

@ -53,8 +53,8 @@ impl Executor {
async fn commit(&mut self, local: bool) { async fn commit(&mut self, local: bool) {
if local { if local {
match self.txn.as_ref() { if let Some(txn) = self.txn.as_ref() {
Some(txn) => match &self.err { match &self.err {
Some(_) => { Some(_) => {
let txn = txn.clone(); let txn = txn.clone();
let mut txn = txn.lock().await; let mut txn = txn.lock().await;
@ -71,8 +71,7 @@ impl Executor {
} }
self.txn = None; self.txn = None;
} }
}, }
None => (),
} }
} }
} }

View file

@ -4,7 +4,6 @@ use crate::dbs::Options;
use crate::dbs::Runtime; use crate::dbs::Runtime;
use crate::dbs::Transaction; use crate::dbs::Transaction;
use crate::err::Error; use crate::err::Error;
use crate::key::thing;
use crate::sql::array::Array; use crate::sql::array::Array;
use crate::sql::model::Model; use crate::sql::model::Model;
use crate::sql::table::Table; use crate::sql::table::Table;
@ -98,10 +97,10 @@ impl Model {
impl Thing { impl Thing {
pub async fn iterate( pub async fn iterate(
self, self,
ctx: &Runtime, _ctx: &Runtime,
opt: &Options, _opt: &Options,
txn: &Transaction, _txn: &Transaction,
ite: &mut Iterator, _ite: &mut Iterator,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())
} }
@ -110,10 +109,10 @@ impl Thing {
impl Table { impl Table {
pub async fn iterate( pub async fn iterate(
self, self,
ctx: &Runtime, _ctx: &Runtime,
opt: &Options, _opt: &Options,
txn: &Transaction, _txn: &Transaction,
ite: &mut Iterator, _ite: &mut Iterator,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())
} }

View file

@ -106,7 +106,7 @@ impl Iterator {
// Create a new record for processing // Create a new record for processing
pub fn produce(&mut self, val: Table) { pub fn produce(&mut self, val: Table) {
self.prepare(Value::Thing(Thing { self.prepare(Value::Thing(Thing {
tb: val.name.to_string(), tb: val.name,
id: nanoid!(20, &ID_CHARS), id: nanoid!(20, &ID_CHARS),
})) }))
} }
@ -121,7 +121,7 @@ impl Iterator {
// Log the statement // Log the statement
trace!("Iterating: {}", self.stm); trace!("Iterating: {}", self.stm);
// Enable context override // Enable context override
let mut ctx = Context::new(&ctx); let mut ctx = Context::new(ctx);
self.run = ctx.add_cancel(); self.run = ctx.add_cancel();
let ctx = ctx.freeze(); let ctx = ctx.freeze();
// Process prepared values // Process prepared values
@ -145,35 +145,35 @@ impl Iterator {
} }
#[inline] #[inline]
fn output_split(&mut self, ctx: &Runtime, opt: &Options, txn: &Transaction) { fn output_split(&mut self, _ctx: &Runtime, _opt: &Options, _txn: &Transaction) {
if self.stm.split().is_some() { if self.stm.split().is_some() {
// Ignore // Ignore
} }
} }
#[inline] #[inline]
fn output_group(&mut self, ctx: &Runtime, opt: &Options, txn: &Transaction) { fn output_group(&mut self, _ctx: &Runtime, _opt: &Options, _txn: &Transaction) {
if self.stm.group().is_some() { if self.stm.group().is_some() {
// Ignore // Ignore
} }
} }
#[inline] #[inline]
fn output_order(&mut self, ctx: &Runtime, opt: &Options, txn: &Transaction) { fn output_order(&mut self, _ctx: &Runtime, _opt: &Options, _txn: &Transaction) {
if self.stm.order().is_some() { if self.stm.order().is_some() {
// Ignore // Ignore
} }
} }
#[inline] #[inline]
fn output_start(&mut self, ctx: &Runtime, opt: &Options, txn: &Transaction) { fn output_start(&mut self, _ctx: &Runtime, _opt: &Options, _txn: &Transaction) {
if let Some(v) = self.stm.start() { if let Some(v) = self.stm.start() {
self.results = mem::take(&mut self.results).into_iter().skip(v.0).collect(); self.results = mem::take(&mut self.results).into_iter().skip(v.0).collect();
} }
} }
#[inline] #[inline]
fn output_limit(&mut self, ctx: &Runtime, opt: &Options, txn: &Transaction) { fn output_limit(&mut self, _ctx: &Runtime, _opt: &Options, _txn: &Transaction) {
if let Some(v) = self.stm.limit() { if let Some(v) = self.stm.limit() {
self.results = mem::take(&mut self.results).into_iter().take(v.0).collect(); self.results = mem::take(&mut self.results).into_iter().take(v.0).collect();
} }
@ -311,18 +311,14 @@ impl Iterator {
Ok(v) => self.results.push(v), Ok(v) => self.results.push(v),
} }
// Check if we can exit // Check if we can exit
if self.stm.group().is_none() { if self.stm.group().is_none() && self.stm.order().is_none() {
if self.stm.order().is_none() { if let Some(l) = self.stm.limit() {
if let Some(l) = self.stm.limit() { if let Some(s) = self.stm.start() {
if let Some(s) = self.stm.start() { if self.results.len() == l.0 + s.0 {
if self.results.len() == l.0 + s.0 { self.run.cancel()
self.run.cancel()
}
} else {
if self.results.len() == l.0 {
self.run.cancel()
}
} }
} else if self.results.len() == l.0 {
self.run.cancel()
} }
} }
} }

View file

@ -166,7 +166,7 @@ impl Options {
// Check whether the authentication permissions are ok // Check whether the authentication permissions are ok
pub fn check(&self, level: Level) -> Result<(), Error> { pub fn check(&self, level: Level) -> Result<(), Error> {
if self.auth.check(level) == false { if !self.auth.check(level) {
return Err(Error::QueryPermissionsError); return Err(Error::QueryPermissionsError);
} }
if self.ns.is_none() { if self.ns.is_none() {

View file

@ -35,15 +35,15 @@ impl Session {
} }
} }
impl Into<Value> for &Session { impl From<&Session> for Value {
fn into(self) -> Value { fn from(val: &Session) -> Value {
Value::from(map! { Value::from(map! {
"ip".to_string() => self.ip.to_owned().into(), "ip".to_string() => val.ip.to_owned().into(),
"or".to_string() => self.or.to_owned().into(), "or".to_string() => val.or.to_owned().into(),
"id".to_string() => self.id.to_owned().into(), "id".to_string() => val.id.to_owned().into(),
"ns".to_string() => self.ns.to_owned().into(), "ns".to_string() => val.ns.to_owned().into(),
"db".to_string() => self.db.to_owned().into(), "db".to_string() => val.db.to_owned().into(),
"sc".to_string() => self.sc.to_owned().into(), "sc".to_string() => val.sc.to_owned().into(),
}) })
} }
} }

View file

@ -82,42 +82,42 @@ impl fmt::Display for Statement {
impl Statement { impl Statement {
// Returns any SPLIT clause if specified // Returns any SPLIT clause if specified
pub fn split<'a>(self: &'a Statement) -> Option<&'a Splits> { pub fn split(self: &Statement) -> Option<&Splits> {
match self { match self {
Statement::Select(v) => v.split.as_ref(), Statement::Select(v) => v.split.as_ref(),
_ => None, _ => None,
} }
} }
// Returns any GROUP clause if specified // Returns any GROUP clause if specified
pub fn group<'a>(self: &'a Statement) -> Option<&'a Groups> { pub fn group(self: &Statement) -> Option<&Groups> {
match self { match self {
Statement::Select(v) => v.group.as_ref(), Statement::Select(v) => v.group.as_ref(),
_ => None, _ => None,
} }
} }
// Returns any ORDER clause if specified // Returns any ORDER clause if specified
pub fn order<'a>(self: &'a Statement) -> Option<&'a Orders> { pub fn order(self: &Statement) -> Option<&Orders> {
match self { match self {
Statement::Select(v) => v.order.as_ref(), Statement::Select(v) => v.order.as_ref(),
_ => None, _ => None,
} }
} }
// Returns any START clause if specified // Returns any START clause if specified
pub fn start<'a>(self: &'a Statement) -> Option<&'a Start> { pub fn start(self: &Statement) -> Option<&Start> {
match self { match self {
Statement::Select(v) => v.start.as_ref(), Statement::Select(v) => v.start.as_ref(),
_ => None, _ => None,
} }
} }
// Returns any LIMIT clause if specified // Returns any LIMIT clause if specified
pub fn limit<'a>(self: &'a Statement) -> Option<&'a Limit> { pub fn limit(self: &Statement) -> Option<&Limit> {
match self { match self {
Statement::Select(v) => v.limit.as_ref(), Statement::Select(v) => v.limit.as_ref(),
_ => None, _ => None,
} }
} }
// Returns any VERSION clause if specified // Returns any VERSION clause if specified
pub fn version<'a>(self: &'a Statement) -> Option<&'a Version> { pub fn version(self: &Statement) -> Option<&Version> {
match self { match self {
Statement::Select(v) => v.version.as_ref(), Statement::Select(v) => v.version.as_ref(),
_ => None, _ => None,

View file

@ -9,9 +9,9 @@ pub struct Document<'a> {
pub(super) initial: Cow<'a, Value>, pub(super) initial: Cow<'a, Value>,
} }
impl<'a> Into<Vec<u8>> for &Document<'a> { impl<'a> From<&Document<'a>> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: &Document<'a>) -> Vec<u8> {
msgpack::to_vec(&self.current).unwrap() msgpack::to_vec(&val.current).unwrap()
} }
} }

View file

@ -26,10 +26,9 @@ impl<'a> Document<'a> {
}; };
// Set default field values // Set default field values
self.current.to_mut().def(ctx, opt, txn, id).await?; self.current.to_mut().def(ctx, opt, txn, id).await?;
// Check for a data clause // The statement has a data clause
match data { if let Some(v) = data {
// The statement has a data clause match v {
Some(v) => match v {
Data::SetExpression(x) => { Data::SetExpression(x) => {
for x in x.iter() { for x in x.iter() {
let v = x.2.compute(ctx, opt, txn, Some(&self.current)).await?; let v = x.2.compute(ctx, opt, txn, Some(&self.current)).await?;
@ -59,9 +58,7 @@ impl<'a> Document<'a> {
self.current.to_mut().replace(ctx, opt, txn, v).await? self.current.to_mut().replace(ctx, opt, txn, v).await?
} }
_ => unreachable!(), _ => unreachable!(),
}, };
// No data clause has been set
None => (),
}; };
// Set default field values // Set default field values
self.current.to_mut().def(ctx, opt, txn, id).await?; self.current.to_mut().def(ctx, opt, txn, id).await?;

View file

@ -42,7 +42,7 @@ impl<'a> Document<'a> {
true => self.current.compute(ctx, opt, txn, Some(&self.current)).await?, true => self.current.compute(ctx, opt, txn, Some(&self.current)).await?,
false => Value::base(), false => Value::base(),
}; };
for v in v.iter() { for v in v.other() {
match v { match v {
Field::All => (), Field::All => (),
Field::Alone(v) => { Field::Alone(v) => {
@ -64,7 +64,7 @@ impl<'a> Document<'a> {
true => self.current.compute(ctx, opt, txn, Some(&self.current)).await?, true => self.current.compute(ctx, opt, txn, Some(&self.current)).await?,
false => Value::base(), false => Value::base(),
}; };
for v in stm.expr.iter() { for v in stm.expr.other() {
match v { match v {
Field::All => (), Field::All => (),
Field::Alone(v) => { Field::Alone(v) => {

View file

@ -9,8 +9,8 @@ impl<'a> Document<'a> {
pub async fn store( pub async fn store(
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, _opt: &Options,
txn: &Transaction, _txn: &Transaction,
_stm: &Statement, _stm: &Statement,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())

View file

@ -16,7 +16,7 @@ pub enum Args {
pub fn check( pub fn check(
ctx: &Runtime, ctx: &Runtime,
name: &String, name: &str,
args: Vec<Value>, args: Vec<Value>,
size: Args, size: Args,
func: fn(&Runtime, Vec<Value>) -> Result<Value, Error>, func: fn(&Runtime, Vec<Value>) -> Result<Value, Error>,

View file

@ -3,8 +3,8 @@ use crate::err::Error;
use crate::sql::number::Number; use crate::sql::number::Number;
use crate::sql::value::Value; use crate::sql::value::Value;
pub fn run(ctx: &Runtime, name: &String, val: Value) -> Result<Value, Error> { pub fn run(ctx: &Runtime, name: &str, val: Value) -> Result<Value, Error> {
match name.as_str() { match name {
"bool" => bool(ctx, val), "bool" => bool(ctx, val),
"int" => int(ctx, val), "int" => int(ctx, val),
"float" => float(ctx, val), "float" => float(ctx, val),

View file

@ -100,7 +100,7 @@ pub mod hash {
_ => Ok(Value::None), _ => Ok(Value::None),
}, },
1 => match args.remove(0) { 1 => match args.remove(0) {
Value::Geometry(Geometry::Point(v)) => Ok(geo::encode(v, 12 as usize).into()), Value::Geometry(Geometry::Point(v)) => Ok(geo::encode(v, 12).into()),
_ => Ok(Value::None), _ => Ok(Value::None),
}, },
_ => unreachable!(), _ => unreachable!(),

View file

@ -22,9 +22,10 @@ pub fn abs(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn bottom(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn bottom(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.remove(0) { match args.remove(0) {
Value::Array(v) => match args.remove(0).as_int() { Value::Array(v) => {
c => Ok(v.as_numbers().bottom(c).into()), let c = args.remove(0).as_int();
}, Ok(v.as_numbers().bottom(c).into())
}
_ => Ok(Value::None), _ => Ok(Value::None),
} }
} }
@ -34,14 +35,13 @@ pub fn ceil(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
} }
pub fn fixed(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn fixed(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.remove(0) { let v = args.remove(0);
v => match args.remove(0).as_int() { match args.remove(0).as_int() {
p if p > 0 => Ok(v.as_number().fixed(p as usize).into()), p if p > 0 => Ok(v.as_number().fixed(p as usize).into()),
_ => Err(Error::ArgumentsError { _ => Err(Error::ArgumentsError {
name: String::from("math::fixed"), name: String::from("math::fixed"),
message: String::from("The second argument must be an integer greater than 0."), message: String::from("The second argument must be an integer greater than 0."),
}), }),
},
} }
} }
@ -156,9 +156,10 @@ pub fn sum(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn top(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn top(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.remove(0) { match args.remove(0) {
Value::Array(v) => match args.remove(0).as_int() { Value::Array(v) => {
c => Ok(v.as_numbers().top(c).into()), let c = args.remove(0).as_int();
}, Ok(v.as_numbers().top(c).into())
}
_ => Ok(Value::None), _ => Ok(Value::None),
} }
} }

View file

@ -22,8 +22,8 @@ pub mod time;
pub mod r#type; pub mod r#type;
pub mod util; pub mod util;
pub async fn run(ctx: &Runtime, name: &String, args: Vec<Value>) -> Result<Value, Error> { pub async fn run(ctx: &Runtime, name: &str, args: Vec<Value>) -> Result<Value, Error> {
match name.as_ref() { match name {
// //
"array::combine" => args::check(ctx, name, args, Args::Two, array::combine), "array::combine" => args::check(ctx, name, args, Args::Two, array::combine),
"array::concat" => args::check(ctx, name, args, Args::Two, array::concat), "array::concat" => args::check(ctx, name, args, Args::Two, array::concat),

View file

@ -38,12 +38,13 @@ pub fn r#enum(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn float(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn float(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.len() { match args.len() {
2 => match args.remove(0).as_float() { 2 => {
min => match args.remove(0).as_float() { let min = args.remove(0).as_float();
match args.remove(0).as_float() {
max if max < min => Ok(rand::thread_rng().gen_range(max..=min).into()), max if max < min => Ok(rand::thread_rng().gen_range(max..=min).into()),
max => Ok(rand::thread_rng().gen_range(min..=max).into()), max => Ok(rand::thread_rng().gen_range(min..=max).into()),
}, }
}, }
0 => Ok(rand::random::<f64>().into()), 0 => Ok(rand::random::<f64>().into()),
_ => unreachable!(), _ => unreachable!(),
} }
@ -51,9 +52,10 @@ pub fn float(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn guid(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn guid(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.len() { match args.len() {
1 => match args.remove(0).as_int() as usize { 1 => {
len => Ok(nanoid!(len, &ID_CHARS).into()), let len = args.remove(0).as_int() as usize;
}, Ok(nanoid!(len, &ID_CHARS).into())
}
0 => Ok(nanoid!(20, &ID_CHARS).into()), 0 => Ok(nanoid!(20, &ID_CHARS).into()),
_ => unreachable!(), _ => unreachable!(),
} }
@ -61,12 +63,13 @@ pub fn guid(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn int(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn int(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.len() { match args.len() {
2 => match args.remove(0).as_int() { 2 => {
min => match args.remove(0).as_int() { let min = args.remove(0).as_int();
match args.remove(0).as_int() {
max if max < min => Ok(rand::thread_rng().gen_range(max..=min).into()), max if max < min => Ok(rand::thread_rng().gen_range(max..=min).into()),
max => Ok(rand::thread_rng().gen_range(min..=max).into()), max => Ok(rand::thread_rng().gen_range(min..=max).into()),
}, }
}, }
0 => Ok(rand::random::<i64>().into()), 0 => Ok(rand::random::<i64>().into()),
_ => unreachable!(), _ => unreachable!(),
} }
@ -122,8 +125,9 @@ pub fn string(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn time(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn time(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.len() { match args.len() {
2 => match args.remove(0).as_int() { 2 => {
min => match args.remove(0).as_int() { let min = args.remove(0).as_int();
match args.remove(0).as_int() {
max if max < min => { max if max < min => {
let i = rand::thread_rng().gen_range(max..=min); let i = rand::thread_rng().gen_range(max..=min);
Ok(Datetime::from(i).into()) Ok(Datetime::from(i).into())
@ -132,8 +136,8 @@ pub fn time(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
let i = rand::thread_rng().gen_range(min..=max); let i = rand::thread_rng().gen_range(min..=max);
Ok(Datetime::from(i).into()) Ok(Datetime::from(i).into())
} }
}, }
}, }
0 => { 0 => {
let i = rand::random::<i64>(); let i = rand::random::<i64>();
Ok(Datetime::from(i).into()) Ok(Datetime::from(i).into())

View file

@ -3,7 +3,7 @@ use crate::err::Error;
use crate::sql::script::Script; use crate::sql::script::Script;
use crate::sql::value::Value; use crate::sql::value::Value;
pub fn run(ctx: &Runtime, expr: Script) -> Result<Value, Error> { pub fn run(_ctx: &Runtime, _expr: Script) -> Result<Value, Error> {
Err(Error::LanguageError { Err(Error::LanguageError {
message: String::from("Embedded functions are not yet supported."), message: String::from("Embedded functions are not yet supported."),
}) })

View file

@ -95,5 +95,5 @@ pub fn uppercase(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
} }
pub fn words(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn words(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
Ok(args.remove(0).as_strand().value.split(" ").collect::<Vec<&str>>().into()) Ok(args.remove(0).as_strand().value.split(' ').collect::<Vec<&str>>().into())
} }

View file

@ -63,17 +63,14 @@ pub fn number(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
pub fn point(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn point(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
match args.len() { match args.len() {
2 => match args.remove(0) { 2 => {
x => match args.remove(0) { let x = args.remove(0);
y => Ok((x.as_float(), y.as_float()).into()), let y = args.remove(0);
}, Ok((x.as_float(), y.as_float()).into())
}, }
1 => match args.remove(0) { 1 => match args.remove(0) {
Value::Array(v) if v.len() == 2 => Ok(v.as_point().into()), Value::Array(v) if v.len() == 2 => Ok(v.as_point().into()),
Value::Geometry(v) => match v { Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
Geometry::Point(v) => Ok(v.into()),
_ => Ok(Value::None),
},
_ => Ok(Value::None), _ => Ok(Value::None),
}, },
_ => unreachable!(), _ => unreachable!(),
@ -102,16 +99,15 @@ pub fn table(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
} }
pub fn thing(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> { pub fn thing(_: &Runtime, mut args: Vec<Value>) -> Result<Value, Error> {
let tb = args.remove(0);
match args.remove(0) { match args.remove(0) {
tb => match args.remove(0) { Value::Thing(id) => Ok(Value::Thing(Thing {
Value::Thing(id) => Ok(Value::Thing(Thing { tb: tb.as_strand().value,
tb: tb.as_strand().value, id: id.id,
id: id.id, })),
})), id => Ok(Value::Thing(Thing {
id => Ok(Value::Thing(Thing { tb: tb.as_strand().value,
tb: tb.as_strand().value, id: id.as_strand().value,
id: id.as_strand().value, })),
})),
},
} }
} }

View file

@ -4,7 +4,6 @@ use serde::de::{Deserialize, Visitor};
use std; use std;
use std::fmt; use std::fmt;
use std::io::{self, Read}; use std::io::{self, Read};
use std::mem::transmute;
use std::str; use std::str;
use std::{i16, i32, i64, i8}; use std::{i16, i32, i64, i8};
use thiserror::Error; use thiserror::Error;
@ -110,10 +109,7 @@ where
where where
V: Visitor<'de>, V: Visitor<'de>,
{ {
let b = match self.reader.read_u8()? { let b = !matches!(self.reader.read_u8()?, 0);
0 => false,
_ => true,
};
visitor.visit_bool(b) visitor.visit_bool(b)
} }
@ -187,7 +183,7 @@ where
{ {
let val = self.reader.read_i32::<BE>()?; let val = self.reader.read_i32::<BE>()?;
let t = ((val ^ i32::MIN) >> 31) | i32::MIN; let t = ((val ^ i32::MIN) >> 31) | i32::MIN;
let f: f32 = unsafe { transmute(val ^ t) }; let f: f32 = f32::from_bits((val ^ t) as u32);
visitor.visit_f32(f) visitor.visit_f32(f)
} }
@ -197,7 +193,7 @@ where
{ {
let val = self.reader.read_i64::<BE>()?; let val = self.reader.read_i64::<BE>()?;
let t = ((val ^ i64::MIN) >> 63) | i64::MIN; let t = ((val ^ i64::MIN) >> 63) | i64::MIN;
let f: f64 = unsafe { transmute(val ^ t) }; let f: f64 = f64::from_bits((val ^ t) as u64);
visitor.visit_f64(f) visitor.visit_f64(f)
} }
@ -211,7 +207,7 @@ where
Ok(_) => match str::from_utf8(&buffer) { Ok(_) => match str::from_utf8(&buffer) {
Ok(mut s) => { Ok(mut s) => {
const EOF: char = '\u{0}'; const EOF: char = '\u{0}';
const EOF_STR: &'static str = "\u{0}"; const EOF_STR: &str = "\u{0}";
if s.len() >= EOF.len_utf8() { if s.len() >= EOF.len_utf8() {
let eof_start = s.len() - EOF.len_utf8(); let eof_start = s.len() - EOF.len_utf8();
if &s[eof_start..] == EOF_STR { if &s[eof_start..] == EOF_STR {
@ -220,9 +216,9 @@ where
} }
string.push_str(s) string.push_str(s)
} }
Err(e) => panic!("1"), Err(_) => panic!("1"),
}, },
Err(e) => panic!("2"), Err(_) => panic!("2"),
} }
visitor.visit_string(string) visitor.visit_string(string)
} }
@ -237,7 +233,7 @@ where
Ok(_) => match str::from_utf8(&buffer) { Ok(_) => match str::from_utf8(&buffer) {
Ok(mut s) => { Ok(mut s) => {
const EOF: char = '\u{0}'; const EOF: char = '\u{0}';
const EOF_STR: &'static str = "\u{0}"; const EOF_STR: &str = "\u{0}";
if s.len() >= EOF.len_utf8() { if s.len() >= EOF.len_utf8() {
let eof_start = s.len() - EOF.len_utf8(); let eof_start = s.len() - EOF.len_utf8();
if &s[eof_start..] == EOF_STR { if &s[eof_start..] == EOF_STR {
@ -246,9 +242,9 @@ where
} }
string.push_str(s) string.push_str(s)
} }
Err(e) => panic!("1"), Err(_) => panic!("1"),
}, },
Err(e) => panic!("2"), Err(_) => panic!("2"),
} }
visitor.visit_string(string) visitor.visit_string(string)
} }

View file

@ -2,7 +2,6 @@ use byteorder::{WriteBytesExt, BE};
use serde::{self, Serialize}; use serde::{self, Serialize};
use std::fmt; use std::fmt;
use std::io::{self, Write}; use std::io::{self, Write};
use std::mem::transmute;
use std::{self, i16, i32, i64, i8}; use std::{self, i16, i32, i64, i8};
use thiserror::Error; use thiserror::Error;
@ -405,14 +404,14 @@ where
} }
fn serialize_f32(self, v: f32) -> Result<()> { fn serialize_f32(self, v: f32) -> Result<()> {
let val = unsafe { transmute::<f32, i32>(v) }; let val = v.to_bits() as i32;
let t = (val >> 31) | i32::MIN; let t = (val >> 31) | i32::MIN;
self.writer.write_i32::<BE>(val ^ t)?; self.writer.write_i32::<BE>(val ^ t)?;
Ok(()) Ok(())
} }
fn serialize_f64(self, v: f64) -> Result<()> { fn serialize_f64(self, v: f64) -> Result<()> {
let val = unsafe { transmute::<f64, i64>(v) }; let val = v.to_bits() as i64;
let t = (val >> 63) | i64::MIN; let t = (val >> 63) | i64::MIN;
self.writer.write_i64::<BE>(val ^ t)?; self.writer.write_i64::<BE>(val ^ t)?;
Ok(()) Ok(())

View file

@ -12,9 +12,9 @@ pub struct Database {
db: String, db: String,
} }
impl Into<Vec<u8>> for Database { impl From<Database> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Database) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -12,9 +12,9 @@ pub struct Db {
db: String, db: String,
} }
impl Into<Vec<u8>> for Db { impl From<Db> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Db) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -14,9 +14,9 @@ pub struct Dl {
us: String, us: String,
} }
impl Into<Vec<u8>> for Dl { impl From<Dl> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Dl) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -14,9 +14,9 @@ pub struct Dt {
tk: String, tk: String,
} }
impl Into<Vec<u8>> for Dt { impl From<Dt> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Dt) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct Ev {
ev: String, ev: String,
} }
impl Into<Vec<u8>> for Ev { impl From<Ev> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Ev) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct Fd {
fd: String, fd: String,
} }
impl Into<Vec<u8>> for Fd { impl From<Fd> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Fd) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct Ft {
ft: String, ft: String,
} }
impl Into<Vec<u8>> for Ft { impl From<Ft> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Ft) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -18,9 +18,9 @@ pub struct Index {
fd: Value, fd: Value,
} }
impl Into<Vec<u8>> for Index { impl From<Index> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Index) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct Ix {
ix: String, ix: String,
} }
impl Into<Vec<u8>> for Ix { impl From<Ix> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Ix) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -4,13 +4,13 @@ use crate::key::bytes::{deserialize, serialize};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
// Default base key // Default base key
pub const BASE: &'static str = "surreal"; pub const BASE: &str = "surreal";
// Ignore specifies an ignored field // Ignore specifies an ignored field
pub const IGNORE: &'static str = "\x00"; pub const IGNORE: &str = "\x00";
// Prefix is the lowest char found in a key // Prefix is the lowest char found in a key
pub const PREFIX: &'static str = "\x01"; pub const PREFIX: &str = "\x01";
// Suffix is the highest char found in a key // Suffix is the highest char found in a key
pub const SUFFIX: &'static str = "\x7f"; pub const SUFFIX: &str = "\x7f";
/// KV {$kv} /// KV {$kv}
/// NS {$kv}!ns{$ns} /// NS {$kv}!ns{$ns}
@ -68,9 +68,9 @@ pub enum Key {
Edge, // Edge resource data key Edge, // Edge resource data key
} }
impl Into<Vec<u8>> for Key { impl From<Key> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Key) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct Lv {
lv: String, lv: String,
} }
impl Into<Vec<u8>> for Lv { impl From<Lv> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Lv) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -10,9 +10,9 @@ pub struct Namespace {
ns: String, ns: String,
} }
impl Into<Vec<u8>> for Namespace { impl From<Namespace> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Namespace) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -12,9 +12,9 @@ pub struct Nl {
us: String, us: String,
} }
impl Into<Vec<u8>> for Nl { impl From<Nl> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Nl) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -10,9 +10,9 @@ pub struct Ns {
ns: String, ns: String,
} }
impl Into<Vec<u8>> for Ns { impl From<Ns> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Ns) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -12,9 +12,9 @@ pub struct Nt {
tk: String, tk: String,
} }
impl Into<Vec<u8>> for Nt { impl From<Nt> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Nt) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -5,7 +5,7 @@ use crate::sql::value::Value;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize)] #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Index { pub struct Point {
kv: String, kv: String,
_a: String, _a: String,
ns: String, ns: String,
@ -19,25 +19,25 @@ pub struct Index {
id: String, id: String,
} }
impl Into<Vec<u8>> for Index { impl From<Point> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Point) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }
impl From<Vec<u8>> for Index { impl From<Vec<u8>> for Point {
fn from(val: Vec<u8>) -> Self { fn from(val: Vec<u8>) -> Self {
Index::decode(&val).unwrap() Point::decode(&val).unwrap()
} }
} }
pub fn new(ns: &str, db: &str, tb: &str, ix: &str, fd: Value, id: &str) -> Index { pub fn new(ns: &str, db: &str, tb: &str, ix: &str, fd: Value, id: &str) -> Point {
Index::new(ns.to_string(), db.to_string(), tb.to_string(), ix.to_string(), fd, id.to_string()) Point::new(ns.to_string(), db.to_string(), tb.to_string(), ix.to_string(), fd, id.to_string())
} }
impl Index { impl Point {
pub fn new(ns: String, db: String, tb: String, ix: String, fd: Value, id: String) -> Index { pub fn new(ns: String, db: String, tb: String, ix: String, fd: Value, id: String) -> Point {
Index { Point {
kv: BASE.to_owned(), kv: BASE.to_owned(),
_a: String::from("*"), _a: String::from("*"),
ns, ns,
@ -54,7 +54,7 @@ impl Index {
pub fn encode(&self) -> Result<Vec<u8>, Error> { pub fn encode(&self) -> Result<Vec<u8>, Error> {
Ok(serialize(self)?) Ok(serialize(self)?)
} }
pub fn decode(v: &[u8]) -> Result<Index, Error> { pub fn decode(v: &[u8]) -> Result<Point, Error> {
Ok(deserialize(v)?) Ok(deserialize(v)?)
} }
} }
@ -65,7 +65,7 @@ mod tests {
fn key() { fn key() {
use super::*; use super::*;
#[rustfmt::skip] #[rustfmt::skip]
let val = Index::new( let val = Point::new(
"test".to_string(), "test".to_string(),
"test".to_string(), "test".to_string(),
"test".to_string(), "test".to_string(),
@ -73,8 +73,8 @@ mod tests {
"test".into(), "test".into(),
"test".into(), "test".into(),
); );
let enc = Index::encode(&val).unwrap(); let enc = Point::encode(&val).unwrap();
let dec = Index::decode(&enc).unwrap(); let dec = Point::decode(&enc).unwrap();
assert_eq!(val, dec); assert_eq!(val, dec);
} }
} }

View file

@ -14,9 +14,9 @@ pub struct Sc {
sc: String, sc: String,
} }
impl Into<Vec<u8>> for Sc { impl From<Sc> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Sc) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct St {
tk: String, tk: String,
} }
impl Into<Vec<u8>> for St { impl From<St> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: St) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -14,9 +14,9 @@ pub struct Table {
tb: String, tb: String,
} }
impl Into<Vec<u8>> for Table { impl From<Table> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Table) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -14,9 +14,9 @@ pub struct Tb {
tb: String, tb: String,
} }
impl Into<Vec<u8>> for Tb { impl From<Tb> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Tb) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -16,9 +16,9 @@ pub struct Thing {
id: String, id: String,
} }
impl Into<Vec<u8>> for Thing { impl From<Thing> for Vec<u8> {
fn into(self) -> Vec<u8> { fn from(val: Thing) -> Vec<u8> {
self.encode().unwrap() val.encode().unwrap()
} }
} }

View file

@ -46,7 +46,7 @@ impl Transaction {
// Cancel a transaction // Cancel a transaction
pub fn cancel(&mut self) -> Result<(), Error> { pub fn cancel(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -59,11 +59,11 @@ impl Transaction {
// Commit a transaction // Commit a transaction
pub fn commit(&mut self) -> Result<(), Error> { pub fn commit(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -79,11 +79,11 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Remove the key // Remove the key
@ -97,7 +97,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check the key // Check the key
@ -111,7 +111,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Get the key // Get the key
@ -126,11 +126,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -145,11 +145,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -163,7 +163,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Convert the range to bytes // Convert the range to bytes

View file

@ -46,7 +46,7 @@ impl Transaction {
// Cancel a transaction // Cancel a transaction
pub async fn cancel(&mut self) -> Result<(), Error> { pub async fn cancel(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -59,11 +59,11 @@ impl Transaction {
// Commit a transaction // Commit a transaction
pub async fn commit(&mut self) -> Result<(), Error> { pub async fn commit(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -79,11 +79,11 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Remove the key // Remove the key
@ -97,7 +97,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check the key // Check the key
@ -111,7 +111,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Get the key // Get the key
@ -126,11 +126,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -145,11 +145,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -163,7 +163,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Convert the range to bytes // Convert the range to bytes

View file

@ -46,7 +46,7 @@ impl Transaction {
// Cancel a transaction // Cancel a transaction
pub fn cancel(&mut self) -> Result<(), Error> { pub fn cancel(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -59,11 +59,11 @@ impl Transaction {
// Commit a transaction // Commit a transaction
pub fn commit(&mut self) -> Result<(), Error> { pub fn commit(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -79,11 +79,11 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Remove the key // Remove the key
@ -97,7 +97,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check the key // Check the key
@ -111,7 +111,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Get the key // Get the key
@ -126,11 +126,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -145,11 +145,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -163,7 +163,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Convert the range to bytes // Convert the range to bytes

View file

@ -56,7 +56,7 @@ impl Transaction {
// Cancel a transaction // Cancel a transaction
pub async fn cancel(&mut self) -> Result<(), Error> { pub async fn cancel(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -69,11 +69,11 @@ impl Transaction {
// Commit a transaction // Commit a transaction
pub async fn commit(&mut self) -> Result<(), Error> { pub async fn commit(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Mark this transaction as done // Mark this transaction as done
@ -89,11 +89,11 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Delete the key // Delete the key
@ -107,7 +107,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check the key // Check the key
@ -121,7 +121,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Get the key // Get the key
@ -136,11 +136,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -155,11 +155,11 @@ impl Transaction {
V: Into<Val>, V: Into<Val>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Check to see if transaction is writable // Check to see if transaction is writable
if self.rw == false { if !self.rw {
return Err(Error::TxReadonlyError); return Err(Error::TxReadonlyError);
} }
// Set the key // Set the key
@ -173,7 +173,7 @@ impl Transaction {
K: Into<Key>, K: Into<Key>,
{ {
// Check to see if transaction is closed // Check to see if transaction is closed
if self.ok == true { if self.ok {
return Err(Error::TxFinishedError); return Err(Error::TxFinishedError);
} }
// Convert the range to bytes // Convert the range to bytes

View file

@ -57,7 +57,7 @@ impl From<Vec<Vec<Value>>> for Array {
impl<'a> From<Vec<&str>> for Array { impl<'a> From<Vec<&str>> for Array {
fn from(v: Vec<&str>) -> Self { fn from(v: Vec<&str>) -> Self {
Array { Array {
value: v.into_iter().map(|v| Value::from(v)).collect(), value: v.into_iter().map(Value::from).collect(),
} }
} }
} }
@ -65,7 +65,7 @@ impl<'a> From<Vec<&str>> for Array {
impl From<Vec<Operation>> for Array { impl From<Vec<Operation>> for Array {
fn from(v: Vec<Operation>) -> Self { fn from(v: Vec<Operation>) -> Self {
Array { Array {
value: v.into_iter().map(|v| Value::from(v)).collect(), value: v.into_iter().map(Value::from).collect(),
} }
} }
} }
@ -75,6 +75,10 @@ impl Array {
self.value.len() self.value.len()
} }
pub fn is_empty(&self) -> bool {
self.value.is_empty()
}
pub fn as_ints(self) -> Vec<i64> { pub fn as_ints(self) -> Vec<i64> {
self.value.into_iter().map(|v| v.as_int()).collect() self.value.into_iter().map(|v| v.as_int()).collect()
} }
@ -163,7 +167,7 @@ impl Serialize for Array {
impl ops::Add<Value> for Array { impl ops::Add<Value> for Array {
type Output = Self; type Output = Self;
fn add(mut self, other: Value) -> Self { fn add(mut self, other: Value) -> Self {
if self.value.iter().position(|x| *x == other).is_none() { if !self.value.iter().any(|x| *x == other) {
self.value.push(other) self.value.push(other)
} }
self self
@ -174,7 +178,7 @@ impl ops::Add for Array {
type Output = Self; type Output = Self;
fn add(mut self, other: Self) -> Self { fn add(mut self, other: Self) -> Self {
for v in other.value { for v in other.value {
if self.value.iter().position(|x| *x == v).is_none() { if !self.value.iter().any(|x| *x == v) {
self.value.push(v) self.value.push(v)
} }
} }

View file

@ -27,8 +27,7 @@ pub fn commas(i: &str) -> IResult<&str, ()> {
#[inline] #[inline]
pub fn is_digit(chr: char) -> bool { pub fn is_digit(chr: char) -> bool {
let chr = chr as u8; (0x30..=0x39).contains(&(chr as u8))
chr >= 0x30 && chr <= 0x39
} }
#[inline] #[inline]
@ -48,7 +47,7 @@ pub fn to_usize(s: &str) -> usize {
#[inline] #[inline]
pub fn val_char(chr: char) -> bool { pub fn val_char(chr: char) -> bool {
is_alphanumeric(chr as u8) || chr == '_' as char is_alphanumeric(chr as u8) || chr == '_'
} }
#[inline] #[inline]

View file

@ -37,14 +37,16 @@ impl Expression {
) -> Result<Value, Error> { ) -> Result<Value, Error> {
let l = self.l.compute(ctx, opt, txn, doc).await?; let l = self.l.compute(ctx, opt, txn, doc).await?;
match self.o { match self.o {
Operator::Or => match l.is_truthy() { Operator::Or => {
true => return Ok(l), // No need to continue if let true = l.is_truthy() {
_ => {} // Continue return Ok(l);
}, }
Operator::And => match l.is_truthy() { }
false => return Ok(l), // No need to continue Operator::And => {
_ => {} // Continue if let false = l.is_truthy() {
}, return Ok(l);
}
}
_ => {} // Continue _ => {} // Continue
} }
let r = self.r.compute(ctx, opt, txn, doc).await?; let r = self.r.compute(ctx, opt, txn, doc).await?;

View file

@ -14,19 +14,10 @@ pub struct Fields(pub Vec<Field>);
impl Fields { impl Fields {
pub fn all(&self) -> bool { pub fn all(&self) -> bool {
self.0.iter().any(|v| match v { self.0.iter().any(|v| matches!(v, Field::All))
Field::All => true,
_ => false,
})
}
pub fn iter(&self) -> impl Iterator<Item = &Field> {
self.0.iter()
} }
pub fn other(&self) -> impl Iterator<Item = &Field> { pub fn other(&self) -> impl Iterator<Item = &Field> {
self.0.iter().filter(|v| match v { self.0.iter().filter(|v| !matches!(v, Field::All))
Field::All => false,
_ => true,
})
} }
pub fn single(&self) -> Option<Idiom> { pub fn single(&self) -> Option<Idiom> {
match self.0.len() { match self.0.len() {

View file

@ -120,7 +120,7 @@ impl From<Geometry> for geo::Geometry<f64> {
Geometry::MultiPoint(v) => v.into(), Geometry::MultiPoint(v) => v.into(),
Geometry::MultiLine(v) => v.into(), Geometry::MultiLine(v) => v.into(),
Geometry::MultiPolygon(v) => v.into(), Geometry::MultiPolygon(v) => v.into(),
Geometry::Collection(v) => v.into_iter().collect::<geo::Geometry<f64>>().into(), Geometry::Collection(v) => v.into_iter().collect::<geo::Geometry<f64>>(),
} }
} }
} }
@ -273,7 +273,7 @@ impl fmt::Display for Geometry {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "), .join(", "),
match v.interiors().len() { match v.interiors().len() {
0 => format!(""), 0 => String::new(),
_ => format!( _ => format!(
", [{}]", ", [{}]",
v.interiors() v.interiors()
@ -328,7 +328,7 @@ impl fmt::Display for Geometry {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "), .join(", "),
match v.interiors().len() { match v.interiors().len() {
0 => format!(""), 0 => String::new(),
_ => format!( _ => format!(
", [{}]", ", [{}]",
v.interiors() v.interiors()
@ -403,7 +403,7 @@ impl Serialize for Geometry {
.into_iter() .into_iter()
.chain( .chain(
v.interiors() v.interiors()
.into_iter() .iter()
.map(|i| { .map(|i| {
i.points() i.points()
.map(|p| vec![p.x(), p.y()]) .map(|p| vec![p.x(), p.y()])

View file

@ -44,7 +44,7 @@ pub fn ident(i: &str) -> IResult<&str, Ident> {
pub fn ident_raw(i: &str) -> IResult<&str, String> { pub fn ident_raw(i: &str) -> IResult<&str, String> {
let (i, v) = alt((ident_default, ident_backtick, ident_brackets))(i)?; let (i, v) = alt((ident_default, ident_backtick, ident_brackets))(i)?;
Ok((i, String::from(v))) Ok((i, v))
} }
fn ident_default(i: &str) -> IResult<&str, String> { fn ident_default(i: &str) -> IResult<&str, String> {

View file

@ -55,8 +55,8 @@ pub fn kind(i: &str) -> IResult<&str, Kind> {
map(tag("number"), |_| Kind::Number), map(tag("number"), |_| Kind::Number),
map(tag("object"), |_| Kind::Object), map(tag("object"), |_| Kind::Object),
map(tag("string"), |_| Kind::String), map(tag("string"), |_| Kind::String),
map(geometry, |v| Kind::Geometry(v)), map(geometry, Kind::Geometry),
map(record, |v| Kind::Record(v)), map(record, Kind::Record),
))(i) ))(i)
} }

View file

@ -17,19 +17,13 @@ pub struct Model {
impl fmt::Display for Model { impl fmt::Display for Model {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.count { if let Some(ref c) = self.count {
Some(ref c) => { let t = escape(&self.table, &val_char, "`");
let t = escape(&self.table, &val_char, "`"); write!(f, "|{}:{}|", t, c)?;
write!(f, "|{}:{}|", t, c)?;
}
None => {}
} }
match self.range { if let Some((ref b, ref e)) = self.range {
Some((ref b, ref e)) => { let t = escape(&self.table, &val_char, "`");
let t = escape(&self.table, &val_char, "`"); write!(f, "|{}:{}..{}|", t, b, e)?;
write!(f, "|{}:{}..{}|", t, b, e)?;
}
None => {}
} }
Ok(()) Ok(())
} }

View file

@ -99,21 +99,21 @@ impl From<usize> for Number {
impl From<f32> for Number { impl From<f32> for Number {
fn from(f: f32) -> Self { fn from(f: f32) -> Self {
Number::Decimal(Decimal::from_f32(f).unwrap_or(Decimal::new(0, 0))) Number::Decimal(Decimal::from_f32(f).unwrap_or_default())
} }
} }
impl From<f64> for Number { impl From<f64> for Number {
fn from(f: f64) -> Self { fn from(f: f64) -> Self {
Number::Decimal(Decimal::from_f64(f).unwrap_or(Decimal::new(0, 0))) Number::Decimal(Decimal::from_f64(f).unwrap_or_default())
} }
} }
impl<'a> From<&'a str> for Number { impl<'a> From<&'a str> for Number {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
match s.contains(&['e', 'E'][..]) { match s.contains(&['e', 'E'][..]) {
true => Number::Decimal(Decimal::from_scientific(s).unwrap_or(Decimal::new(0, 0))), true => Number::Decimal(Decimal::from_scientific(s).unwrap_or_default()),
false => Number::Decimal(Decimal::from_str(s).unwrap_or(Decimal::new(0, 0))), false => Number::Decimal(Decimal::from_str(s).unwrap_or_default()),
} }
} }
} }
@ -121,8 +121,8 @@ impl<'a> From<&'a str> for Number {
impl From<String> for Number { impl From<String> for Number {
fn from(s: String) -> Self { fn from(s: String) -> Self {
match s.contains(&['e', 'E'][..]) { match s.contains(&['e', 'E'][..]) {
true => Number::Decimal(Decimal::from_scientific(&s).unwrap_or(Decimal::new(0, 0))), true => Number::Decimal(Decimal::from_scientific(&s).unwrap_or_default()),
false => Number::Decimal(Decimal::from_str(&s).unwrap_or(Decimal::new(0, 0))), false => Number::Decimal(Decimal::from_str(&s).unwrap_or_default()),
} }
} }
} }
@ -173,7 +173,7 @@ impl Number {
match self { match self {
Number::Int(v) => v != &0, Number::Int(v) => v != &0,
Number::Float(v) => v != &0.0, Number::Float(v) => v != &0.0,
Number::Decimal(v) => v != &Decimal::new(0, 0), Number::Decimal(v) => v != &Decimal::default(),
} }
} }
@ -200,7 +200,7 @@ impl Number {
pub fn as_decimal(self) -> Decimal { pub fn as_decimal(self) -> Decimal {
match self { match self {
Number::Int(v) => Decimal::from(v), Number::Int(v) => Decimal::from(v),
Number::Float(v) => Decimal::from_f64(v).unwrap_or(Decimal::new(0, 0)), Number::Float(v) => Decimal::from_f64(v).unwrap_or_default(),
Number::Decimal(v) => v, Number::Decimal(v) => v,
} }
} }
@ -236,7 +236,7 @@ impl Number {
pub fn to_decimal(&self) -> Decimal { pub fn to_decimal(&self) -> Decimal {
match self { match self {
Number::Int(v) => Decimal::from(*v), Number::Int(v) => Decimal::from(*v),
Number::Float(v) => Decimal::from_f64(*v).unwrap_or(Decimal::new(0, 0)), Number::Float(v) => Decimal::from_f64(*v).unwrap_or_default(),
Number::Decimal(v) => *v, Number::Decimal(v) => *v,
} }
} }
@ -281,7 +281,7 @@ impl Number {
match self { match self {
Number::Int(v) => (v as f64).sqrt().into(), Number::Int(v) => (v as f64).sqrt().into(),
Number::Float(v) => v.sqrt().into(), Number::Float(v) => v.sqrt().into(),
Number::Decimal(v) => v.sqrt().unwrap_or(Decimal::new(0, 0)).into(), Number::Decimal(v) => v.sqrt().unwrap_or_default().into(),
} }
} }
@ -302,7 +302,7 @@ impl Eq for Number {}
impl Ord for Number { impl Ord for Number {
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(&other).unwrap_or(Ordering::Equal) self.partial_cmp(other).unwrap_or(Ordering::Equal)
} }
} }
@ -320,10 +320,10 @@ impl PartialEq for Number {
(Number::Decimal(v), Number::Int(w)) => v.eq(&Decimal::from(*w)), (Number::Decimal(v), Number::Int(w)) => v.eq(&Decimal::from(*w)),
// ------------------------------ // ------------------------------
(Number::Float(v), Number::Decimal(w)) => { (Number::Float(v), Number::Decimal(w)) => {
Decimal::from_f64(*v).unwrap_or(Decimal::default()).eq(w) Decimal::from_f64(*v).unwrap_or_default().eq(w)
} }
(Number::Decimal(v), Number::Float(w)) => { (Number::Decimal(v), Number::Float(w)) => {
v.eq(&Decimal::from_f64(*w).unwrap_or(Decimal::default())) v.eq(&Decimal::from_f64(*w).unwrap_or_default())
} }
} }
} }
@ -343,10 +343,10 @@ impl PartialOrd for Number {
(Number::Decimal(v), Number::Int(w)) => v.partial_cmp(&Decimal::from(*w)), (Number::Decimal(v), Number::Int(w)) => v.partial_cmp(&Decimal::from(*w)),
// ------------------------------ // ------------------------------
(Number::Float(v), Number::Decimal(w)) => { (Number::Float(v), Number::Decimal(w)) => {
Decimal::from_f64(*v).unwrap_or(Decimal::default()).partial_cmp(w) Decimal::from_f64(*v).unwrap_or_default().partial_cmp(w)
} }
(Number::Decimal(v), Number::Float(w)) => { (Number::Decimal(v), Number::Float(w)) => {
v.partial_cmp(&Decimal::from_f64(*w).unwrap_or(Decimal::default())) v.partial_cmp(&Decimal::from_f64(*w).unwrap_or_default())
} }
} }
} }

View file

@ -61,13 +61,11 @@ impl From<Operation> for Object {
} }
impl Object { impl Object {
pub fn remove(&mut self, key: &String) { pub fn remove(&mut self, key: &str) {
self.value.remove(key); self.value.remove(key);
()
} }
pub fn insert(&mut self, key: &String, val: Value) { pub fn insert(&mut self, key: &str, val: Value) {
self.value.insert(key.to_owned(), val); self.value.insert(key.to_owned(), val);
()
} }
pub fn to_operation(&self) -> Result<Operation, Error> { pub fn to_operation(&self) -> Result<Operation, Error> {
match self.value.get("op") { match self.value.get("op") {
@ -119,7 +117,7 @@ impl fmt::Display for Object {
"{{ {} }}", "{{ {} }}",
self.value self.value
.iter() .iter()
.map(|(ref k, ref v)| format!("{}: {}", escape(&k, &val_char, "\""), v)) .map(|(k, v)| format!("{}: {}", escape(k, &val_char, "\""), v))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
) )

View file

@ -46,7 +46,7 @@ pub fn output(i: &str) -> IResult<&str, Output> {
map(tag_no_case("DIFF"), |_| Output::Diff), map(tag_no_case("DIFF"), |_| Output::Diff),
map(tag_no_case("AFTER"), |_| Output::After), map(tag_no_case("AFTER"), |_| Output::After),
map(tag_no_case("BEFORE"), |_| Output::Before), map(tag_no_case("BEFORE"), |_| Output::Before),
map(fields, |v| Output::Fields(v)), map(fields, Output::Fields),
))(i)?; ))(i)?;
Ok((i, v)) Ok((i, v))
} }

View file

@ -12,25 +12,27 @@ pub fn parse(input: &str) -> Result<Query, Error> {
_ => match query(input) { _ => match query(input) {
Ok((_, query)) => Ok(query), Ok((_, query)) => Ok(query),
Err(Err::Error(e)) => match e { Err(Err::Error(e)) => match e {
ParserError(e) => match locate(input, e) { ParserError(e) => {
(s, l, c) => Err(Error::ParseError { let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l, line: l,
char: c, char: c,
sql: s.to_string(), sql: s.to_string(),
}), })
}, }
ScriptError(e) => Err(Error::LanguageError { ScriptError(e) => Err(Error::LanguageError {
message: e, message: e,
}), }),
}, },
Err(Err::Failure(e)) => match e { Err(Err::Failure(e)) => match e {
ParserError(e) => match locate(input, e) { ParserError(e) => {
(s, l, c) => Err(Error::ParseError { let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l, line: l,
char: c, char: c,
sql: s.to_string(), sql: s.to_string(),
}), })
}, }
ScriptError(e) => Err(Error::LanguageError { ScriptError(e) => Err(Error::LanguageError {
message: e, message: e,
}), }),
@ -46,25 +48,27 @@ pub fn json(input: &str) -> Result<Value, Error> {
_ => match value(input) { _ => match value(input) {
Ok((_, query)) => Ok(query), Ok((_, query)) => Ok(query),
Err(Err::Error(e)) => match e { Err(Err::Error(e)) => match e {
ParserError(e) => match locate(input, e) { ParserError(e) => {
(s, l, c) => Err(Error::ParseError { let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l, line: l,
char: c, char: c,
sql: s.to_string(), sql: s.to_string(),
}), })
}, }
ScriptError(e) => Err(Error::LanguageError { ScriptError(e) => Err(Error::LanguageError {
message: e, message: e,
}), }),
}, },
Err(Err::Failure(e)) => match e { Err(Err::Failure(e)) => match e {
ParserError(e) => match locate(input, e) { ParserError(e) => {
(s, l, c) => Err(Error::ParseError { let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l, line: l,
char: c, char: c,
sql: s.to_string(), sql: s.to_string(),
}), })
}, }
ScriptError(e) => Err(Error::LanguageError { ScriptError(e) => Err(Error::LanguageError {
message: e, message: e,
}), }),
@ -83,7 +87,7 @@ fn truncate(s: &str, l: usize) -> &str {
fn locate<'a>(input: &str, tried: &'a str) -> (&'a str, usize, usize) { fn locate<'a>(input: &str, tried: &'a str) -> (&'a str, usize, usize) {
let index = input.len() - tried.len(); let index = input.len() - tried.len();
let tried = truncate(&tried, 100); let tried = truncate(tried, 100);
let lines = input.split('\n').collect::<Vec<&str>>(); let lines = input.split('\n').collect::<Vec<&str>>();
let lines = lines.iter().map(|l| l.len()).enumerate(); let lines = lines.iter().map(|l| l.len()).enumerate();
let (mut total, mut chars) = (0, 0); let (mut total, mut chars) = (0, 0);
@ -96,7 +100,7 @@ fn locate<'a>(input: &str, tried: &'a str) -> (&'a str, usize, usize) {
} }
chars += size + 1; chars += size + 1;
} }
return (tried, 0, 0); (tried, 0, 0)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -98,7 +98,7 @@ fn specific(i: &str) -> IResult<&str, Permissions> {
_ => None, _ => None,
}) })
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
create: perms create: perms
.iter() .iter()
.find_map(|x| { .find_map(|x| {
@ -107,7 +107,7 @@ fn specific(i: &str) -> IResult<&str, Permissions> {
_ => None, _ => None,
}) })
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
update: perms update: perms
.iter() .iter()
.find_map(|x| { .find_map(|x| {
@ -116,7 +116,7 @@ fn specific(i: &str) -> IResult<&str, Permissions> {
_ => None, _ => None,
}) })
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
delete: perms delete: perms
.iter() .iter()
.find_map(|x| { .find_map(|x| {
@ -125,7 +125,7 @@ fn specific(i: &str) -> IResult<&str, Permissions> {
_ => None, _ => None,
}) })
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
}, },
)) ))
} }

View file

@ -76,30 +76,12 @@ pub enum Statement {
impl Statement { impl Statement {
pub fn timeout(&self) -> Option<Duration> { pub fn timeout(&self) -> Option<Duration> {
match self { match self {
Statement::Select(v) => match &v.timeout { Statement::Select(v) => v.timeout.as_ref().map(|v| v.expr.value),
Some(v) => Some(v.expr.value), Statement::Create(v) => v.timeout.as_ref().map(|v| v.expr.value),
None => None, Statement::Update(v) => v.timeout.as_ref().map(|v| v.expr.value),
}, Statement::Relate(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Create(v) => match &v.timeout { Statement::Delete(v) => v.timeout.as_ref().map(|v| v.expr.value),
Some(v) => Some(v.expr.value), Statement::Insert(v) => v.timeout.as_ref().map(|v| v.expr.value),
None => None,
},
Statement::Update(v) => match &v.timeout {
Some(v) => Some(v.expr.value),
None => None,
},
Statement::Relate(v) => match &v.timeout {
Some(v) => Some(v.expr.value),
None => None,
},
Statement::Delete(v) => match &v.timeout {
Some(v) => Some(v.expr.value),
None => None,
},
Statement::Insert(v) => match &v.timeout {
Some(v) => Some(v.expr.value),
None => None,
},
_ => None, _ => None,
} }
} }

View file

@ -79,15 +79,15 @@ impl fmt::Display for DefineStatement {
pub fn define(i: &str) -> IResult<&str, DefineStatement> { pub fn define(i: &str) -> IResult<&str, DefineStatement> {
alt(( alt((
map(namespace, |v| DefineStatement::Namespace(v)), map(namespace, DefineStatement::Namespace),
map(database, |v| DefineStatement::Database(v)), map(database, DefineStatement::Database),
map(login, |v| DefineStatement::Login(v)), map(login, DefineStatement::Login),
map(token, |v| DefineStatement::Token(v)), map(token, DefineStatement::Token),
map(scope, |v| DefineStatement::Scope(v)), map(scope, DefineStatement::Scope),
map(table, |v| DefineStatement::Table(v)), map(table, DefineStatement::Table),
map(event, |v| DefineStatement::Event(v)), map(event, DefineStatement::Event),
map(field, |v| DefineStatement::Field(v)), map(field, DefineStatement::Field),
map(index, |v| DefineStatement::Index(v)), map(index, DefineStatement::Index),
))(i) ))(i)
} }
@ -105,7 +105,7 @@ impl DefineNamespaceStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -149,7 +149,7 @@ impl DefineDatabaseStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -196,7 +196,7 @@ impl DefineLoginStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -294,7 +294,7 @@ impl DefineTokenStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -365,7 +365,7 @@ impl DefineScopeStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -487,7 +487,7 @@ impl DefineTableStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -500,13 +500,13 @@ impl DefineTableStatement {
impl fmt::Display for DefineTableStatement { impl fmt::Display for DefineTableStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DEFINE TABLE {}", self.name)?; write!(f, "DEFINE TABLE {}", self.name)?;
if self.drop == true { if self.drop {
write!(f, " DROP")? write!(f, " DROP")?
} }
if self.full == true { if self.full {
write!(f, " SCHEMAFULL")? write!(f, " SCHEMAFULL")?
} }
if self.full == false { if !self.full {
write!(f, " SCHEMALESS")? write!(f, " SCHEMALESS")?
} }
if let Some(ref v) = self.view { if let Some(ref v) = self.view {
@ -534,7 +534,7 @@ fn table(i: &str) -> IResult<&str, DefineTableStatement> {
DefineTableOption::Drop => Some(true), DefineTableOption::Drop => Some(true),
_ => None, _ => None,
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
full: opts full: opts
.iter() .iter()
.find_map(|x| match x { .find_map(|x| match x {
@ -542,7 +542,7 @@ fn table(i: &str) -> IResult<&str, DefineTableStatement> {
DefineTableOption::Schemaless => Some(false), DefineTableOption::Schemaless => Some(false),
_ => None, _ => None,
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
view: opts.iter().find_map(|x| match x { view: opts.iter().find_map(|x| match x {
DefineTableOption::View(ref v) => Some(v.to_owned()), DefineTableOption::View(ref v) => Some(v.to_owned()),
_ => None, _ => None,
@ -553,7 +553,7 @@ fn table(i: &str) -> IResult<&str, DefineTableStatement> {
DefineTableOption::Permissions(ref v) => Some(v.to_owned()), DefineTableOption::Permissions(ref v) => Some(v.to_owned()),
_ => None, _ => None,
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
}, },
)) ))
} }
@ -618,7 +618,7 @@ impl DefineEventStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -688,7 +688,7 @@ impl DefineFieldStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -754,7 +754,7 @@ fn field(i: &str) -> IResult<&str, DefineFieldStatement> {
DefineFieldOption::Permissions(ref v) => Some(v.to_owned()), DefineFieldOption::Permissions(ref v) => Some(v.to_owned()),
_ => None, _ => None,
}) })
.unwrap_or(Default::default()), .unwrap_or_default(),
}, },
)) ))
} }
@ -827,7 +827,7 @@ impl DefineIndexStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -840,7 +840,7 @@ impl DefineIndexStatement {
impl fmt::Display for DefineIndexStatement { impl fmt::Display for DefineIndexStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DEFINE INDEX {} ON {} COLUMNS {}", self.name, self.what, self.cols)?; write!(f, "DEFINE INDEX {} ON {} COLUMNS {}", self.name, self.what, self.cols)?;
if self.uniq == true { if self.uniq {
write!(f, " UNIQUE")? write!(f, " UNIQUE")?
} }
Ok(()) Ok(())

View file

@ -24,9 +24,9 @@ pub enum InfoStatement {
impl InfoStatement { impl InfoStatement {
pub async fn compute( pub async fn compute(
&self, &self,
ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?

View file

@ -69,15 +69,15 @@ impl fmt::Display for RemoveStatement {
pub fn remove(i: &str) -> IResult<&str, RemoveStatement> { pub fn remove(i: &str) -> IResult<&str, RemoveStatement> {
alt(( alt((
map(namespace, |v| RemoveStatement::Namespace(v)), map(namespace, RemoveStatement::Namespace),
map(database, |v| RemoveStatement::Database(v)), map(database, RemoveStatement::Database),
map(login, |v| RemoveStatement::Login(v)), map(login, RemoveStatement::Login),
map(token, |v| RemoveStatement::Token(v)), map(token, RemoveStatement::Token),
map(scope, |v| RemoveStatement::Scope(v)), map(scope, RemoveStatement::Scope),
map(table, |v| RemoveStatement::Table(v)), map(table, RemoveStatement::Table),
map(event, |v| RemoveStatement::Event(v)), map(event, RemoveStatement::Event),
map(field, |v| RemoveStatement::Field(v)), map(field, RemoveStatement::Field),
map(index, |v| RemoveStatement::Index(v)), map(index, RemoveStatement::Index),
))(i) ))(i)
} }
@ -95,7 +95,7 @@ impl RemoveNamespaceStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -139,7 +139,7 @@ impl RemoveDatabaseStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -184,7 +184,7 @@ impl RemoveLoginStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -238,7 +238,7 @@ impl RemoveTokenStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -291,7 +291,7 @@ impl RemoveScopeStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -335,7 +335,7 @@ impl RemoveTableStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -380,7 +380,7 @@ impl RemoveEventStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -431,7 +431,7 @@ impl RemoveFieldStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?
@ -482,7 +482,7 @@ impl RemoveIndexStatement {
&self, &self,
_ctx: &Runtime, _ctx: &Runtime,
opt: &Options, opt: &Options,
txn: &Transaction, _txn: &Transaction,
_doc: Option<&Value>, _doc: Option<&Value>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Allowed to run? // Allowed to run?

View file

@ -205,7 +205,7 @@ pub fn subquery(i: &str) -> IResult<&str, Subquery> {
} }
fn subquery_ifelse(i: &str) -> IResult<&str, Subquery> { fn subquery_ifelse(i: &str) -> IResult<&str, Subquery> {
let (i, v) = map(ifelse, |v| Subquery::Ifelse(v))(i)?; let (i, v) = map(ifelse, Subquery::Ifelse)(i)?;
Ok((i, v)) Ok((i, v))
} }
@ -218,7 +218,7 @@ fn subquery_others(i: &str) -> IResult<&str, Subquery> {
map(delete, |v| Subquery::Delete(Arc::new(v))), map(delete, |v| Subquery::Delete(Arc::new(v))),
map(relate, |v| Subquery::Relate(Arc::new(v))), map(relate, |v| Subquery::Relate(Arc::new(v))),
map(insert, |v| Subquery::Insert(Arc::new(v))), map(insert, |v| Subquery::Insert(Arc::new(v))),
map(value, |v| Subquery::Value(v)), map(value, Subquery::Value),
))(i)?; ))(i)?;
let (i, _) = tag(")")(i)?; let (i, _) = tag(")")(i)?;
Ok((i, v)) Ok((i, v))

View file

@ -46,7 +46,7 @@ impl Value {
} }
_ => { _ => {
let path = path.next(); let path = path.next();
let futs = v.value.iter_mut().map(|v| v.del(&ctx, opt, txn, path)); let futs = v.value.iter_mut().map(|v| v.del(ctx, opt, txn, path));
try_join_all(futs).await?; try_join_all(futs).await?;
Ok(()) Ok(())
} }
@ -82,18 +82,16 @@ impl Value {
} }
Ok(()) Ok(())
} }
_ => match path.len() { _ => match v.value.get_mut(i.to_usize()) {
_ => match v.value.get_mut(i.to_usize()) { Some(v) => v.del(ctx, opt, txn, path.next()).await,
Some(v) => v.del(ctx, opt, txn, path.next()).await, None => Ok(()),
None => Ok(()),
},
}, },
}, },
Part::Where(w) => match path.len() { Part::Where(w) => match path.len() {
1 => { 1 => {
let mut m = HashMap::new(); let mut m = HashMap::new();
for (i, v) in v.value.iter().enumerate() { for (i, v) in v.value.iter().enumerate() {
if w.compute(ctx, opt, txn, Some(&v)).await?.is_truthy() { if w.compute(ctx, opt, txn, Some(v)).await?.is_truthy() {
m.insert(i, ()); m.insert(i, ());
}; };
} }
@ -103,7 +101,7 @@ impl Value {
_ => { _ => {
let path = path.next(); let path = path.next();
for v in &mut v.value { for v in &mut v.value {
if w.compute(ctx, opt, txn, Some(&v)).await?.is_truthy() { if w.compute(ctx, opt, txn, Some(v)).await?.is_truthy() {
v.del(ctx, opt, txn, path).await?; v.del(ctx, opt, txn, path).await?;
} }
} }
@ -116,7 +114,7 @@ impl Value {
Ok(()) Ok(())
} }
_ => { _ => {
let futs = v.value.iter_mut().map(|v| v.del(&ctx, opt, txn, path)); let futs = v.value.iter_mut().map(|v| v.del(ctx, opt, txn, path));
try_join_all(futs).await?; try_join_all(futs).await?;
Ok(()) Ok(())
} }

View file

@ -10,7 +10,7 @@ impl Value {
(Value::Object(a), Value::Object(b)) if a != b => { (Value::Object(a), Value::Object(b)) if a != b => {
// Loop over old keys // Loop over old keys
for (key, _) in a.value.iter() { for (key, _) in a.value.iter() {
if b.value.contains_key(key) == false { if !b.value.contains_key(key) {
ops.push(Operation { ops.push(Operation {
op: Op::Remove, op: Op::Remove,
path: path.add(key.clone().into()), path: path.add(key.clone().into()),

View file

@ -36,7 +36,7 @@ impl Value {
Value::Array(v) => match p { Value::Array(v) => match p {
Part::All => { Part::All => {
let path = path.next(); let path = path.next();
let futs = v.value.iter().map(|v| v.get(&ctx, opt, txn, path)); let futs = v.value.iter().map(|v| v.get(ctx, opt, txn, path));
try_join_all(futs).await.map(|v| v.into()) try_join_all(futs).await.map(|v| v.into())
} }
Part::First => match v.value.first() { Part::First => match v.value.first() {
@ -55,14 +55,14 @@ impl Value {
let path = path.next(); let path = path.next();
let mut a = Vec::new(); let mut a = Vec::new();
for v in &v.value { for v in &v.value {
if w.compute(ctx, opt, txn, Some(&v)).await?.is_truthy() { if w.compute(ctx, opt, txn, Some(v)).await?.is_truthy() {
a.push(v.get(ctx, opt, txn, path).await?) a.push(v.get(ctx, opt, txn, path).await?)
} }
} }
Ok(a.into()) Ok(a.into())
} }
_ => { _ => {
let futs = v.value.iter().map(|v| v.get(&ctx, opt, txn, path)); let futs = v.value.iter().map(|v| v.get(ctx, opt, txn, path));
try_join_all(futs).await.map(|v| v.into()) try_join_all(futs).await.map(|v| v.into())
} }
}, },

View file

@ -22,20 +22,17 @@ impl Value {
}, },
Op::Remove => self.del(ctx, opt, txn, &o.path).await?, Op::Remove => self.del(ctx, opt, txn, &o.path).await?,
Op::Replace => self.set(ctx, opt, txn, &o.path, o.value).await?, Op::Replace => self.set(ctx, opt, txn, &o.path, o.value).await?,
Op::Change => match o.value { Op::Change => {
Value::Strand(p) => match self.get(ctx, opt, txn, &o.path).await? { if let Value::Strand(p) = o.value {
Value::Strand(v) => { if let Value::Strand(v) = self.get(ctx, opt, txn, &o.path).await? {
let mut dmp = dmp::new(); let mut dmp = dmp::new();
let mut pch = dmp.patch_from_text(p.value); let mut pch = dmp.patch_from_text(p.value);
let (txt, _) = dmp.patch_apply(&mut pch, &v.value); let (txt, _) = dmp.patch_apply(&mut pch, &v.value);
let txt = txt.into_iter().collect::<String>(); let txt = txt.into_iter().collect::<String>();
self.set(ctx, opt, txn, &o.path, Value::from(txt)).await?; self.set(ctx, opt, txn, &o.path, Value::from(txt)).await?;
()
} }
_ => (), }
}, }
_ => (),
},
_ => (), _ => (),
} }
} }

View file

@ -59,7 +59,7 @@ impl Value {
Part::Where(w) => { Part::Where(w) => {
let path = path.next(); let path = path.next();
for v in &mut v.value { for v in &mut v.value {
if w.compute(ctx, opt, txn, Some(&v)).await?.is_truthy() { if w.compute(ctx, opt, txn, Some(v)).await?.is_truthy() {
v.set(ctx, opt, txn, path, val.clone()).await?; v.set(ctx, opt, txn, path, val.clone()).await?;
} }
} }

View file

@ -417,37 +417,19 @@ impl Value {
// ----------------------------------- // -----------------------------------
pub fn is_none(&self) -> bool { pub fn is_none(&self) -> bool {
match self { matches!(self, Value::None | Value::Void | Value::Null)
Value::None => true,
Value::Void => true,
Value::Null => true,
_ => false,
}
} }
pub fn is_void(&self) -> bool { pub fn is_void(&self) -> bool {
match self { matches!(self, Value::None | Value::Void)
Value::None => true,
Value::Void => true,
_ => false,
}
} }
pub fn is_null(&self) -> bool { pub fn is_null(&self) -> bool {
match self { matches!(self, Value::None | Value::Null)
Value::None => true,
Value::Null => true,
_ => false,
}
} }
pub fn is_some(&self) -> bool { pub fn is_some(&self) -> bool {
match self { !self.is_none()
Value::None => false,
Value::Void => false,
Value::Null => false,
_ => true,
}
} }
pub fn is_true(&self) -> bool { pub fn is_true(&self) -> bool {
@ -472,9 +454,9 @@ impl Value {
Value::False => false, Value::False => false,
Value::Thing(_) => true, Value::Thing(_) => true,
Value::Geometry(_) => true, Value::Geometry(_) => true,
Value::Array(v) => v.value.len() > 0, Value::Array(v) => !v.value.is_empty(),
Value::Object(v) => v.value.len() > 0, Value::Object(v) => !v.value.is_empty(),
Value::Strand(v) => v.value.len() > 0 && v.value.to_ascii_lowercase() != "false", Value::Strand(v) => !v.value.is_empty() && v.value.to_ascii_lowercase() != "false",
Value::Number(v) => v.is_truthy(), Value::Number(v) => v.is_truthy(),
Value::Duration(v) => v.value.as_nanos() > 0, Value::Duration(v) => v.value.as_nanos() > 0,
Value::Datetime(v) => v.value.timestamp() > 0, Value::Datetime(v) => v.value.timestamp() > 0,
@ -512,7 +494,7 @@ impl Value {
match self { match self {
Value::True => Decimal::from(1), Value::True => Decimal::from(1),
Value::Number(v) => v.as_decimal(), Value::Number(v) => v.as_decimal(),
Value::Strand(v) => Decimal::from_str(v.as_str()).unwrap_or(Decimal::new(0, 0)), Value::Strand(v) => Decimal::from_str(v.as_str()).unwrap_or_default(),
Value::Duration(v) => v.value.as_secs().into(), Value::Duration(v) => v.value.as_secs().into(),
Value::Datetime(v) => v.value.timestamp().into(), Value::Datetime(v) => v.value.timestamp().into(),
_ => Decimal::default(), _ => Decimal::default(),
@ -596,7 +578,7 @@ impl Value {
.value .value
.trim_start_matches('/') .trim_start_matches('/')
.split(&['.', '/'][..]) .split(&['.', '/'][..])
.map(|s| Part::from(s)) .map(Part::from)
.collect::<Vec<Part>>() .collect::<Vec<Part>>()
.into() .into()
} }
@ -611,15 +593,15 @@ impl Value {
pub fn equal(&self, other: &Value) -> bool { pub fn equal(&self, other: &Value) -> bool {
match self { match self {
Value::None => other.is_none() == true, Value::None => other.is_none(),
Value::Null => other.is_null() == true, Value::Null => other.is_null(),
Value::Void => other.is_void() == true, Value::Void => other.is_void(),
Value::True => other.is_true() == true, Value::True => other.is_true(),
Value::False => other.is_false() == true, Value::False => other.is_false(),
Value::Thing(v) => match other { Value::Thing(v) => match other {
Value::Thing(w) => v == w, Value::Thing(w) => v == w,
Value::Regex(w) => match w.value { Value::Regex(w) => match w.value {
Some(ref r) => r.is_match(v.to_string().as_str()) == true, Some(ref r) => r.is_match(v.to_string().as_str()),
None => false, None => false,
}, },
_ => false, _ => false,
@ -647,7 +629,7 @@ impl Value {
Value::Strand(v) => match other { Value::Strand(v) => match other {
Value::Strand(w) => v == w, Value::Strand(w) => v == w,
Value::Regex(w) => match w.value { Value::Regex(w) => match w.value {
Some(ref r) => r.is_match(v.as_str()) == true, Some(ref r) => r.is_match(v.as_str()),
None => false, None => false,
}, },
_ => v == &other.to_strand(), _ => v == &other.to_strand(),
@ -656,7 +638,7 @@ impl Value {
Value::Number(w) => v == w, Value::Number(w) => v == w,
Value::Strand(_) => v == &other.to_number(), Value::Strand(_) => v == &other.to_number(),
Value::Regex(w) => match w.value { Value::Regex(w) => match w.value {
Some(ref r) => r.is_match(v.to_string().as_str()) == true, Some(ref r) => r.is_match(v.to_string().as_str()),
None => false, None => false,
}, },
_ => false, _ => false,
@ -936,18 +918,18 @@ pub fn single(i: &str) -> IResult<&str, Value> {
map(tag_no_case("false"), |_| Value::False), map(tag_no_case("false"), |_| Value::False),
map(subquery, |v| Value::Subquery(Box::new(v))), map(subquery, |v| Value::Subquery(Box::new(v))),
map(function, |v| Value::Function(Box::new(v))), map(function, |v| Value::Function(Box::new(v))),
map(datetime, |v| Value::Datetime(v)), map(datetime, Value::Datetime),
map(duration, |v| Value::Duration(v)), map(duration, Value::Duration),
map(geometry, |v| Value::Geometry(v)), map(geometry, Value::Geometry),
map(number, |v| Value::Number(v)), map(number, Value::Number),
map(strand, |v| Value::Strand(v)), map(strand, Value::Strand),
map(object, |v| Value::Object(v)), map(object, Value::Object),
map(array, |v| Value::Array(v)), map(array, Value::Array),
map(param, |v| Value::Param(v)), map(param, Value::Param),
map(regex, |v| Value::Regex(v)), map(regex, Value::Regex),
map(thing, |v| Value::Thing(v)), map(thing, Value::Thing),
map(model, |v| Value::Model(v)), map(model, Value::Model),
map(idiom, |v| Value::Idiom(v)), map(idiom, Value::Idiom),
))(i) ))(i)
} }
@ -960,28 +942,28 @@ pub fn select(i: &str) -> IResult<&str, Value> {
map(tag_no_case("false"), |_| Value::False), map(tag_no_case("false"), |_| Value::False),
map(subquery, |v| Value::Subquery(Box::new(v))), map(subquery, |v| Value::Subquery(Box::new(v))),
map(function, |v| Value::Function(Box::new(v))), map(function, |v| Value::Function(Box::new(v))),
map(datetime, |v| Value::Datetime(v)), map(datetime, Value::Datetime),
map(duration, |v| Value::Duration(v)), map(duration, Value::Duration),
map(geometry, |v| Value::Geometry(v)), map(geometry, Value::Geometry),
map(number, |v| Value::Number(v)), map(number, Value::Number),
map(strand, |v| Value::Strand(v)), map(strand, Value::Strand),
map(object, |v| Value::Object(v)), map(object, Value::Object),
map(array, |v| Value::Array(v)), map(array, Value::Array),
map(param, |v| Value::Param(v)), map(param, Value::Param),
map(regex, |v| Value::Regex(v)), map(regex, Value::Regex),
map(thing, |v| Value::Thing(v)), map(thing, Value::Thing),
map(model, |v| Value::Model(v)), map(model, Value::Model),
map(table, |v| Value::Table(v)), map(table, Value::Table),
))(i) ))(i)
} }
pub fn what(i: &str) -> IResult<&str, Value> { pub fn what(i: &str) -> IResult<&str, Value> {
alt(( alt((
map(function, |v| Value::Function(Box::new(v))), map(function, |v| Value::Function(Box::new(v))),
map(param, |v| Value::Param(v)), map(param, Value::Param),
map(model, |v| Value::Model(v)), map(model, Value::Model),
map(thing, |v| Value::Thing(v)), map(thing, Value::Thing),
map(table, |v| Value::Table(v)), map(table, Value::Table),
))(i) ))(i)
} }
@ -990,13 +972,13 @@ pub fn json(i: &str) -> IResult<&str, Value> {
map(tag_no_case("NULL"), |_| Value::Null), map(tag_no_case("NULL"), |_| Value::Null),
map(tag_no_case("true"), |_| Value::True), map(tag_no_case("true"), |_| Value::True),
map(tag_no_case("false"), |_| Value::False), map(tag_no_case("false"), |_| Value::False),
map(datetime, |v| Value::Datetime(v)), map(datetime, Value::Datetime),
map(duration, |v| Value::Duration(v)), map(duration, Value::Duration),
map(geometry, |v| Value::Geometry(v)), map(geometry, Value::Geometry),
map(number, |v| Value::Number(v)), map(number, Value::Number),
map(object, |v| Value::Object(v)), map(object, Value::Object),
map(array, |v| Value::Array(v)), map(array, Value::Array),
map(strand, |v| Value::Strand(v)), map(strand, Value::Strand),
))(i) ))(i)
} }

View file

@ -5,7 +5,7 @@ use reqwest::header::CONTENT_TYPE;
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::io::copy; use std::io::copy;
const TYPE: &'static str = "application/octet-stream"; const TYPE: &str = "application/octet-stream";
pub fn init(matches: &clap::ArgMatches) -> Result<(), Error> { pub fn init(matches: &clap::ArgMatches) -> Result<(), Error> {
// Attempt to open the specified file, // Attempt to open the specified file,

View file

@ -8,7 +8,7 @@ mod version;
use clap::{Arg, Command}; use clap::{Arg, Command};
fn auth_valid(v: &str) -> Result<(), String> { fn auth_valid(v: &str) -> Result<(), String> {
if v.contains(":") { if v.contains(':') {
return Ok(()); return Ok(());
} }
Err(String::from( Err(String::from(
@ -20,7 +20,7 @@ fn auth_valid(v: &str) -> Result<(), String> {
} }
fn file_valid(v: &str) -> Result<(), String> { fn file_valid(v: &str) -> Result<(), String> {
if v.len() > 0 { if !v.is_empty() {
return Ok(()); return Ok(());
} }
Err(String::from( Err(String::from(
@ -390,11 +390,7 @@ pub fn init() {
_ => Ok(()), _ => Ok(()),
}; };
match output { if let Err(e) = output {
Err(e) => { error!("{}", e);
error!("{}", e); }
return ();
}
Ok(_) => {}
};
} }

View file

@ -1,8 +1,7 @@
use crate::err::Error; use crate::err::Error;
use crate::net; use crate::net;
use clap;
const LOGO: &'static str = " const LOGO: &str = "
.d8888b. 888 8888888b. 888888b. .d8888b. 888 8888888b. 888888b.
d88P Y88b 888 888 'Y88b 888 '88b d88P Y88b 888 888 'Y88b 888 '88b
Y88b. 888 888 888 888 .88P Y88b. 888 888 888 888 .88P

View file

@ -1,8 +1,7 @@
use crate::err::Error; use crate::err::Error;
use clap;
const NAME: &'static str = env!("CARGO_PKG_NAME"); const NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const VERSION: &str = env!("CARGO_PKG_VERSION");
macro_rules! get_cfg { macro_rules! get_cfg {
($i:ident : $($s:expr),+) => ( ($i:ident : $($s:expr),+) => (

View file

@ -1,9 +1,9 @@
// The name and version of this build // The name and version of this build
pub const PKG_NAME: &'static str = env!("CARGO_PKG_NAME"); pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
pub const PKG_VERS: &'static str = env!("CARGO_PKG_VERSION"); pub const PKG_VERS: &str = env!("CARGO_PKG_VERSION");
// The publicly visible name of the server // The publicly visible name of the server
pub const SERVER_NAME: &'static str = "SurrealDB"; pub const SERVER_NAME: &str = "SurrealDB";
// The public endpoint for the database administration interface // The public endpoint for the database administration interface
pub const APP_ENDPOINT: &'static str = "https://app.surrealdb.com"; pub const APP_ENDPOINT: &str = "https://app.surrealdb.com";

View file

@ -32,15 +32,15 @@ fn process(
// Specify default conf // Specify default conf
let mut conf = Session::default(); let mut conf = Session::default();
// Specify client ip // Specify client ip
conf.ip = ip.map(|v| v.to_string()).map(|v| v.into()); conf.ip = ip.map(|v| v.to_string());
// Specify session origin // Specify session origin
conf.or = or.map(|v| v.into()); conf.or = or;
// Specify session id // Specify session id
conf.id = id.map(|v| v.into()); conf.id = id;
// Specify namespace // Specify namespace
conf.ns = ns.map(|v| v.into()); conf.ns = ns;
// Specify database // Specify database
conf.db = db.map(|v| v.into()); conf.db = db;
// Parse authentication // Parse authentication
match au { match au {
Some(auth) if auth.starts_with("Basic") => basic(auth, conf), Some(auth) if auth.starts_with("Basic") => basic(auth, conf),
@ -49,10 +49,10 @@ fn process(
} }
} }
fn basic(auth: String, conf: Session) -> Session { fn basic(_auth: String, conf: Session) -> Session {
conf conf
} }
fn token(auth: String, conf: Session) -> Session { fn token(_auth: String, conf: Session) -> Session {
conf conf
} }

View file

@ -1,6 +1,6 @@
use crate::net::conf; use crate::net::conf;
use crate::net::DB; // use crate::net::DB;
use hyper::body::Body; // use hyper::body::Body;
// use surrealdb::dbs::export; // use surrealdb::dbs::export;
use surrealdb::Session; use surrealdb::Session;
use warp::Filter; use warp::Filter;
@ -16,9 +16,10 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
opts.or(get) opts.or(get)
} }
async fn handler(session: Session) -> Result<impl warp::Reply, warp::Rejection> { async fn handler(_session: Session) -> Result<impl warp::Reply, warp::Rejection> {
let db = DB.get().unwrap().clone(); // let db = DB.get().unwrap().clone();
let (chn, body) = Body::channel(); // let (chn, body) = Body::channel();
// tokio::spawn(export(db, session, chn)); // tokio::spawn(export(db, session, chn));
Ok(warp::reply::Response::new(body)) // Ok(warp::reply::Response::new(body))
Ok(warp::reply::reply())
} }

View file

@ -18,8 +18,8 @@ pub async fn recover(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rej
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 404, code: 404,
details: Some(format!("Requested resource not found")), details: Some("Requested resource not found".to_string()),
description: Some(format!("The requested resource does not exist. Check that you have entered the url correctly.")), description: Some("The requested resource does not exist. Check that you have entered the url correctly.".to_string()),
information: None, information: None,
}), }),
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,
@ -28,68 +28,68 @@ pub async fn recover(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rej
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 400, code: 400,
details: Some(format!("Request problems detected")), details: Some("Request problems detected".to_string()),
description: Some(format!("There is a problem with your request. Refer to the documentation for further information.")), description: Some("There is a problem with your request. Refer to the documentation for further information.".to_string()),
information: Some(err.to_string()), information: Some(err.to_string()),
}), }),
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
)) ))
} else if let Some(_) = err.find::<warp::reject::MethodNotAllowed>() { } else if err.find::<warp::reject::MethodNotAllowed>().is_some() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 405, code: 405,
details: Some(format!("Request content length too large")), details: Some("Request content length too large".to_string()),
description: Some(format!("The requested http method is not allowed for this resource. Refer to the documentation for allowed methods.")), description: Some("The requested http method is not allowed for this resource. Refer to the documentation for allowed methods.".to_string()),
information: None, information: None,
}), }),
StatusCode::METHOD_NOT_ALLOWED, StatusCode::METHOD_NOT_ALLOWED,
)) ))
} else if let Some(_) = err.find::<warp::reject::PayloadTooLarge>() { } else if err.find::<warp::reject::PayloadTooLarge>().is_some() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 413, code: 413,
details: Some(format!("Request problems detected")), details: Some("Request problems detected".to_string()),
description: Some(format!("The request has exceeded the maximum payload size. Refer to the documentation for the request limitations.")), description: Some("The request has exceeded the maximum payload size. Refer to the documentation for the request limitations.".to_string()),
information: None, information: None,
}), }),
StatusCode::PAYLOAD_TOO_LARGE, StatusCode::PAYLOAD_TOO_LARGE,
)) ))
} else if let Some(_) = err.find::<warp::reject::UnsupportedMediaType>() { } else if err.find::<warp::reject::UnsupportedMediaType>().is_some() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 415, code: 415,
details: Some(format!("Unsupported content type requested")), details: Some("Unsupported content type requested".to_string()),
description: Some(format!("The request needs to adhere to certain constraints. Refer to the documentation for supported content types.")), description: Some("The request needs to adhere to certain constraints. Refer to the documentation for supported content types.".to_string()),
information: None, information: None,
}), }),
StatusCode::UNSUPPORTED_MEDIA_TYPE, StatusCode::UNSUPPORTED_MEDIA_TYPE,
)) ))
} else if let Some(_) = err.find::<warp::reject::MissingHeader>() { } else if err.find::<warp::reject::MissingHeader>().is_some() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 412, code: 412,
details: Some(format!("Request problems detected")), details: Some("Request problems detected".to_string()),
description: Some(format!("The request appears to be missing a required header. Refer to the documentation for request requirements.")), description: Some("The request appears to be missing a required header. Refer to the documentation for request requirements.".to_string()),
information: None, information: None,
}), }),
StatusCode::PRECONDITION_FAILED, StatusCode::PRECONDITION_FAILED,
)) ))
} else if let Some(_) = err.find::<warp::reject::InvalidQuery>() { } else if err.find::<warp::reject::InvalidQuery>().is_some() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 501, code: 501,
details: Some(format!("Not Implemented")), details: Some("Not Implemented".to_string()),
description: Some(format!("The server either does not recognize the request method, or it lacks the ability to fulfill the request.")), description: Some("The server either does not recognize the query, or it lacks the ability to fulfill the request.".to_string()),
information: None, information: None,
}), }),
StatusCode::NOT_IMPLEMENTED, StatusCode::NOT_IMPLEMENTED,
)) ))
} else if let Some(_) = err.find::<warp::reject::InvalidHeader>() { } else if err.find::<warp::reject::InvalidHeader>().is_some() {
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 501, code: 501,
details: Some(format!("Not Implemented")), details: Some("Not Implemented".to_string()),
description: Some(format!("The server either does not recognize the request method, or it lacks the ability to fulfill the request.")), description: Some("The server either does not recognize a request header, or it lacks the ability to fulfill the request.".to_string()),
information: None, information: None,
}), }),
StatusCode::NOT_IMPLEMENTED, StatusCode::NOT_IMPLEMENTED,
@ -98,8 +98,8 @@ pub async fn recover(err: warp::Rejection) -> Result<impl warp::Reply, warp::Rej
Ok(warp::reply::with_status( Ok(warp::reply::with_status(
warp::reply::json(&Message { warp::reply::json(&Message {
code: 500, code: 500,
details: Some(format!("Internal server error")), details: Some("Internal server error".to_string()),
description: Some(format!("There was a problem with our servers, and we have been notified. Refer to the documentation for further information")), description: Some("There was a problem with our servers, and we have been notified. Refer to the documentation for further information".to_string()),
information: None, information: None,
}), }),
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,

View file

@ -2,11 +2,11 @@ use crate::cnf::PKG_NAME;
use crate::cnf::PKG_VERS; use crate::cnf::PKG_VERS;
use crate::cnf::SERVER_NAME; use crate::cnf::SERVER_NAME;
const ID: &'static str = "ID"; const ID: &str = "ID";
const NS: &'static str = "NS"; const NS: &str = "NS";
const DB: &'static str = "DB"; const DB: &str = "DB";
const SERVER: &'static str = "Server"; const SERVER: &str = "Server";
const VERSION: &'static str = "Version"; const VERSION: &str = "Version";
pub fn version() -> warp::filters::reply::WithHeader { pub fn version() -> warp::filters::reply::WithHeader {
let val = format!("{}-{}", PKG_NAME, PKG_VERS); let val = format!("{}-{}", PKG_NAME, PKG_VERS);

View file

@ -9,7 +9,7 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set post method // Set post method
let post = base let post = base
.and(warp::post()) .and(warp::post())
.and(warp::body::content_length_limit(1024 * 1024 * 1024 * 1)) // 1GiB .and(warp::body::content_length_limit(1024 * 1024 * 1024)) // 1GiB
.and_then(handler); .and_then(handler);
// Specify route // Specify route
opts.or(post) opts.or(post)

View file

@ -43,7 +43,7 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set create method // Set create method
let create = base let create = base
.and(warp::post()) .and(warp::post())
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and(warp::body::bytes()) .and(warp::body::bytes())
.and_then(create_all); .and_then(create_all);
// Set delete method // Set delete method
@ -68,19 +68,19 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set create method // Set create method
let create = base let create = base
.and(warp::post()) .and(warp::post())
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and(warp::body::bytes()) .and(warp::body::bytes())
.and_then(create_one); .and_then(create_one);
// Set update method // Set update method
let update = base let update = base
.and(warp::put()) .and(warp::put())
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and(warp::body::bytes()) .and(warp::body::bytes())
.and_then(update_one); .and_then(update_one);
// Set modify method // Set modify method
let modify = base let modify = base
.and(warp::patch()) .and(warp::patch())
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and(warp::body::bytes()) .and(warp::body::bytes())
.and_then(modify_one); .and_then(modify_one);
// Set delete method // Set delete method
@ -109,8 +109,8 @@ async fn select_all(
let db = DB.get().unwrap().clone(); let db = DB.get().unwrap().clone();
let sql = format!( let sql = format!(
"SELECT * FROM type::table($table) LIMIT {l} START {s}", "SELECT * FROM type::table($table) LIMIT {l} START {s}",
l = query.limit.unwrap_or(String::from("100")), l = query.limit.unwrap_or_else(|| String::from("100")),
s = query.start.unwrap_or(String::from("0")), s = query.start.unwrap_or_else(|| String::from("0")),
); );
let vars = hmap! { let vars = hmap! {
String::from("table") => Value::from(table), String::from("table") => Value::from(table),
@ -139,7 +139,7 @@ async fn create_all(
let sql = "CREATE type::table($table) CONTENT $data"; let sql = "CREATE type::table($table) CONTENT $data";
let vars = hmap! { let vars = hmap! {
String::from("table") => Value::from(table), String::from("table") => Value::from(table),
String::from("data") => Value::from(data), String::from("data") => data,
}; };
match surrealdb::execute(db, sql, session, Some(vars)).await { match surrealdb::execute(db, sql, session, Some(vars)).await {
Ok(res) => match output.as_ref() { Ok(res) => match output.as_ref() {
@ -218,7 +218,7 @@ async fn create_one(
let vars = hmap! { let vars = hmap! {
String::from("table") => Value::from(table), String::from("table") => Value::from(table),
String::from("id") => Value::from(id), String::from("id") => Value::from(id),
String::from("data") => Value::from(data), String::from("data") => data,
}; };
match surrealdb::execute(db, sql, session, Some(vars)).await { match surrealdb::execute(db, sql, session, Some(vars)).await {
Ok(res) => match output.as_ref() { Ok(res) => match output.as_ref() {
@ -249,7 +249,7 @@ async fn update_one(
let vars = hmap! { let vars = hmap! {
String::from("table") => Value::from(table), String::from("table") => Value::from(table),
String::from("id") => Value::from(id), String::from("id") => Value::from(id),
String::from("data") => Value::from(data), String::from("data") => data,
}; };
match surrealdb::execute(db, sql, session, Some(vars)).await { match surrealdb::execute(db, sql, session, Some(vars)).await {
Ok(res) => match output.as_ref() { Ok(res) => match output.as_ref() {
@ -280,7 +280,7 @@ async fn modify_one(
let vars = hmap! { let vars = hmap! {
String::from("table") => Value::from(table), String::from("table") => Value::from(table),
String::from("id") => Value::from(id), String::from("id") => Value::from(id),
String::from("data") => Value::from(data), String::from("data") => data,
}; };
match surrealdb::execute(db, sql, session, Some(vars)).await { match surrealdb::execute(db, sql, session, Some(vars)).await {
Ok(res) => match output.as_ref() { Ok(res) => match output.as_ref() {

View file

@ -13,7 +13,7 @@ impl<T: fmt::Display> fmt::Display for OptFmt<T> {
} }
} }
const NAME: &'static str = "surreal::web"; const NAME: &str = "surreal::web";
pub fn write() -> warp::filters::log::Log<impl Fn(warp::filters::log::Info) + Copy> { pub fn write() -> warp::filters::log::Log<impl Fn(warp::filters::log::Info) + Copy> {
warp::log::custom(|info| { warp::log::custom(|info| {

View file

@ -10,7 +10,7 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set post method // Set post method
let post = base let post = base
.and(warp::post()) .and(warp::post())
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and_then(handler); .and_then(handler);
// Specify route // Specify route
opts.or(post).with(head::cors()) opts.or(post).with(head::cors())

View file

@ -10,7 +10,7 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set post method // Set post method
let post = base let post = base
.and(warp::post()) .and(warp::post())
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and_then(handler); .and_then(handler);
// Specify route // Specify route
opts.or(post).with(head::cors()) opts.or(post).with(head::cors())

View file

@ -18,7 +18,7 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.and(warp::post()) .and(warp::post())
.and(conf::build()) .and(conf::build())
.and(warp::header::<String>(http::header::CONTENT_TYPE.as_str())) .and(warp::header::<String>(http::header::CONTENT_TYPE.as_str()))
.and(warp::body::content_length_limit(1024 * 1024 * 1)) // 1MiB .and(warp::body::content_length_limit(1024 * 1024)) // 1MiB
.and(warp::body::bytes()) .and(warp::body::bytes())
.and_then(handler); .and_then(handler);
// Set sock method // Set sock method