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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//! Diesel's `Insertable` implementation for [`VoluntaryServitude`]
//!
//! [`VoluntaryServitude`]: ../struct.VoluntaryServitude.html#implementations
//!
//! Batch Insert:
//!
//! Sqlite doesn't allow for batch inserts, it's implemented by diesel as a transaction of
//! individual insert queries, we can't implement the necessary traits to directly allow that.
//!
//! You have to crate a transaction and insert by yourself (it should be done in a transaction to
//! avoid locking and writing to file for each insert.
//!
//! [https://github.com/diesel-rs/diesel/issues/1177](https://github.com/diesel-rs/diesel/issues/1177)
//!
//! **Cargo.toml**
//!
//! ```toml
//! [dependencies]
//! voluntary_servitude = { version = "4", features = "diesel-traits" }
//! ```

use crate::{prelude::*, voluntary_servitude::Inner};
use diesel::{backend::*, insertable::*, query_builder::*, *};
use std::{marker::PhantomData, sync::Arc};

/// Helper type to integrate with `Diesel`
#[allow(missing_debug_implementations)]
pub struct InnerBatchInsert<'a, T, Tab>(Arc<Inner<T>>, PhantomData<(Tab, &'a T)>);

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(any(feature = "diesel-traits", feature = "diesel-sqlite")))
)]
impl<'a, T, Tab> Insertable<Tab> for &'a VoluntaryServitude<T>
where
    T: Insertable<Tab> + UndecoratedInsertRecord<Tab>,
{
    type Values = InnerBatchInsert<'a, T, Tab>;

    #[inline]
    fn values(self) -> Self::Values {
        InnerBatchInsert(self.inner(), PhantomData)
    }
}

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(any(feature = "diesel-traits", feature = "diesel-sqlite")))
)]
impl<'a, T, Tab> Insertable<Tab> for &'a Iter<T>
where
    T: Insertable<Tab> + UndecoratedInsertRecord<Tab>,
{
    type Values = InnerBatchInsert<'a, T, Tab>;

    #[inline]
    fn values(self) -> Self::Values {
        InnerBatchInsert(self.inner(), PhantomData)
    }
}

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(any(feature = "diesel-traits", feature = "diesel-sqlite")))
)]
impl<'a, T, Tab, DB, Inner> QueryFragment<DB> for InnerBatchInsert<'a, T, Tab>
where
    DB: Backend + SupportsDefaultKeyword,
    &'a T: Insertable<Tab, Values = ValuesClause<Inner, Tab>>,
    ValuesClause<Inner, Tab>: QueryFragment<DB>,
    Inner: QueryFragment<DB>,
{
    #[inline]
    fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
        let mut value = self.0.first_node().map(|nn| unsafe { &*nn.as_ptr() });
        if let Some(v) = value {
            v.value().values().walk_ast(out.reborrow())?;
            value = v.next();
        }

        while let Some(v) = value {
            out.push_sql(", (");
            v.value().values().walk_ast(out.reborrow())?;
            out.push_sql(")");
            value = v.next();
        }
        Ok(())
    }
}

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(any(feature = "diesel-traits", feature = "diesel-sqlite")))
)]
impl<'a, T, Table> UndecoratedInsertRecord<Table> for InnerBatchInsert<'a, T, Table> where
    T: UndecoratedInsertRecord<Table>
{
}

#[cfg_attr(
    docs_rs_workaround,
    doc(cfg(any(feature = "diesel-traits", feature = "diesel-sqlite")))
)]
impl<'a, T, Tab, DB> CanInsertInSingleQuery<DB> for InnerBatchInsert<'a, T, Tab>
where
    DB: Backend + SupportsDefaultKeyword,
{
    #[inline]
    fn rows_to_insert(&self) -> Option<usize> {
        Some(self.0.len())
    }
}

#[cfg(test)]
mod tests {
    #![allow(proc_macro_derive_resolution_fallback)]
    #![allow(unused_import_braces)]

    use diesel::{insert_into, prelude::*};

    table! {
        derives (id) {
            id -> Int4,
            name -> VarChar,
        }
    }

    #[derive(Queryable, Insertable, Clone, Debug)]
    struct Derive {
        name: String,
    }

    impl Derive {
        pub fn new<S: Into<String>>(s: S) -> Self {
            let name = s.into();
            Self { name }
        }
    }

    #[test]
    #[ignore]
    fn insert_query_mysql() {
        let conn = MysqlConnection::establish("127.0.0.1").unwrap();
        let vs = vs![
            Derive::new("Name1"),
            Derive::new("Name2"),
            Derive::new("Name3")
        ];

        let _ = insert_into(derives::table)
            .values(&vs)
            .execute(&conn)
            .unwrap();
        let queried: Vec<String> = derives::table.select(derives::name).load(&conn).unwrap();
        assert_eq!(
            vs.iter().map(|d| d.name.to_owned()).collect::<Vec<_>>(),
            queried
        );

        let _ = insert_into(derives::table)
            .values(&vs.iter().cloned().collect::<Vec<_>>())
            .execute(&conn)
            .unwrap();
        let queried: Vec<String> = derives::table.select(derives::name).load(&conn).unwrap();
        assert_eq!(
            vs.iter().map(|d| d.name.to_owned()).collect::<Vec<_>>(),
            queried
        );
    }

    #[test]
    #[ignore]
    fn insert_query_postgres() {
        let conn = PgConnection::establish("127.0.0.1").unwrap();
        let vs = vs![
            Derive::new("Name1"),
            Derive::new("Name2"),
            Derive::new("Name3")
        ];

        let _ = insert_into(derives::table)
            .values(&vs)
            .execute(&conn)
            .unwrap();
        let queried: Vec<String> = derives::table.select(derives::name).load(&conn).unwrap();
        assert_eq!(
            vs.iter().map(|d| d.name.to_owned()).collect::<Vec<_>>(),
            queried
        );

        let _ = insert_into(derives::table)
            .values(&vs.iter().cloned().collect::<Vec<_>>())
            .execute(&conn)
            .unwrap();
        let queried: Vec<String> = derives::table.select(derives::name).load(&conn).unwrap();
        assert_eq!(
            vs.iter().map(|d| d.name.to_owned()).collect::<Vec<_>>(),
            queried
        );
    }
}