1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use crate::Result;
use futures::future::BoxFuture;
pub use sqlmo::query::OnConflict;
#[allow(unused_imports)]
use sqlmo::{Dialect, Insert, ToSql};

/// Represents an insert query.
/// We had to turn this into a model because we need to pass in the on_conflict configuration.
pub struct Insertion<'a, Acquire, Model, DB: sqlx::Database> {
    pub acquire: Acquire,
    pub model: Model,
    pub closure: Box<dyn 'static + Send + FnOnce(Acquire, Model, String) -> BoxFuture<'a, Result<Model>>>,
    pub insert: Insert,
    pub _db: std::marker::PhantomData<DB>,
}

impl<'a, Acquire, Model, DB: sqlx::Database> Insertion<'a, Acquire, Model, DB> {
    pub fn on_conflict(mut self, c: OnConflict) -> Self {
        self.insert.on_conflict = c;
        self
    }
}

impl<'a, Acquire, Model: crate::model::Model<DB>, DB: sqlx::Database> std::future::IntoFuture
    for Insertion<'a, Acquire, Model, DB>
{
    type Output = Result<Model>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        let q = self.insert.to_sql(Dialect::Postgres);
        (self.closure)(self.acquire, self.model, q)
    }
}