surrealdb/sql/statements/define/
database.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::{changefeed::ChangeFeed, Base, Ident, Strand, Value};
7use derive::Store;
8use revision::revisioned;
9use serde::{Deserialize, Serialize};
10use std::fmt::{self, Display};
11
12#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
13#[revisioned(revision = 1)]
14pub struct DefineDatabaseStatement {
15	pub id: Option<u32>,
16	pub name: Ident,
17	pub comment: Option<Strand>,
18	pub changefeed: Option<ChangeFeed>,
19}
20
21impl DefineDatabaseStatement {
22	/// Process this type returning a computed simple Value
23	pub(crate) async fn compute(
24		&self,
25		_ctx: &Context<'_>,
26		opt: &Options,
27		txn: &Transaction,
28		_doc: Option<&CursorDoc<'_>>,
29	) -> Result<Value, Error> {
30		// Allowed to run?
31		opt.is_allowed(Action::Edit, ResourceKind::Database, &Base::Ns)?;
32		// Claim transaction
33		let mut run = txn.lock().await;
34		// Clear the cache
35		run.clear_cache();
36		// Process the statement
37		let key = crate::key::namespace::db::new(opt.ns(), &self.name);
38		let ns = run.add_ns(opt.ns(), opt.strict).await?;
39		// Set the id
40		if self.id.is_none() && ns.id.is_some() {
41			let mut db = self.clone();
42			db.id = Some(run.get_next_db_id(ns.id.unwrap()).await?);
43			// Store the db
44			run.set(key, db).await?;
45		} else {
46			// Store the db
47			run.set(key, self).await?;
48		}
49		// Ok all good
50		Ok(Value::None)
51	}
52}
53
54impl Display for DefineDatabaseStatement {
55	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56		write!(f, "DEFINE DATABASE {}", self.name)?;
57		if let Some(ref v) = self.comment {
58			write!(f, " COMMENT {v}")?
59		}
60		if let Some(ref v) = self.changefeed {
61			write!(f, " {v}")?;
62		}
63		Ok(())
64	}
65}