surrealdb_sql/statements/define/
api.rs1use common::fmt::Fmt;
2use surrealdb_types::{SqlFormat, ToSql, write_sql};
3
4use super::DefineKind;
5use super::config::api::ApiConfig;
6use crate::{ApiMethod, CoverStmts, Expr, Literal};
7
8#[derive(Clone, Debug, Eq, PartialEq)]
9#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
10pub struct DefineApiStatement {
11 pub kind: DefineKind,
12 pub path: Expr,
13 pub actions: Vec<ApiAction>,
14 pub fallback: Option<Expr>,
15 pub config: ApiConfig,
16 pub comment: Expr,
17}
18
19impl Default for DefineApiStatement {
20 fn default() -> Self {
21 Self {
22 kind: DefineKind::Default,
23 path: Expr::Literal(Literal::None),
24 actions: Vec::new(),
25 fallback: None,
26 config: ApiConfig::default(),
27 comment: Expr::Literal(Literal::None),
28 }
29 }
30}
31
32impl ToSql for DefineApiStatement {
33 fn fmt_sql(&self, f: &mut String, sql_fmt: SqlFormat) {
34 write_sql!(f, sql_fmt, "DEFINE API");
35 match self.kind {
36 DefineKind::Default => {}
37 DefineKind::Overwrite => write_sql!(f, sql_fmt, " OVERWRITE"),
38 DefineKind::IfNotExists => write_sql!(f, sql_fmt, " IF NOT EXISTS"),
39 }
40 write_sql!(f, sql_fmt, " {}", CoverStmts(&self.path));
41 let sql_fmt = sql_fmt.increment();
42
43 write_sql!(f, sql_fmt, " FOR any");
44 {
45 let sql_fmt = sql_fmt.increment();
46
47 write_sql!(f, sql_fmt, "{}", self.config);
48
49 if let Some(fallback) = &self.fallback {
50 write_sql!(f, sql_fmt, " THEN {}", CoverStmts(fallback));
51 }
52 }
53
54 for action in &self.actions {
55 write_sql!(f, sql_fmt, " {}", action);
56 }
57
58 if !matches!(self.comment, Expr::Literal(Literal::None)) {
59 write_sql!(f, sql_fmt, " COMMENT {}", CoverStmts(&self.comment));
60 }
61 }
62}
63
64#[derive(Clone, Debug, Eq, PartialEq)]
65#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
66pub struct ApiAction {
67 #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary::atleast_one))]
68 pub methods: Vec<ApiMethod>,
69 pub action: Expr,
70 pub config: ApiConfig,
71}
72
73impl ToSql for ApiAction {
74 fn fmt_sql(&self, f: &mut String, sql_fmt: SqlFormat) {
75 f.push_str("FOR ");
76 f.push_str(&Fmt::comma_separated(self.methods.iter()).to_sql());
77 if sql_fmt.is_pretty() {
78 f.push('\n');
79 let inner_fmt = sql_fmt.increment();
80 inner_fmt.write_indent(f);
81 }
82 write_sql!(f, sql_fmt, "{} THEN {}", self.config, self.action);
83 }
84}