surrealdb/sql/statements/
sleep.rs

1use crate::ctx::Context;
2use crate::dbs::{Options, Transaction};
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::iam::{Action, ResourceKind};
6use crate::sql::{Base, Duration, Value};
7use derive::Store;
8use revision::revisioned;
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
13#[revisioned(revision = 1)]
14pub struct SleepStatement {
15	pub(crate) duration: Duration,
16}
17
18impl SleepStatement {
19	/// Process this type returning a computed simple Value
20	pub(crate) async fn compute(
21		&self,
22		ctx: &Context<'_>,
23		opt: &Options,
24		_txn: &Transaction,
25		_doc: Option<&CursorDoc<'_>>,
26	) -> Result<Value, Error> {
27		// Allowed to run?
28		opt.is_allowed(Action::Edit, ResourceKind::Table, &Base::Root)?;
29		// Calculate the sleep duration
30		let dur = match (ctx.timeout(), self.duration.0) {
31			(Some(t), d) if t < d => t,
32			(_, d) => d,
33		};
34		// Sleep for the specified time
35		#[cfg(target_arch = "wasm32")]
36		wasmtimer::tokio::sleep(dur).await;
37		#[cfg(not(target_arch = "wasm32"))]
38		tokio::time::sleep(dur).await;
39		// Ok all good
40		Ok(Value::None)
41	}
42}
43
44impl fmt::Display for SleepStatement {
45	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46		write!(f, "SLEEP {}", self.duration)
47	}
48}