surrealdb_core/sql/statements/define/
analyzer.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::iam::{Action, ResourceKind};
6use crate::sql::statements::info::InfoStructure;
7use crate::sql::{filter::Filter, tokenizer::Tokenizer, Array, Base, Ident, Strand, Value};
8
9use revision::revisioned;
10use serde::{Deserialize, Serialize};
11use std::fmt::{self, Display};
12
13#[revisioned(revision = 4)]
14#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
15#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
16#[non_exhaustive]
17pub struct DefineAnalyzerStatement {
18	pub name: Ident,
19	#[revision(start = 2)]
20	pub function: Option<Ident>,
21	pub tokenizers: Option<Vec<Tokenizer>>,
22	pub filters: Option<Vec<Filter>>,
23	pub comment: Option<Strand>,
24	#[revision(start = 3)]
25	pub if_not_exists: bool,
26	#[revision(start = 4)]
27	pub overwrite: bool,
28}
29
30impl DefineAnalyzerStatement {
31	pub(crate) async fn compute(
32		&self,
33		ctx: &Context,
34		opt: &Options,
35		_doc: Option<&CursorDoc>,
36	) -> Result<Value, Error> {
37		// Allowed to run?
38		opt.is_allowed(Action::Edit, ResourceKind::Analyzer, &Base::Db)?;
39		// Fetch the transaction
40		let txn = ctx.tx();
41		let (ns, db) = opt.ns_db()?;
42		// Check if the definition exists
43		if txn.get_db_analyzer(ns, db, &self.name).await.is_ok() {
44			if self.if_not_exists {
45				return Ok(Value::None);
46			} else if !self.overwrite {
47				return Err(Error::AzAlreadyExists {
48					name: self.name.to_string(),
49				});
50			}
51		}
52		// Process the statement
53		let key = crate::key::database::az::new(ns, db, &self.name);
54		txn.get_or_add_ns(ns, opt.strict).await?;
55		txn.get_or_add_db(ns, db, opt.strict).await?;
56		let az = DefineAnalyzerStatement {
57			// Don't persist the `IF NOT EXISTS` clause to schema
58			if_not_exists: false,
59			overwrite: false,
60			..self.clone()
61		};
62		ctx.get_index_stores().mappers().load(&az).await?;
63		txn.set(key, revision::to_vec(&az)?, None).await?;
64		// Clear the cache
65		txn.clear();
66		// Ok all good
67		Ok(Value::None)
68	}
69}
70
71impl Display for DefineAnalyzerStatement {
72	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73		write!(f, "DEFINE ANALYZER")?;
74		if self.if_not_exists {
75			write!(f, " IF NOT EXISTS")?
76		}
77		if self.overwrite {
78			write!(f, " OVERWRITE")?
79		}
80		write!(f, " {}", self.name)?;
81		if let Some(ref i) = self.function {
82			write!(f, " FUNCTION fn::{i}")?
83		}
84		if let Some(v) = &self.tokenizers {
85			let tokens: Vec<String> = v.iter().map(|f| f.to_string()).collect();
86			write!(f, " TOKENIZERS {}", tokens.join(","))?;
87		}
88		if let Some(v) = &self.filters {
89			let tokens: Vec<String> = v.iter().map(|f| f.to_string()).collect();
90			write!(f, " FILTERS {}", tokens.join(","))?;
91		}
92		if let Some(ref v) = self.comment {
93			write!(f, " COMMENT {v}")?
94		}
95		Ok(())
96	}
97}
98
99impl InfoStructure for DefineAnalyzerStatement {
100	fn structure(self) -> Value {
101		Value::from(map! {
102			"name".to_string() => self.name.structure(),
103			"function".to_string(), if let Some(v) = self.function => v.structure(),
104			"tokenizers".to_string(), if let Some(v) = self.tokenizers =>
105				v.into_iter().map(|v| v.to_string().into()).collect::<Array>().into(),
106			"filters".to_string(), if let Some(v) = self.filters =>
107				v.into_iter().map(|v| v.to_string().into()).collect::<Array>().into(),
108			"comment".to_string(), if let Some(v) = self.comment => v.into(),
109		})
110	}
111}