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 duration: AccessDuration,
15	pub comment: Expr,
16}
17
18impl ToSql for DefineAccessStatement {
19	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
20		write_sql!(f, fmt, "DEFINE ACCESS");
21		match self.kind {
22			DefineKind::Default => {}
23			DefineKind::Overwrite => {
24				write_sql!(f, fmt, " OVERWRITE");
25			}
26			DefineKind::IfNotExists => {
27				write_sql!(f, fmt, " IF NOT EXISTS");
28			}
29		}
30		// The specific access method definition is displayed by AccessType
31		write_sql!(
32			f,
33			fmt,
34			" {} ON {} TYPE {}",
35			CoverStmts(&self.name),
36			self.base,
37			self.access_type
38		);
39		// The additional authentication clause
40		if let Some(ref v) = self.authenticate {
41			write_sql!(f, fmt, " AUTHENTICATE {}", CoverStmts(v))
42		}
43		// Always print relevant durations so defaults can be changed in the future
44		// If default values were not printed, exports would not be forward compatible
45		// None values need to be printed, as they are different from the default values
46		write_sql!(f, fmt, " DURATION");
47		if self.access_type.can_issue_grants() {
48			write_sql!(f, fmt, " FOR GRANT {},", CoverStmts(&self.duration.grant));
49		}
50		if self.access_type.can_issue_tokens() {
51			write_sql!(f, fmt, " FOR TOKEN {},", CoverStmts(&self.duration.token));
52		}
53
54		write_sql!(f, fmt, " FOR SESSION {}", CoverStmts(&self.duration.session));
55		if !matches!(self.comment, Expr::Literal(Literal::None)) {
56			write_sql!(f, fmt, " COMMENT {}", CoverStmts(&self.comment));
57		}
58	}
59}