surrealdb_core/sql/statements/
live.rsuse crate::ctx::Context;
use crate::dbs::{Options, Transaction};
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::fflags::FFLAGS;
use crate::iam::Auth;
use crate::sql::{Cond, Fetchs, Fields, Uuid, Value};
use derive::Store;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::fmt;
#[revisioned(revision = 2)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct LiveStatement {
pub id: Uuid,
pub node: Uuid,
pub expr: Fields,
pub what: Value,
pub cond: Option<Cond>,
pub fetch: Option<Fetchs>,
pub(crate) archived: Option<Uuid>,
#[revision(start = 2)]
pub(crate) session: Option<Value>,
pub(crate) auth: Option<Auth>,
}
impl LiveStatement {
#[doc(hidden)]
pub fn new(expr: Fields) -> Self {
LiveStatement {
id: Uuid::new_v4(),
node: Uuid::new_v4(),
expr,
..Default::default()
}
}
pub(crate) fn from_source_parts(
expr: Fields,
what: Value,
cond: Option<Cond>,
fetch: Option<Fetchs>,
) -> Self {
LiveStatement {
id: Uuid::new_v4(),
node: Uuid::new_v4(),
expr,
what,
cond,
fetch,
..Default::default()
}
}
pub(crate) async fn compute(
&self,
ctx: &Context<'_>,
opt: &Options,
txn: &Transaction,
doc: Option<&CursorDoc<'_>>,
) -> Result<Value, Error> {
opt.realtime()?;
opt.valid_for_db()?;
let nid = opt.id()?;
let mut stm = LiveStatement {
session: ctx.value("session").cloned(),
auth: Some(opt.auth.as_ref().clone()),
..self.clone()
};
let id = stm.id.0;
let mut run = txn.lock().await;
match stm.what.compute(ctx, opt, txn, doc).await? {
Value::Table(tb) => {
if FFLAGS.change_feed_live_queries.enabled() {
return Ok(id.into());
}
stm.node = nid.into();
run.putc_ndlq(nid, id, opt.ns(), opt.db(), tb.as_str(), None).await?;
run.putc_tblq(opt.ns(), opt.db(), &tb, stm, None).await?;
}
v => {
return Err(Error::LiveStatement {
value: v.to_string(),
})
}
};
Ok(id.into())
}
pub(crate) fn archive(mut self, node_id: Uuid) -> LiveStatement {
self.archived = Some(node_id);
self
}
}
impl fmt::Display for LiveStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LIVE SELECT {} FROM {}", self.expr, self.what)?;
if let Some(ref v) = self.cond {
write!(f, " {v}")?
}
if let Some(ref v) = self.fetch {
write!(f, " {v}")?
}
Ok(())
}
}