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.
pub fn is_timedout(&self) -> bool {
match self.done() {
Some(Reason::Timedout) => true,
_ => false,
}
matches!(self.done(), Some(Reason::Timedout))
}
// Check if the context is not ok to continue, because it was cancelled.
pub fn is_cancelled(&self) -> bool {
match self.done() {
Some(Reason::Canceled) => true,
_ => false,
}
matches!(self.done(), Some(Reason::Canceled))
}
// 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 {
pub fn check(&self, level: Level) -> bool {
match self {
Auth::No => match level {
Level::No => true,
_ => false,
},
Auth::Kv => match level {
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,
},
Auth::No => matches!(level, Level::No),
Auth::Kv => matches!(level, Level::No | Level::Kv),
Auth::Ns(_) => matches!(level, Level::No | Level::Kv | Level::Ns),
Auth::Db(_, _) => matches!(level, Level::No | Level::Kv | Level::Ns | Level::Db),
Auth::Sc(_, _, _) => true,
}
}
}

View file

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

View file

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

View file

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

View file

@ -106,7 +106,7 @@ impl Iterator {
// Create a new record for processing
pub fn produce(&mut self, val: Table) {
self.prepare(Value::Thing(Thing {
tb: val.name.to_string(),
tb: val.name,
id: nanoid!(20, &ID_CHARS),
}))
}
@ -121,7 +121,7 @@ impl Iterator {
// Log the statement
trace!("Iterating: {}", self.stm);
// Enable context override
let mut ctx = Context::new(&ctx);
let mut ctx = Context::new(ctx);
self.run = ctx.add_cancel();
let ctx = ctx.freeze();
// Process prepared values
@ -145,35 +145,35 @@ impl Iterator {
}
#[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() {
// Ignore
}
}
#[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() {
// Ignore
}
}
#[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() {
// Ignore
}
}
#[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() {
self.results = mem::take(&mut self.results).into_iter().skip(v.0).collect();
}
}
#[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() {
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),
}
// Check if we can exit
if self.stm.group().is_none() {
if self.stm.order().is_none() {
if let Some(l) = self.stm.limit() {
if let Some(s) = self.stm.start() {
if self.results.len() == l.0 + s.0 {
self.run.cancel()
}
} else {
if self.results.len() == l.0 {
self.run.cancel()
}
if self.stm.group().is_none() && self.stm.order().is_none() {
if let Some(l) = self.stm.limit() {
if let Some(s) = self.stm.start() {
if self.results.len() == l.0 + s.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
pub fn check(&self, level: Level) -> Result<(), Error> {
if self.auth.check(level) == false {
if !self.auth.check(level) {
return Err(Error::QueryPermissionsError);
}
if self.ns.is_none() {

View file

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

View file

@ -82,42 +82,42 @@ impl fmt::Display for Statement {
impl Statement {
// 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 {
Statement::Select(v) => v.split.as_ref(),
_ => None,
}
}
// 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 {
Statement::Select(v) => v.group.as_ref(),
_ => None,
}
}
// 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 {
Statement::Select(v) => v.order.as_ref(),
_ => None,
}
}
// 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 {
Statement::Select(v) => v.start.as_ref(),
_ => None,
}
}
// 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 {
Statement::Select(v) => v.limit.as_ref(),
_ => None,
}
}
// 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 {
Statement::Select(v) => v.version.as_ref(),
_ => None,

View file

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

View file

@ -26,10 +26,9 @@ impl<'a> Document<'a> {
};
// Set default field values
self.current.to_mut().def(ctx, opt, txn, id).await?;
// Check for a data clause
match data {
// The statement has a data clause
Some(v) => match v {
// The statement has a data clause
if let Some(v) = data {
match v {
Data::SetExpression(x) => {
for x in x.iter() {
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?
}
_ => unreachable!(),
},
// No data clause has been set
None => (),
};
};
// Set default field values
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?,
false => Value::base(),
};
for v in v.iter() {
for v in v.other() {
match v {
Field::All => (),
Field::Alone(v) => {
@ -64,7 +64,7 @@ impl<'a> Document<'a> {
true => self.current.compute(ctx, opt, txn, Some(&self.current)).await?,
false => Value::base(),
};
for v in stm.expr.iter() {
for v in stm.expr.other() {
match v {
Field::All => (),
Field::Alone(v) => {

View file

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

View file

@ -16,7 +16,7 @@ pub enum Args {
pub fn check(
ctx: &Runtime,
name: &String,
name: &str,
args: Vec<Value>,
size: Args,
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::value::Value;
pub fn run(ctx: &Runtime, name: &String, val: Value) -> Result<Value, Error> {
match name.as_str() {
pub fn run(ctx: &Runtime, name: &str, val: Value) -> Result<Value, Error> {
match name {
"bool" => bool(ctx, val),
"int" => int(ctx, val),
"float" => float(ctx, val),

View file

@ -100,7 +100,7 @@ pub mod hash {
_ => Ok(Value::None),
},
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),
},
_ => 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> {
match args.remove(0) {
Value::Array(v) => match args.remove(0).as_int() {
c => Ok(v.as_numbers().bottom(c).into()),
},
Value::Array(v) => {
let c = args.remove(0).as_int();
Ok(v.as_numbers().bottom(c).into())
}
_ => 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> {
match args.remove(0) {
v => match args.remove(0).as_int() {
p if p > 0 => Ok(v.as_number().fixed(p as usize).into()),
_ => Err(Error::ArgumentsError {
name: String::from("math::fixed"),
message: String::from("The second argument must be an integer greater than 0."),
}),
},
let v = args.remove(0);
match args.remove(0).as_int() {
p if p > 0 => Ok(v.as_number().fixed(p as usize).into()),
_ => Err(Error::ArgumentsError {
name: String::from("math::fixed"),
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> {
match args.remove(0) {
Value::Array(v) => match args.remove(0).as_int() {
c => Ok(v.as_numbers().top(c).into()),
},
Value::Array(v) => {
let c = args.remove(0).as_int();
Ok(v.as_numbers().top(c).into())
}
_ => Ok(Value::None),
}
}

View file

@ -22,8 +22,8 @@ pub mod time;
pub mod r#type;
pub mod util;
pub async fn run(ctx: &Runtime, name: &String, args: Vec<Value>) -> Result<Value, Error> {
match name.as_ref() {
pub async fn run(ctx: &Runtime, name: &str, args: Vec<Value>) -> Result<Value, Error> {
match name {
//
"array::combine" => args::check(ctx, name, args, Args::Two, array::combine),
"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> {
match args.len() {
2 => match args.remove(0).as_float() {
min => match args.remove(0).as_float() {
2 => {
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 => Ok(rand::thread_rng().gen_range(min..=max).into()),
},
},
}
}
0 => Ok(rand::random::<f64>().into()),
_ => 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> {
match args.len() {
1 => match args.remove(0).as_int() as usize {
len => Ok(nanoid!(len, &ID_CHARS).into()),
},
1 => {
let len = args.remove(0).as_int() as usize;
Ok(nanoid!(len, &ID_CHARS).into())
}
0 => Ok(nanoid!(20, &ID_CHARS).into()),
_ => 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> {
match args.len() {
2 => match args.remove(0).as_int() {
min => match args.remove(0).as_int() {
2 => {
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 => Ok(rand::thread_rng().gen_range(min..=max).into()),
},
},
}
}
0 => Ok(rand::random::<i64>().into()),
_ => 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> {
match args.len() {
2 => match args.remove(0).as_int() {
min => match args.remove(0).as_int() {
2 => {
let min = args.remove(0).as_int();
match args.remove(0).as_int() {
max if max < min => {
let i = rand::thread_rng().gen_range(max..=min);
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);
Ok(Datetime::from(i).into())
}
},
},
}
}
0 => {
let i = rand::random::<i64>();
Ok(Datetime::from(i).into())

View file

@ -3,7 +3,7 @@ use crate::err::Error;
use crate::sql::script::Script;
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 {
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> {
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> {
match args.len() {
2 => match args.remove(0) {
x => match args.remove(0) {
y => Ok((x.as_float(), y.as_float()).into()),
},
},
2 => {
let x = args.remove(0);
let y = args.remove(0);
Ok((x.as_float(), y.as_float()).into())
}
1 => match args.remove(0) {
Value::Array(v) if v.len() == 2 => Ok(v.as_point().into()),
Value::Geometry(v) => match v {
Geometry::Point(v) => Ok(v.into()),
_ => Ok(Value::None),
},
Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
_ => Ok(Value::None),
},
_ => 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> {
let tb = args.remove(0);
match args.remove(0) {
tb => match args.remove(0) {
Value::Thing(id) => Ok(Value::Thing(Thing {
tb: tb.as_strand().value,
id: id.id,
})),
id => Ok(Value::Thing(Thing {
tb: tb.as_strand().value,
id: id.as_strand().value,
})),
},
Value::Thing(id) => Ok(Value::Thing(Thing {
tb: tb.as_strand().value,
id: id.id,
})),
id => Ok(Value::Thing(Thing {
tb: tb.as_strand().value,
id: id.as_strand().value,
})),
}
}

View file

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

View file

@ -2,7 +2,6 @@ use byteorder::{WriteBytesExt, BE};
use serde::{self, Serialize};
use std::fmt;
use std::io::{self, Write};
use std::mem::transmute;
use std::{self, i16, i32, i64, i8};
use thiserror::Error;
@ -405,14 +404,14 @@ where
}
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;
self.writer.write_i32::<BE>(val ^ t)?;
Ok(())
}
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;
self.writer.write_i64::<BE>(val ^ t)?;
Ok(())

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -56,7 +56,7 @@ impl Transaction {
// Cancel a transaction
pub async fn cancel(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Mark this transaction as done
@ -69,11 +69,11 @@ impl Transaction {
// Commit a transaction
pub async fn commit(&mut self) -> Result<(), Error> {
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Check to see if transaction is writable
if self.rw == false {
if !self.rw {
return Err(Error::TxReadonlyError);
}
// Mark this transaction as done
@ -89,11 +89,11 @@ impl Transaction {
K: Into<Key>,
{
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Check to see if transaction is writable
if self.rw == false {
if !self.rw {
return Err(Error::TxReadonlyError);
}
// Delete the key
@ -107,7 +107,7 @@ impl Transaction {
K: Into<Key>,
{
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Check the key
@ -121,7 +121,7 @@ impl Transaction {
K: Into<Key>,
{
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Get the key
@ -136,11 +136,11 @@ impl Transaction {
V: Into<Val>,
{
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Check to see if transaction is writable
if self.rw == false {
if !self.rw {
return Err(Error::TxReadonlyError);
}
// Set the key
@ -155,11 +155,11 @@ impl Transaction {
V: Into<Val>,
{
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// Check to see if transaction is writable
if self.rw == false {
if !self.rw {
return Err(Error::TxReadonlyError);
}
// Set the key
@ -173,7 +173,7 @@ impl Transaction {
K: Into<Key>,
{
// Check to see if transaction is closed
if self.ok == true {
if self.ok {
return Err(Error::TxFinishedError);
}
// 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 {
fn from(v: Vec<&str>) -> Self {
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 {
fn from(v: Vec<Operation>) -> Self {
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()
}
pub fn is_empty(&self) -> bool {
self.value.is_empty()
}
pub fn as_ints(self) -> Vec<i64> {
self.value.into_iter().map(|v| v.as_int()).collect()
}
@ -163,7 +167,7 @@ impl Serialize for Array {
impl ops::Add<Value> for Array {
type Output = 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
@ -174,7 +178,7 @@ impl ops::Add for Array {
type Output = Self;
fn add(mut self, other: Self) -> Self {
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)
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -99,21 +99,21 @@ impl From<usize> for Number {
impl From<f32> for Number {
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 {
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 {
fn from(s: &str) -> Self {
match s.contains(&['e', 'E'][..]) {
true => Number::Decimal(Decimal::from_scientific(s).unwrap_or(Decimal::new(0, 0))),
false => Number::Decimal(Decimal::from_str(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_default()),
}
}
}
@ -121,8 +121,8 @@ impl<'a> From<&'a str> for Number {
impl From<String> for Number {
fn from(s: String) -> Self {
match s.contains(&['e', 'E'][..]) {
true => Number::Decimal(Decimal::from_scientific(&s).unwrap_or(Decimal::new(0, 0))),
false => Number::Decimal(Decimal::from_str(&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_default()),
}
}
}
@ -173,7 +173,7 @@ impl Number {
match self {
Number::Int(v) => v != &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 {
match self {
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,
}
}
@ -236,7 +236,7 @@ impl Number {
pub fn to_decimal(&self) -> Decimal {
match self {
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,
}
}
@ -281,7 +281,7 @@ impl Number {
match self {
Number::Int(v) => (v as f64).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 {
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::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)) => {
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::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)) => {
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 {
pub fn remove(&mut self, key: &String) {
pub fn remove(&mut self, key: &str) {
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);
()
}
pub fn to_operation(&self) -> Result<Operation, Error> {
match self.value.get("op") {
@ -119,7 +117,7 @@ impl fmt::Display for Object {
"{{ {} }}",
self.value
.iter()
.map(|(ref k, ref v)| format!("{}: {}", escape(&k, &val_char, "\""), v))
.map(|(k, v)| format!("{}: {}", escape(k, &val_char, "\""), v))
.collect::<Vec<_>>()
.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("AFTER"), |_| Output::After),
map(tag_no_case("BEFORE"), |_| Output::Before),
map(fields, |v| Output::Fields(v)),
map(fields, Output::Fields),
))(i)?;
Ok((i, v))
}

View file

@ -12,25 +12,27 @@ pub fn parse(input: &str) -> Result<Query, Error> {
_ => match query(input) {
Ok((_, query)) => Ok(query),
Err(Err::Error(e)) => match e {
ParserError(e) => match locate(input, e) {
(s, l, c) => Err(Error::ParseError {
ParserError(e) => {
let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l,
char: c,
sql: s.to_string(),
}),
},
})
}
ScriptError(e) => Err(Error::LanguageError {
message: e,
}),
},
Err(Err::Failure(e)) => match e {
ParserError(e) => match locate(input, e) {
(s, l, c) => Err(Error::ParseError {
ParserError(e) => {
let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l,
char: c,
sql: s.to_string(),
}),
},
})
}
ScriptError(e) => Err(Error::LanguageError {
message: e,
}),
@ -46,25 +48,27 @@ pub fn json(input: &str) -> Result<Value, Error> {
_ => match value(input) {
Ok((_, query)) => Ok(query),
Err(Err::Error(e)) => match e {
ParserError(e) => match locate(input, e) {
(s, l, c) => Err(Error::ParseError {
ParserError(e) => {
let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l,
char: c,
sql: s.to_string(),
}),
},
})
}
ScriptError(e) => Err(Error::LanguageError {
message: e,
}),
},
Err(Err::Failure(e)) => match e {
ParserError(e) => match locate(input, e) {
(s, l, c) => Err(Error::ParseError {
ParserError(e) => {
let (s, l, c) = locate(input, e);
Err(Error::ParseError {
line: l,
char: c,
sql: s.to_string(),
}),
},
})
}
ScriptError(e) => Err(Error::LanguageError {
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) {
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 = lines.iter().map(|l| l.len()).enumerate();
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;
}
return (tried, 0, 0);
(tried, 0, 0)
}
#[cfg(test)]

View file

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

View file

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

View file

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

View file

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

View file

@ -69,15 +69,15 @@ impl fmt::Display for RemoveStatement {
pub fn remove(i: &str) -> IResult<&str, RemoveStatement> {
alt((
map(namespace, |v| RemoveStatement::Namespace(v)),
map(database, |v| RemoveStatement::Database(v)),
map(login, |v| RemoveStatement::Login(v)),
map(token, |v| RemoveStatement::Token(v)),
map(scope, |v| RemoveStatement::Scope(v)),
map(table, |v| RemoveStatement::Table(v)),
map(event, |v| RemoveStatement::Event(v)),
map(field, |v| RemoveStatement::Field(v)),
map(index, |v| RemoveStatement::Index(v)),
map(namespace, RemoveStatement::Namespace),
map(database, RemoveStatement::Database),
map(login, RemoveStatement::Login),
map(token, RemoveStatement::Token),
map(scope, RemoveStatement::Scope),
map(table, RemoveStatement::Table),
map(event, RemoveStatement::Event),
map(field, RemoveStatement::Field),
map(index, RemoveStatement::Index),
))(i)
}
@ -95,7 +95,7 @@ impl RemoveNamespaceStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -139,7 +139,7 @@ impl RemoveDatabaseStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -184,7 +184,7 @@ impl RemoveLoginStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -238,7 +238,7 @@ impl RemoveTokenStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -291,7 +291,7 @@ impl RemoveScopeStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -335,7 +335,7 @@ impl RemoveTableStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -380,7 +380,7 @@ impl RemoveEventStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -431,7 +431,7 @@ impl RemoveFieldStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// Allowed to run?
@ -482,7 +482,7 @@ impl RemoveIndexStatement {
&self,
_ctx: &Runtime,
opt: &Options,
txn: &Transaction,
_txn: &Transaction,
_doc: Option<&Value>,
) -> Result<Value, Error> {
// 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> {
let (i, v) = map(ifelse, |v| Subquery::Ifelse(v))(i)?;
let (i, v) = map(ifelse, Subquery::Ifelse)(i)?;
Ok((i, v))
}
@ -218,7 +218,7 @@ fn subquery_others(i: &str) -> IResult<&str, Subquery> {
map(delete, |v| Subquery::Delete(Arc::new(v))),
map(relate, |v| Subquery::Relate(Arc::new(v))),
map(insert, |v| Subquery::Insert(Arc::new(v))),
map(value, |v| Subquery::Value(v)),
map(value, Subquery::Value),
))(i)?;
let (i, _) = tag(")")(i)?;
Ok((i, v))

View file

@ -46,7 +46,7 @@ impl Value {
}
_ => {
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?;
Ok(())
}
@ -82,18 +82,16 @@ impl Value {
}
Ok(())
}
_ => match path.len() {
_ => match v.value.get_mut(i.to_usize()) {
Some(v) => v.del(ctx, opt, txn, path.next()).await,
None => Ok(()),
},
_ => match v.value.get_mut(i.to_usize()) {
Some(v) => v.del(ctx, opt, txn, path.next()).await,
None => Ok(()),
},
},
Part::Where(w) => match path.len() {
1 => {
let mut m = HashMap::new();
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, ());
};
}
@ -103,7 +101,7 @@ impl Value {
_ => {
let path = path.next();
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?;
}
}
@ -116,7 +114,7 @@ impl Value {
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?;
Ok(())
}

View file

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

View file

@ -36,7 +36,7 @@ impl Value {
Value::Array(v) => match p {
Part::All => {
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())
}
Part::First => match v.value.first() {
@ -55,14 +55,14 @@ impl Value {
let path = path.next();
let mut a = Vec::new();
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?)
}
}
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())
}
},

View file

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

View file

@ -59,7 +59,7 @@ impl Value {
Part::Where(w) => {
let path = path.next();
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?;
}
}

View file

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

View file

@ -5,7 +5,7 @@ use reqwest::header::CONTENT_TYPE;
use std::fs::OpenOptions;
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> {
// Attempt to open the specified file,

View file

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

View file

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

View file

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

View file

@ -1,9 +1,9 @@
// The name and version of this build
pub const PKG_NAME: &'static str = env!("CARGO_PKG_NAME");
pub const PKG_VERS: &'static str = env!("CARGO_PKG_VERSION");
pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
pub const PKG_VERS: &str = env!("CARGO_PKG_VERSION");
// 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
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
let mut conf = Session::default();
// 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
conf.or = or.map(|v| v.into());
conf.or = or;
// Specify session id
conf.id = id.map(|v| v.into());
conf.id = id;
// Specify namespace
conf.ns = ns.map(|v| v.into());
conf.ns = ns;
// Specify database
conf.db = db.map(|v| v.into());
conf.db = db;
// Parse authentication
match au {
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
}
fn token(auth: String, conf: Session) -> Session {
fn token(_auth: String, conf: Session) -> Session {
conf
}

View file

@ -1,6 +1,6 @@
use crate::net::conf;
use crate::net::DB;
use hyper::body::Body;
// use crate::net::DB;
// use hyper::body::Body;
// use surrealdb::dbs::export;
use surrealdb::Session;
use warp::Filter;
@ -16,9 +16,10 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
opts.or(get)
}
async fn handler(session: Session) -> Result<impl warp::Reply, warp::Rejection> {
let db = DB.get().unwrap().clone();
let (chn, body) = Body::channel();
async fn handler(_session: Session) -> Result<impl warp::Reply, warp::Rejection> {
// let db = DB.get().unwrap().clone();
// let (chn, body) = Body::channel();
// 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(
warp::reply::json(&Message {
code: 404,
details: Some(format!("Requested resource not found")),
description: Some(format!("The requested resource does not exist. Check that you have entered the url correctly.")),
details: Some("Requested resource not found".to_string()),
description: Some("The requested resource does not exist. Check that you have entered the url correctly.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 400,
details: Some(format!("Request problems detected")),
description: Some(format!("There is a problem with your request. Refer to the documentation for further information.")),
details: Some("Request problems detected".to_string()),
description: Some("There is a problem with your request. Refer to the documentation for further information.".to_string()),
information: Some(err.to_string()),
}),
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(
warp::reply::json(&Message {
code: 405,
details: Some(format!("Request content length too large")),
description: Some(format!("The requested http method is not allowed for this resource. Refer to the documentation for allowed methods.")),
details: Some("Request content length too large".to_string()),
description: Some("The requested http method is not allowed for this resource. Refer to the documentation for allowed methods.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 413,
details: Some(format!("Request problems detected")),
description: Some(format!("The request has exceeded the maximum payload size. Refer to the documentation for the request limitations.")),
details: Some("Request problems detected".to_string()),
description: Some("The request has exceeded the maximum payload size. Refer to the documentation for the request limitations.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 415,
details: Some(format!("Unsupported content type requested")),
description: Some(format!("The request needs to adhere to certain constraints. Refer to the documentation for supported content types.")),
details: Some("Unsupported content type requested".to_string()),
description: Some("The request needs to adhere to certain constraints. Refer to the documentation for supported content types.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 412,
details: Some(format!("Request problems detected")),
description: Some(format!("The request appears to be missing a required header. Refer to the documentation for request requirements.")),
details: Some("Request problems detected".to_string()),
description: Some("The request appears to be missing a required header. Refer to the documentation for request requirements.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 501,
details: Some(format!("Not Implemented")),
description: Some(format!("The server either does not recognize the request method, or it lacks the ability to fulfill the request.")),
details: Some("Not Implemented".to_string()),
description: Some("The server either does not recognize the query, or it lacks the ability to fulfill the request.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 501,
details: Some(format!("Not Implemented")),
description: Some(format!("The server either does not recognize the request method, or it lacks the ability to fulfill the request.")),
details: Some("Not Implemented".to_string()),
description: Some("The server either does not recognize a request header, or it lacks the ability to fulfill the request.".to_string()),
information: None,
}),
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(
warp::reply::json(&Message {
code: 500,
details: Some(format!("Internal server error")),
description: Some(format!("There was a problem with our servers, and we have been notified. Refer to the documentation for further information")),
details: Some("Internal server error".to_string()),
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,
}),
StatusCode::INTERNAL_SERVER_ERROR,

View file

@ -2,11 +2,11 @@ use crate::cnf::PKG_NAME;
use crate::cnf::PKG_VERS;
use crate::cnf::SERVER_NAME;
const ID: &'static str = "ID";
const NS: &'static str = "NS";
const DB: &'static str = "DB";
const SERVER: &'static str = "Server";
const VERSION: &'static str = "Version";
const ID: &str = "ID";
const NS: &str = "NS";
const DB: &str = "DB";
const SERVER: &str = "Server";
const VERSION: &str = "Version";
pub fn version() -> warp::filters::reply::WithHeader {
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
let post = base
.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);
// Specify route
opts.or(post)

View file

@ -43,7 +43,7 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set create method
let create = base
.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_then(create_all);
// Set delete method
@ -68,19 +68,19 @@ pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
// Set create method
let create = base
.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_then(create_one);
// Set update method
let update = base
.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_then(update_one);
// Set modify method
let modify = base
.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_then(modify_one);
// Set delete method
@ -109,8 +109,8 @@ async fn select_all(
let db = DB.get().unwrap().clone();
let sql = format!(
"SELECT * FROM type::table($table) LIMIT {l} START {s}",
l = query.limit.unwrap_or(String::from("100")),
s = query.start.unwrap_or(String::from("0")),
l = query.limit.unwrap_or_else(|| String::from("100")),
s = query.start.unwrap_or_else(|| String::from("0")),
);
let vars = hmap! {
String::from("table") => Value::from(table),
@ -139,7 +139,7 @@ async fn create_all(
let sql = "CREATE type::table($table) CONTENT $data";
let vars = hmap! {
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 {
Ok(res) => match output.as_ref() {
@ -218,7 +218,7 @@ async fn create_one(
let vars = hmap! {
String::from("table") => Value::from(table),
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 {
Ok(res) => match output.as_ref() {
@ -249,7 +249,7 @@ async fn update_one(
let vars = hmap! {
String::from("table") => Value::from(table),
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 {
Ok(res) => match output.as_ref() {
@ -280,7 +280,7 @@ async fn modify_one(
let vars = hmap! {
String::from("table") => Value::from(table),
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 {
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> {
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
let post = base
.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);
// Specify route
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
let post = base
.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);
// Specify route
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(conf::build())
.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_then(handler);
// Set sock method