use std::marker::PhantomData;
use ruprizzle_core::ir::ReferentialAction;
use crate::BoxFuture;
use crate::compile::{CompiledSql, delete, select, update};
use crate::error::Error;
use crate::executor::Executor;
use crate::filter::FilterNode;
use crate::model::Model;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelAction {
Connect,
Disconnect,
Set,
}
pub type DeleteAction = ReferentialAction;
pub struct RelWrite<M: Model, C: Model> {
action: RelAction,
child_fk_col: &'static str,
child_pk_col: &'static str,
pks: Vec<Value>,
get_parent_pk: fn(&M) -> Value,
_marker: PhantomData<fn() -> C>,
}
impl<M: Model, C: Model> RelWrite<M, C> {
#[allow(clippy::too_many_arguments)]
pub fn new(
action: RelAction,
child_fk_col: &'static str,
child_pk_col: &'static str,
pks: Vec<Value>,
get_parent_pk: fn(&M) -> Value,
) -> Self {
Self {
action,
child_fk_col,
child_pk_col,
pks,
get_parent_pk,
_marker: PhantomData,
}
}
pub fn parent_pk(&self, parent: &M) -> Value {
(self.get_parent_pk)(parent)
}
pub async fn execute_update<'a>(
&'a self,
exec: &'a dyn Executor,
parent_pk: Value,
) -> Result<u64, Error> {
match self.action {
RelAction::Connect => self.connect(exec, parent_pk).await,
RelAction::Disconnect => self.disconnect(exec, parent_pk).await,
RelAction::Set => self.set(exec, parent_pk).await,
}
}
async fn connect(&self, exec: &dyn Executor, parent_pk: Value) -> Result<u64, Error> {
let dialect = exec.dialect();
let filter = FilterNode::In {
table: C::TABLE,
column: self.child_pk_col,
values: self.pks.clone(),
negated: false,
};
let compiled = update::<M>(
dialect,
C::TABLE,
&[(self.child_fk_col, parent_pk)],
&filter,
&[],
);
exec.execute_raw(compiled.sql, compiled.binds).await
}
async fn disconnect(&self, exec: &dyn Executor, parent_pk: Value) -> Result<u64, Error> {
let dialect = exec.dialect();
let filter = FilterNode::And(vec![
FilterNode::In {
table: C::TABLE,
column: self.child_pk_col,
values: self.pks.clone(),
negated: false,
},
FilterNode::Cmp {
table: C::TABLE,
column: self.child_fk_col,
op: crate::filter::CmpOp::Eq,
value: parent_pk,
},
]);
let compiled = update::<M>(
dialect,
C::TABLE,
&[(self.child_fk_col, Value::Null)],
&filter,
&[],
);
exec.execute_raw(compiled.sql, compiled.binds).await
}
async fn set(&self, exec: &dyn Executor, parent_pk: Value) -> Result<u64, Error> {
let mut total = self.disconnect_all(exec, parent_pk.clone()).await?;
total += self.connect(exec, parent_pk).await?;
Ok(total)
}
async fn disconnect_all(&self, exec: &dyn Executor, parent_pk: Value) -> Result<u64, Error> {
let dialect = exec.dialect();
let filter = FilterNode::Cmp {
table: C::TABLE,
column: self.child_fk_col,
op: crate::filter::CmpOp::Eq,
value: parent_pk,
};
let compiled = update::<M>(
dialect,
C::TABLE,
&[(self.child_fk_col, Value::Null)],
&filter,
&[],
);
exec.execute_raw(compiled.sql, compiled.binds).await
}
}
impl<M: Model, C: Model> std::fmt::Debug for RelWrite<M, C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RelWrite")
.field("action", &self.action)
.field("child_table", &C::TABLE)
.field("child_fk_col", &self.child_fk_col)
.field("child_pk_col", &self.child_pk_col)
.field("pks", &self.pks)
.finish_non_exhaustive()
}
}
pub(crate) trait AnyRelWrite<M: Model>: Send + Sync + std::fmt::Debug {
fn parent_pk(&self, parent: &M) -> Value;
fn execute_update<'a>(
&'a self,
exec: &'a dyn Executor,
parent_pk: Value,
) -> BoxFuture<'a, Result<u64, Error>>;
}
impl<M: Model, C: Model> AnyRelWrite<M> for RelWrite<M, C> {
fn parent_pk(&self, parent: &M) -> Value {
RelWrite::parent_pk(self, parent)
}
fn execute_update<'a>(
&'a self,
exec: &'a dyn Executor,
parent_pk: Value,
) -> BoxFuture<'a, Result<u64, Error>> {
Box::pin(self.execute_update(exec, parent_pk))
}
}
pub struct DeleteCascade<C: Model> {
child_fk_col: &'static str,
action: DeleteAction,
_marker: PhantomData<C>,
}
impl<C: Model> DeleteCascade<C> {
pub fn new(child_fk_col: &'static str, action: DeleteAction) -> Self {
Self {
child_fk_col,
action,
_marker: PhantomData,
}
}
pub async fn execute_delete<'a, M: Model>(
&'a self,
exec: &'a dyn Executor,
parent_subquery: CompiledSql,
) -> Result<u64, Error> {
match self.action {
DeleteAction::NoAction => Ok(0),
DeleteAction::Cascade => self.cascade::<M>(exec, parent_subquery).await,
DeleteAction::SetNull => self.set_null::<M>(exec, parent_subquery).await,
DeleteAction::Restrict => self.restrict(exec, parent_subquery).await,
DeleteAction::SetDefault => Err(Error::Message(
"SET DEFAULT is not supported for cascaded deletes".into(),
)),
}
}
fn child_filter(&self, parent_subquery: CompiledSql) -> FilterNode {
FilterNode::InSubquery {
table: C::TABLE,
column: self.child_fk_col,
subquery: parent_subquery,
negated: false,
}
}
async fn cascade<M: Model>(
&self,
exec: &dyn Executor,
parent_subquery: CompiledSql,
) -> Result<u64, Error> {
let dialect = exec.dialect();
let filter = self.child_filter(parent_subquery);
let compiled = delete::<M>(dialect, C::TABLE, &filter, &[]);
exec.execute_raw(compiled.sql, compiled.binds).await
}
async fn set_null<M: Model>(
&self,
exec: &dyn Executor,
parent_subquery: CompiledSql,
) -> Result<u64, Error> {
let dialect = exec.dialect();
let filter = self.child_filter(parent_subquery);
let compiled = update::<M>(
dialect,
C::TABLE,
&[(self.child_fk_col, Value::Null)],
&filter,
&[],
);
exec.execute_raw(compiled.sql, compiled.binds).await
}
async fn restrict(
&self,
exec: &dyn Executor,
parent_subquery: CompiledSql,
) -> Result<u64, Error> {
let dialect = exec.dialect();
let filter = self.child_filter(parent_subquery);
let compiled = select::<C>(dialect, C::TABLE, &[], &filter, &[], Some(1), None, false);
let batch = exec.fetch_all_raw(compiled.sql, compiled.binds).await?;
if !batch.is_empty() {
return Err(Error::Message(format!(
"cannot delete parent: child rows exist in {}",
C::TABLE
)));
}
Ok(0)
}
}
impl<C: Model> std::fmt::Debug for DeleteCascade<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DeleteCascade")
.field("child_table", &C::TABLE)
.field("child_fk_col", &self.child_fk_col)
.field("action", &self.action)
.finish()
}
}
pub(crate) trait AnyRelDelete<M: Model>: Send + Sync + std::fmt::Debug {
fn execute_delete<'a>(
&'a self,
exec: &'a dyn Executor,
parent_subquery: CompiledSql,
) -> BoxFuture<'a, Result<u64, Error>>;
}
impl<M: Model, C: Model> AnyRelDelete<M> for DeleteCascade<C> {
fn execute_delete<'a>(
&'a self,
exec: &'a dyn Executor,
parent_subquery: CompiledSql,
) -> BoxFuture<'a, Result<u64, Error>> {
Box::pin(self.execute_delete::<M>(exec, parent_subquery))
}
}