surrealdb_sql/statements/define/
function.rs1use crate::ctx::Context;
2use crate::dbs::{Options, Transaction};
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::iam::{Action, ResourceKind};
6use crate::{
7 fmt::{is_pretty, pretty_indent},
8 Base, Block, Ident, Kind, Permission, Strand, Value,
9};
10use derive::Store;
11use revision::revisioned;
12use serde::{Deserialize, Serialize};
13use std::fmt::{self, Display, Write};
14
15#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
16#[revisioned(revision = 1)]
17pub struct DefineFunctionStatement {
18 pub name: Ident,
19 pub args: Vec<(Ident, Kind)>,
20 pub block: Block,
21 pub comment: Option<Strand>,
22 pub permissions: Permission,
23}
24
25impl DefineFunctionStatement {
26 pub(crate) async fn compute(
28 &self,
29 _ctx: &Context<'_>,
30 opt: &Options,
31 txn: &Transaction,
32 _doc: Option<&CursorDoc<'_>>,
33 ) -> Result<Value, Error> {
34 opt.is_allowed(Action::Edit, ResourceKind::Function, &Base::Db)?;
36 let mut run = txn.lock().await;
38 run.clear_cache();
40 let key = crate::key::database::fc::new(opt.ns(), opt.db(), &self.name);
42 run.add_ns(opt.ns(), opt.strict).await?;
43 run.add_db(opt.ns(), opt.db(), opt.strict).await?;
44 run.set(key, self).await?;
45 Ok(Value::None)
47 }
48}
49
50impl fmt::Display for DefineFunctionStatement {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 write!(f, "DEFINE FUNCTION fn::{}(", self.name.0)?;
53 for (i, (name, kind)) in self.args.iter().enumerate() {
54 if i > 0 {
55 f.write_str(", ")?;
56 }
57 write!(f, "${name}: {kind}")?;
58 }
59 f.write_str(") ")?;
60 Display::fmt(&self.block, f)?;
61 if let Some(ref v) = self.comment {
62 write!(f, " COMMENT {v}")?
63 }
64 let _indent = if is_pretty() {
65 Some(pretty_indent())
66 } else {
67 f.write_char(' ')?;
68 None
69 };
70 write!(f, "PERMISSIONS {}", self.permissions)?;
71 Ok(())
72 }
73}