use crate::ctx::Context;
use crate::dbs::Statement;
use crate::dbs::{Options, Transaction};
use crate::doc::Document;
use crate::err::Error;
use crate::iam::Action;
use crate::idiom::Idiom;
use crate::output::Output;
use crate::paths::META;
use crate::permission::Permission;
use crate::value::Value;
impl<'a> Document<'a> {
pub async fn pluck(
&self,
ctx: &Context<'_>,
opt: &Options,
txn: &Transaction,
stm: &Statement<'_>,
) -> Result<Value, Error> {
let opt = &opt.new_with_futures(true);
let mut out = match stm.output() {
Some(v) => match v {
Output::None => Err(Error::Ignore),
Output::Null => Ok(Value::Null),
Output::Diff => {
Ok(self.initial.doc.diff(self.current.doc.as_ref(), Idiom::default()).into())
}
Output::After => {
self.current.doc.compute(ctx, opt, txn, Some(&self.current)).await
}
Output::Before => {
self.initial.doc.compute(ctx, opt, txn, Some(&self.initial)).await
}
Output::Fields(v) => {
let mut ctx = Context::new(ctx);
ctx.add_value("after", self.current.doc.as_ref());
ctx.add_value("before", self.initial.doc.as_ref());
v.compute(&ctx, opt, txn, Some(&self.current), false).await
}
},
None => match stm {
Statement::Live(s) => match s.expr.len() {
0 => Ok(self.initial.doc.diff(&self.current.doc, Idiom::default()).into()),
_ => s.expr.compute(ctx, opt, txn, Some(&self.current), false).await,
},
Statement::Select(s) => {
s.expr.compute(ctx, opt, txn, Some(&self.current), s.group.is_some()).await
}
Statement::Create(_) => {
self.current.doc.compute(ctx, opt, txn, Some(&self.current)).await
}
Statement::Update(_) => {
self.current.doc.compute(ctx, opt, txn, Some(&self.current)).await
}
Statement::Relate(_) => {
self.current.doc.compute(ctx, opt, txn, Some(&self.current)).await
}
Statement::Insert(_) => {
self.current.doc.compute(ctx, opt, txn, Some(&self.current)).await
}
_ => Err(Error::Ignore),
},
}?;
if self.id.is_some() {
if opt.check_perms(Action::View) {
for fd in self.fd(opt, txn).await?.iter() {
for k in out.each(&fd.name).iter() {
match &fd.permissions.select {
Permission::Full => (),
Permission::None => out.del(ctx, opt, txn, k).await?,
Permission::Specific(e) => {
let opt = &opt.new_with_perms(false);
let val = self.current.doc.pick(k);
let mut ctx = Context::new(ctx);
ctx.add_value("value", &val);
if !e
.compute(&ctx, opt, txn, Some(&self.current))
.await?
.is_truthy()
{
out.del(&ctx, opt, txn, k).await?
}
}
}
}
}
}
}
if let Some(v) = stm.omit() {
for v in v.iter() {
out.del(ctx, opt, txn, v).await?;
}
}
out.cut(&*META);
Ok(out)
}
}