surrealpatch/src/sql/object.rs

189 lines
4.1 KiB
Rust
Raw Normal View History

2021-03-29 15:43:37 +00:00
use crate::dbs;
use crate::dbs::Executor;
use crate::dbs::Options;
use crate::dbs::Runtime;
2021-03-29 15:43:37 +00:00
use crate::err::Error;
2020-06-29 15:36:01 +00:00
use crate::sql::comment::mightbespace;
use crate::sql::common::{commas, escape, val_char};
use crate::sql::value::{value, Value};
2020-06-29 15:36:01 +00:00
use nom::branch::alt;
use nom::bytes::complete::is_not;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while1;
use nom::combinator::opt;
2021-03-29 15:43:37 +00:00
use nom::multi::separated_list0;
2020-06-29 15:36:01 +00:00
use nom::sequence::delimited;
use nom::IResult;
2021-03-29 15:43:37 +00:00
use serde::ser::SerializeMap;
use serde::ser::SerializeStruct;
2020-06-29 15:36:01 +00:00
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::HashMap;
2020-06-29 15:36:01 +00:00
use std::fmt;
2021-03-29 15:43:37 +00:00
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Deserialize)]
pub struct Object {
pub value: BTreeMap<String, Value>,
}
impl From<BTreeMap<String, Value>> for Object {
fn from(v: BTreeMap<String, Value>) -> Self {
Object {
value: v,
}
}
}
impl From<HashMap<String, Value>> for Object {
fn from(v: HashMap<String, Value>) -> Self {
Object {
value: v.into_iter().collect(),
}
}
}
impl Object {
pub fn remove(&mut self, key: &String) {
self.value.remove(key);
()
}
pub fn insert(&mut self, key: &String, val: Value) {
self.value.insert(key.to_owned(), val);
()
}
2021-03-29 15:43:37 +00:00
}
2020-06-29 15:36:01 +00:00
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{{ {} }}",
2021-03-29 15:43:37 +00:00
self.value
2020-06-29 15:36:01 +00:00
.iter()
.map(|(ref k, ref v)| format!("{}: {}", escape(&k, &val_char, "\""), v))
.collect::<Vec<_>>()
.join(", ")
)
}
}
2021-03-29 15:43:37 +00:00
impl dbs::Process for Object {
fn process(
&self,
ctx: &Runtime,
opt: &Options,
exe: &mut Executor,
doc: Option<&Value>,
) -> Result<Value, Error> {
2021-03-29 15:43:37 +00:00
self.value
.iter()
.map(|(k, v)| match v.process(ctx, opt, exe, doc) {
Ok(v) => Ok((k.clone(), v)),
2021-03-29 15:43:37 +00:00
Err(e) => Err(e),
})
.collect::<Result<BTreeMap<_, _>, _>>()
2021-03-29 15:43:37 +00:00
.map(|v| {
Value::Object(Object {
2021-03-29 15:43:37 +00:00
value: v,
})
})
}
}
impl Serialize for Object {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
let mut map = serializer.serialize_map(Some(self.value.len()))?;
for (ref k, ref v) in &self.value {
map.serialize_key(k)?;
map.serialize_value(v)?;
}
map.end()
} else {
let mut val = serializer.serialize_struct("Object", 1)?;
2021-03-29 15:43:37 +00:00
val.serialize_field("value", &self.value)?;
val.end()
}
}
}
2020-06-29 15:36:01 +00:00
pub fn object(i: &str) -> IResult<&str, Object> {
let (i, _) = tag("{")(i)?;
let (i, _) = mightbespace(i)?;
2021-03-29 15:43:37 +00:00
let (i, v) = separated_list0(commas, item)(i)?;
2020-06-29 15:36:01 +00:00
let (i, _) = mightbespace(i)?;
let (i, _) = opt(tag(","))(i)?;
let (i, _) = mightbespace(i)?;
let (i, _) = tag("}")(i)?;
2021-03-29 15:43:37 +00:00
Ok((
i,
Object {
value: v.into_iter().collect(),
2021-03-29 15:43:37 +00:00
},
))
2020-06-29 15:36:01 +00:00
}
2021-03-29 15:43:37 +00:00
fn item(i: &str) -> IResult<&str, (String, Value)> {
2020-06-29 15:36:01 +00:00
let (i, k) = key(i)?;
let (i, _) = mightbespace(i)?;
let (i, _) = tag(":")(i)?;
let (i, _) = mightbespace(i)?;
let (i, v) = value(i)?;
Ok((i, (String::from(k), v)))
2020-06-29 15:36:01 +00:00
}
fn key(i: &str) -> IResult<&str, &str> {
alt((key_none, key_single, key_double))(i)
}
fn key_none(i: &str) -> IResult<&str, &str> {
take_while1(val_char)(i)
}
fn key_single(i: &str) -> IResult<&str, &str> {
delimited(tag("\'"), is_not("\'"), tag("\'"))(i)
2020-06-29 15:36:01 +00:00
}
fn key_double(i: &str) -> IResult<&str, &str> {
delimited(tag("\""), is_not("\""), tag("\""))(i)
2020-06-29 15:36:01 +00:00
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn object_normal() {
let sql = "{one:1,two:2,tre:3}";
let res = object(sql);
assert!(res.is_ok());
let out = res.unwrap().1;
assert_eq!("{ one: 1, tre: 3, two: 2 }", format!("{}", out));
2021-03-29 15:43:37 +00:00
assert_eq!(out.value.len(), 3);
2020-06-29 15:36:01 +00:00
}
#[test]
fn object_commas() {
let sql = "{one:1,two:2,tre:3,}";
let res = object(sql);
assert!(res.is_ok());
let out = res.unwrap().1;
assert_eq!("{ one: 1, tre: 3, two: 2 }", format!("{}", out));
2021-03-29 15:43:37 +00:00
assert_eq!(out.value.len(), 3);
2020-06-29 15:36:01 +00:00
}
#[test]
fn object_expression() {
let sql = "{one:1,two:2,tre:3+1}";
let res = object(sql);
assert!(res.is_ok());
let out = res.unwrap().1;
assert_eq!("{ one: 1, tre: 3 + 1, two: 2 }", format!("{}", out));
2021-03-29 15:43:37 +00:00
assert_eq!(out.value.len(), 3);
2020-06-29 15:36:01 +00:00
}
}