use std::collections::HashMap;
use std::sync::Arc;
use crate::builder::{Condition, JoinType};
use crate::error::{Error, Result};
use crate::value::{Array, IntoValues, Value};
pub trait Filter: Send + Sync {
fn filter(&self, table: &str) -> Result<Condition>;
}
pub trait Attribute: Send + Sync {
fn resolve(&self, attribute: &str) -> Result<String>;
}
pub trait JoinFilter: Send + Sync {
fn filter_join(&self, table: &str, join_type: JoinType) -> Result<Option<JoinCondition>>;
}
pub trait Write: Send + Sync {
fn decorate_row(&self, row: Array, metadata: &Array) -> Result<Array>;
fn after_create(&self, table: &str, metadata: &Array, context: &Value) -> Result<()>;
fn after_update(&self, table: &str, metadata: &Array, context: &Value) -> Result<()>;
fn after_batch_update(&self, table: &str, update_data: &Array, metadata: &Array, context: &Value) -> Result<()>;
fn after_delete(&self, table: &str, ids: &Array, context: &Value) -> Result<()>;
}
#[derive(Clone, Default)]
pub struct Hook {
pub filter: Option<Arc<dyn Filter>>,
pub attribute: Option<Arc<dyn Attribute>>,
pub join_filter: Option<Arc<dyn JoinFilter>>,
}
impl Hook {
pub fn filter(filter: impl Filter + 'static) -> Self {
Hook { filter: Some(Arc::new(filter)), ..Hook::default() }
}
pub fn attribute(attribute: impl Attribute + 'static) -> Self {
Hook { attribute: Some(Arc::new(attribute)), ..Hook::default() }
}
pub fn join_filter(join_filter: impl JoinFilter + 'static) -> Self {
Hook { join_filter: Some(Arc::new(join_filter)), ..Hook::default() }
}
}
impl From<Tenant> for Hook {
fn from(tenant: Tenant) -> Self {
let tenant = Arc::new(tenant);
Hook { filter: Some(tenant.clone()), attribute: None, join_filter: Some(tenant) }
}
}
impl From<Map> for Hook {
fn from(map: Map) -> Self {
Hook::attribute(map)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Placement {
On,
Where,
}
impl Placement {
pub fn name(self) -> &'static str {
match self {
Placement::On => "On",
Placement::Where => "Where",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct JoinCondition {
pub condition: Condition,
pub placement: Placement,
}
impl JoinCondition {
pub fn new(condition: Condition, placement: Placement) -> Self {
JoinCondition { condition, placement }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Tenant {
tenant_ids: Vec<Value>,
column: String,
}
impl Tenant {
pub fn new(tenant_ids: impl IntoValues, column: impl Into<String>) -> Result<Self> {
let column = column.into();
if !is_column_name(&column) {
return Err(Error::InvalidArgument(format!("Invalid column name: {column}")));
}
Ok(Tenant { tenant_ids: tenant_ids.into_values().values().cloned().collect(), column })
}
}
pub(crate) fn is_column_name(name: &str) -> bool {
let bytes = name.as_bytes();
match bytes.split_first() {
Some((first, rest)) => {
(first.is_ascii_alphabetic() || *first == b'_')
&& rest.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'.')
}
None => false,
}
}
impl Filter for Tenant {
fn filter(&self, _table: &str) -> Result<Condition> {
if self.tenant_ids.is_empty() {
return Ok(Condition::new("1 = 0", Vec::new()));
}
let placeholders = vec!["?"; self.tenant_ids.len()].join(", ");
Ok(Condition::new(format!("{} IN ({placeholders})", self.column), self.tenant_ids.clone()))
}
}
impl JoinFilter for Tenant {
fn filter_join(&self, table: &str, join_type: JoinType) -> Result<Option<JoinCondition>> {
let condition = self.filter(table)?;
let placement = match join_type {
JoinType::Left | JoinType::Right => Placement::On,
_ => Placement::Where,
};
Ok(Some(JoinCondition::new(condition, placement)))
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Map {
map: HashMap<String, String>,
}
impl Map {
pub fn new<K: Into<String>, V: Into<String>>(map: impl IntoIterator<Item = (K, V)>) -> Self {
Map { map: map.into_iter().map(|(k, v)| (k.into(), v.into())).collect() }
}
}
impl Attribute for Map {
fn resolve(&self, attribute: &str) -> Result<String> {
Ok(self.map.get(attribute).cloned().unwrap_or_else(|| attribute.to_owned()))
}
}