use surrealdb_types::ToSql;
use crate::expr::Expr;
use crate::expr::statements::info::InfoStructure;
use crate::sql;
use crate::val::Value;
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
pub enum Permission {
None,
#[default]
Full,
Specific(Expr),
}
impl Permission {
pub fn has_direct_write(&self) -> bool {
match self {
Permission::None | Permission::Full => false,
Permission::Specific(expr) => expr.has_direct_write(),
}
}
pub fn to_sql_permission(&self) -> sql::Permission {
match self {
Permission::None => sql::Permission::None,
Permission::Full => sql::Permission::Full,
Permission::Specific(e) => sql::Permission::Specific(e.clone().into()),
}
}
}
impl InfoStructure for Permission {
fn structure(self) -> Value {
match self {
Permission::None => Value::Bool(false),
Permission::Full => Value::Bool(true),
Permission::Specific(e) => Value::from(e.to_stored_sql()),
}
}
}
impl ToSql for Permission {
fn fmt_sql(&self, f: &mut String, _fmt: surrealdb_types::SqlFormat) {
match self {
Self::None => f.push_str("NONE"),
Self::Full => f.push_str("FULL"),
Self::Specific(e) => {
f.push_str("WHERE ");
f.push_str(&e.to_stored_sql());
}
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
pub struct Permissions {
pub select: Permission,
pub create: Permission,
pub update: Permission,
pub delete: Permission,
}
impl Permissions {
pub fn to_sql_permissions(&self) -> sql::Permissions {
sql::Permissions {
select: self.select.to_sql_permission(),
create: self.create.to_sql_permission(),
update: self.update.to_sql_permission(),
delete: self.delete.to_sql_permission(),
}
}
}
impl InfoStructure for Permissions {
fn structure(self) -> Value {
Value::from(map! {
"select" => self.select.structure(),
"create" => self.create.structure(),
"update" => self.update.structure(),
"delete" => self.delete.structure(),
})
}
}
impl ToSql for Permissions {
fn fmt_sql(&self, f: &mut String, fmt: surrealdb_types::SqlFormat) {
self.to_sql_permissions().fmt_sql(f, fmt)
}
}
impl Permission {
pub fn is_none(&self) -> bool {
matches!(self, Self::None)
}
pub fn is_specific(&self) -> bool {
matches!(self, Self::Specific(_))
}
}
impl Permissions {
pub fn has_direct_write(&self) -> bool {
self.select.has_direct_write()
|| self.create.has_direct_write()
|| self.update.has_direct_write()
|| self.delete.has_direct_write()
}
}