toasty_core/stmt/
insert_target.rs

1use super::{Expr, InsertTable, Query};
2use crate::schema::app::ModelId;
3
4#[derive(Debug, Clone, PartialEq)]
5pub enum InsertTarget {
6    /// Inserting into a scope implies that the inserted value should be
7    /// included by the query after insertion. This could be a combination of
8    /// setting default field values or validating existing ones.
9    Scope(Box<Query>),
10
11    /// Insert a model
12    Model(ModelId),
13
14    /// Insert into a table
15    Table(InsertTable),
16}
17
18impl InsertTarget {
19    pub fn is_model(&self) -> bool {
20        matches!(self, InsertTarget::Model(..))
21    }
22
23    pub fn as_model_unwrap(&self) -> ModelId {
24        match self {
25            Self::Scope(query) => query.body.as_select_unwrap().source.model_id_unwrap(),
26            Self::Model(model_id) => *model_id,
27            _ => todo!(),
28        }
29    }
30
31    pub fn is_table(&self) -> bool {
32        matches!(self, InsertTarget::Table(..))
33    }
34
35    pub fn as_table_unwrap(&self) -> &InsertTable {
36        match self {
37            Self::Table(table) => table,
38            _ => todo!(),
39        }
40    }
41
42    pub fn add_constraint(&mut self, expr: impl Into<Expr>) {
43        let expr = expr.into();
44        match self {
45            Self::Scope(query) => query.add_filter(expr),
46            Self::Model(model_id) => {
47                *self = Self::Scope(Box::new(Query::new_select(*model_id, expr)));
48            }
49            _ => todo!("{self:#?}"),
50        }
51    }
52}
53
54impl From<Query> for InsertTarget {
55    fn from(value: Query) -> Self {
56        Self::Scope(Box::new(value))
57    }
58}