Skip to main content

surrealdb_sql/statements/define/
access.rs

1use surrealdb_types::{SqlFormat, ToSql, write_sql};
2
3use super::DefineKind;
4use crate::access::AccessDuration;
5use crate::{AccessType, Base, CoverStmts, Expr, Literal};
6
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct DefineAccessStatement {
9	pub kind: DefineKind,
10	pub name: Expr,
11	pub base: Base,
12	pub access_type: AccessType,
13	pub authenticate: Option<Expr>,
14	pub context: Option<Expr>,
15	pub duration: AccessDuration,
16	pub comment: Expr,
17}
18
19impl ToSql for DefineAccessStatement {
20	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
21		write_sql!(f, fmt, "DEFINE ACCESS");
22		match self.kind {
23			DefineKind::Default => {}
24			DefineKind::Overwrite => {
25				write_sql!(f, fmt, " OVERWRITE");
26			}
27			DefineKind::IfNotExists => {
28				write_sql!(f, fmt, " IF NOT EXISTS");
29			}
30		}
31		// The specific access method definition is displayed by AccessType
32		write_sql!(
33			f,
34			fmt,
35			" {} ON {} TYPE {}",
36			CoverStmts(&self.name),
37			self.base,
38			self.access_type
39		);
40		// The additional authentication clause
41		if let Some(ref v) = self.authenticate {
42			write_sql!(f, fmt, " AUTHENTICATE {}", CoverStmts(v))
43		}
44		// The authorisation context clause. Printed before DURATION so a
45		// rendered definition re-parses to the same statement.
46		if let Some(ref v) = self.context {
47			write_sql!(f, fmt, " CONTEXT {}", CoverStmts(v))
48		}
49		// Always print relevant durations so defaults can be changed in the future
50		// If default values were not printed, exports would not be forward compatible
51		// None values need to be printed, as they are different from the default values
52		write_sql!(f, fmt, " DURATION");
53		if self.access_type.can_issue_grants() {
54			write_sql!(f, fmt, " FOR GRANT {},", CoverStmts(&self.duration.grant));
55		}
56		if self.access_type.can_issue_tokens() {
57			write_sql!(f, fmt, " FOR TOKEN {},", CoverStmts(&self.duration.token));
58		}
59
60		write_sql!(f, fmt, " FOR SESSION {}", CoverStmts(&self.duration.session));
61		if !matches!(self.comment, Expr::Literal(Literal::None)) {
62			write_sql!(f, fmt, " COMMENT {}", CoverStmts(&self.comment));
63		}
64	}
65}