surrealdb_core/sql/statements/
show.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::iam::{Action, ResourceKind};
6use crate::sql::{Base, Datetime, Table, Value};
7use crate::vs::VersionStamp;
8
9use revision::revisioned;
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13#[revisioned(revision = 1)]
14#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
15#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
16#[non_exhaustive]
17pub enum ShowSince {
18	Timestamp(Datetime),
19	Versionstamp(u64),
20}
21
22impl ShowSince {
23	pub fn versionstamp(vs: &VersionStamp) -> ShowSince {
24		ShowSince::Versionstamp(vs.into_u64_lossy())
25	}
26
27	pub fn as_versionstamp(&self) -> Option<VersionStamp> {
28		match self {
29			ShowSince::Timestamp(_) => None,
30			ShowSince::Versionstamp(v) => Some(VersionStamp::from_u64(*v)),
31		}
32	}
33}
34
35/// A SHOW CHANGES statement for displaying changes made to a table or database.
36#[revisioned(revision = 1)]
37#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
38#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
39#[non_exhaustive]
40pub struct ShowStatement {
41	pub table: Option<Table>,
42	pub since: ShowSince,
43	pub limit: Option<u32>,
44}
45
46impl ShowStatement {
47	/// Process this type returning a computed simple Value
48	pub(crate) async fn compute(
49		&self,
50		ctx: &Context,
51		opt: &Options,
52		_doc: Option<&CursorDoc>,
53	) -> Result<Value, Error> {
54		// Allowed to run?
55		opt.is_allowed(Action::View, ResourceKind::Table, &Base::Db)?;
56		// Get the transaction
57		let txn = ctx.tx();
58		// Process the show query
59		let (ns, db) = opt.ns_db()?;
60		let r = crate::cf::read(
61			&txn,
62			ns,
63			db,
64			self.table.as_deref().map(String::as_str),
65			self.since.clone(),
66			self.limit,
67		)
68		.await?;
69		// Return the changes
70		let a: Vec<Value> = r.iter().cloned().map(|x| x.into_value()).collect();
71		Ok(a.into())
72	}
73}
74
75impl fmt::Display for ShowStatement {
76	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77		write!(f, "SHOW CHANGES FOR")?;
78		match self.table {
79			Some(ref v) => write!(f, " TABLE {}", v)?,
80			None => write!(f, " DATABASE")?,
81		}
82		match self.since {
83			ShowSince::Timestamp(ref v) => write!(f, " SINCE {}", v)?,
84			ShowSince::Versionstamp(ref v) => write!(f, " SINCE {}", v)?,
85		}
86		if let Some(ref v) = self.limit {
87			write!(f, " LIMIT {}", v)?
88		}
89		Ok(())
90	}
91}