Skip to main content

diesel/query_builder/insert_statement/
insert_with_default_for_sqlite.rs

1use super::{BatchInsert, InsertStatement};
2use crate::insertable::{
3    CanInsertInSingleQuery, ColumnInsertValue, DefaultableColumnInsertValue, InsertValues,
4};
5use crate::prelude::*;
6use crate::query_builder::debug_query::DebugBinds;
7use crate::query_builder::returning::ReturningClause;
8use crate::query_builder::upsert::on_conflict_clause::OnConflictValues;
9use crate::query_builder::{
10    AstPass, DebugQuery, QueryBuilder, QueryFragment, QueryId, ValuesClause,
11};
12use crate::query_dsl::LoadQuery;
13use crate::query_dsl::methods::ExecuteDsl;
14use crate::sqlite::{Sqlite, SqliteQueryBuilder};
15use alloc::string::{String, ToString};
16use alloc::vec::Vec;
17use core::fmt::{self, Debug, Display};
18
19pub trait DebugQueryHelper<ContainsDefaultableValue> {
20    fn fmt_debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
21    fn fmt_display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
22}
23
24impl<T, V, QId, Op, Ret, const STATIC_QUERY_ID: bool> DebugQueryHelper<Yes>
25    for DebugQuery<
26        '_,
27        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op, Ret>,
28        Sqlite,
29    >
30where
31    V: QueryFragment<Sqlite>,
32    T: Copy + QuerySource,
33    Op: Copy,
34    Ret: Copy,
35    for<'b> InsertStatement<T, &'b ValuesClause<V, T>, Op, Ret>: QueryFragment<Sqlite>,
36{
37    fn fmt_debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        let mut statements = alloc::vec![String::from("BEGIN")];
39        for record in self.query.records.values.iter() {
40            let stmt = InsertStatement::new(
41                self.query.target,
42                record,
43                self.query.operator,
44                self.query.returning,
45            );
46            statements.push(crate::debug_query(&stmt).to_string());
47        }
48        statements.push("COMMIT".into());
49
50        f.debug_struct("Query")
51            .field("sql", &statements)
52            .field("binds", &[] as &[i32; 0])
53            .finish()
54    }
55
56    fn fmt_display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        writeln!(f, "BEGIN;")?;
58        for record in self.query.records.values.iter() {
59            let stmt = InsertStatement::new(
60                self.query.target,
61                record,
62                self.query.operator,
63                self.query.returning,
64            );
65            writeln!(f, "{}", crate::debug_query(&stmt))?;
66        }
67        writeln!(f, "COMMIT;")?;
68        Ok(())
69    }
70}
71
72impl<'a, T, V, QId, Op, const STATIC_QUERY_ID: bool> DebugQueryHelper<No>
73    for DebugQuery<
74        'a,
75        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>,
76        Sqlite,
77    >
78where
79    T: Copy + Table,
80    Op: Copy + QueryFragment<Sqlite>,
81    SqliteBatchInsertWrapper<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>:
82        QueryFragment<Sqlite>,
83    V: CanInsertInSingleQuery<Sqlite>,
84    T::FromClause: QueryFragment<Sqlite>,
85{
86    fn fmt_debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        self.fmt_helper(f, crate::query_builder::debug_query::debug)
88    }
89
90    fn fmt_display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        self.fmt_helper(f, crate::query_builder::debug_query::display)
92    }
93}
94
95#[allow(unsafe_code)] // cast to transparent wrapper type
96impl<'a, T, V, QId, Op, const STATIC_QUERY_ID: bool>
97    DebugQuery<
98        'a,
99        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>,
100        Sqlite,
101    >
102where
103    T: Copy + Table,
104    Op: Copy + QueryFragment<Sqlite>,
105    SqliteBatchInsertWrapper<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>:
106        QueryFragment<Sqlite>,
107    V: CanInsertInSingleQuery<Sqlite>,
108    T::FromClause: QueryFragment<Sqlite>,
109{
110    fn fmt_helper(
111        &self,
112        f: &mut fmt::Formatter<'_>,
113        formatter: fn(String, &DebugBinds<'_>, &mut fmt::Formatter<'_>) -> fmt::Result,
114    ) -> fmt::Result {
115        // explicit destruct to make sure we use all  the fields
116        let InsertStatement {
117            operator,
118            target: _,
119            records,
120            returning,
121            into_clause,
122        } = self.query;
123        let records = unsafe {
124            // SAFETY:
125            // * SqliteBatchInsertWrapper is `#[repr(transparent)]` so this cast
126            // is allowed
127            &*(records as *const _
128                as *const SqliteBatchInsertWrapper<
129                    Vec<ValuesClause<V, T>>,
130                    T,
131                    QId,
132                    STATIC_QUERY_ID,
133                >)
134        };
135        let mut buffer = Vec::new();
136        let ast_pass = AstPass::debug_binds(&mut buffer, &Sqlite);
137        super::insert_statement::walk_ast_intern::<T, _, _, _, Sqlite>(
138            ast_pass,
139            records,
140            into_clause,
141            operator,
142            returning,
143        )
144        .map_err(|_| fmt::Error)?;
145        let mut query_builder = SqliteQueryBuilder::default();
146        let mut ast_pass_to_sql_options = Default::default();
147        let sql_pass = AstPass::to_sql(&mut query_builder, &mut ast_pass_to_sql_options, &Sqlite);
148        super::insert_statement::walk_ast_intern::<T, _, _, _, Sqlite>(
149            sql_pass,
150            records,
151            into_clause,
152            operator,
153            returning,
154        )
155        .map_err(|_| fmt::Error)?;
156        let query = query_builder.finish();
157        let debug_binds = crate::query_builder::debug_query::DebugBinds::new(&buffer);
158        formatter(query, &debug_binds, f)
159    }
160}
161
162impl<T, V, QId, Op, O, const STATIC_QUERY_ID: bool> Display
163    for DebugQuery<
164        '_,
165        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>,
166        Sqlite,
167    >
168where
169    T: QuerySource,
170    V: ContainsDefaultableValue<Out = O>,
171    Self: DebugQueryHelper<O>,
172{
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        self.fmt_display(f)
175    }
176}
177
178impl<T, V, QId, Op, O, const STATIC_QUERY_ID: bool> Debug
179    for DebugQuery<
180        '_,
181        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>,
182        Sqlite,
183    >
184where
185    T: QuerySource,
186    V: ContainsDefaultableValue<Out = O>,
187    Self: DebugQueryHelper<O>,
188{
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        self.fmt_debug(f)
191    }
192}
193
194#[allow(missing_debug_implementations, missing_copy_implementations)]
195pub struct Yes;
196
197impl Default for Yes {
198    fn default() -> Self {
199        Yes
200    }
201}
202
203#[allow(missing_debug_implementations, missing_copy_implementations)]
204pub struct No;
205
206impl Default for No {
207    fn default() -> Self {
208        No
209    }
210}
211
212pub trait Any<Rhs> {
213    type Out: Any<Yes> + Any<No>;
214}
215
216impl Any<No> for No {
217    type Out = No;
218}
219
220impl Any<Yes> for No {
221    type Out = Yes;
222}
223
224impl Any<No> for Yes {
225    type Out = Yes;
226}
227
228impl Any<Yes> for Yes {
229    type Out = Yes;
230}
231
232pub trait ContainsDefaultableValue {
233    type Out: Any<Yes> + Any<No>;
234}
235
236impl<C, B> ContainsDefaultableValue for ColumnInsertValue<C, B> {
237    type Out = No;
238}
239
240impl<I> ContainsDefaultableValue for DefaultableColumnInsertValue<I> {
241    type Out = Yes;
242}
243
244impl<I, const SIZE: usize> ContainsDefaultableValue for [I; SIZE]
245where
246    I: ContainsDefaultableValue,
247{
248    type Out = I::Out;
249}
250
251impl<I, T> ContainsDefaultableValue for ValuesClause<I, T>
252where
253    I: ContainsDefaultableValue,
254{
255    type Out = I::Out;
256}
257
258impl<T> ContainsDefaultableValue for &T
259where
260    T: ContainsDefaultableValue,
261{
262    type Out = T::Out;
263}
264
265impl<V, T, QId, C, Op, O, const STATIC_QUERY_ID: bool> ExecuteDsl<C, Sqlite>
266    for InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>
267where
268    T: QuerySource,
269    C: Connection<Backend = Sqlite>,
270    V: ContainsDefaultableValue<Out = O>,
271    O: Default,
272    (O, Self): ExecuteDsl<C, Sqlite>,
273{
274    fn execute(query: Self, conn: &mut C) -> QueryResult<usize> {
275        <(O, Self) as ExecuteDsl<C, Sqlite>>::execute((O::default(), query), conn)
276    }
277}
278
279impl<V, T, QId, C, Op, O, Target, ConflictOpt, const STATIC_QUERY_ID: bool> ExecuteDsl<C, Sqlite>
280    for InsertStatement<
281        T,
282        OnConflictValues<
283            BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
284            Target,
285            ConflictOpt,
286        >,
287        Op,
288    >
289where
290    T: QuerySource,
291    C: Connection<Backend = Sqlite>,
292    V: ContainsDefaultableValue<Out = O>,
293    O: Default,
294    (O, Self): ExecuteDsl<C, Sqlite>,
295{
296    fn execute(query: Self, conn: &mut C) -> QueryResult<usize> {
297        <(O, Self) as ExecuteDsl<C, Sqlite>>::execute((O::default(), query), conn)
298    }
299}
300
301impl<V, T, QId, C, Op, const STATIC_QUERY_ID: bool> ExecuteDsl<C, Sqlite>
302    for (
303        Yes,
304        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>,
305    )
306where
307    C: Connection<Backend = Sqlite>,
308    T: Table + Copy + QueryId + 'static,
309    T::FromClause: QueryFragment<Sqlite>,
310    Op: Copy + QueryId + QueryFragment<Sqlite>,
311    V: InsertValues<Sqlite, T> + CanInsertInSingleQuery<Sqlite> + QueryId,
312{
313    fn execute((Yes, query): Self, conn: &mut C) -> QueryResult<usize> {
314        conn.transaction(|conn| {
315            let mut result = 0;
316            for record in &query.records.values {
317                let stmt =
318                    InsertStatement::new(query.target, record, query.operator, query.returning);
319                result += stmt.execute(conn)?;
320            }
321            Ok(result)
322        })
323    }
324}
325
326impl<'query, V, T, QId, Op, O, U, B, const STATIC_QUERY_ID: bool>
327    LoadQuery<'query, SqliteConnection, U, B>
328    for InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>
329where
330    T: QuerySource,
331    V: ContainsDefaultableValue<Out = O>,
332    O: Default,
333    (O, Self): LoadQuery<'query, SqliteConnection, U, B>,
334{
335    type RowIter<'conn> = <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::RowIter<'conn>;
336
337    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
338        <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::internal_load(
339            (O::default(), self),
340            conn,
341        )
342    }
343}
344
345impl<'query, V, T, QId, Op, Ret, O, U, B, const STATIC_QUERY_ID: bool>
346    LoadQuery<'query, SqliteConnection, U, B>
347    for InsertStatement<
348        T,
349        BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
350        Op,
351        ReturningClause<Ret>,
352    >
353where
354    T: QuerySource,
355    V: ContainsDefaultableValue<Out = O>,
356    O: Default,
357    (O, Self): LoadQuery<'query, SqliteConnection, U, B>,
358{
359    type RowIter<'conn> = <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::RowIter<'conn>;
360
361    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
362        <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::internal_load(
363            (O::default(), self),
364            conn,
365        )
366    }
367}
368
369impl<'query, V, T, QId, Op, O, U, B, Target, ConflictOpt, const STATIC_QUERY_ID: bool>
370    LoadQuery<'query, SqliteConnection, U, B>
371    for InsertStatement<
372        T,
373        OnConflictValues<
374            BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
375            Target,
376            ConflictOpt,
377        >,
378        Op,
379    >
380where
381    T: QuerySource,
382    V: ContainsDefaultableValue<Out = O>,
383    O: Default,
384    (O, Self): LoadQuery<'query, SqliteConnection, U, B>,
385{
386    type RowIter<'conn> = <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::RowIter<'conn>;
387
388    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
389        <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::internal_load(
390            (O::default(), self),
391            conn,
392        )
393    }
394}
395
396impl<'query, V, T, QId, Op, Ret, O, U, B, Target, ConflictOpt, const STATIC_QUERY_ID: bool>
397    LoadQuery<'query, SqliteConnection, U, B>
398    for InsertStatement<
399        T,
400        OnConflictValues<
401            BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
402            Target,
403            ConflictOpt,
404        >,
405        Op,
406        ReturningClause<Ret>,
407    >
408where
409    T: QuerySource,
410    V: ContainsDefaultableValue<Out = O>,
411    O: Default,
412    (O, Self): LoadQuery<'query, SqliteConnection, U, B>,
413{
414    type RowIter<'conn> = <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::RowIter<'conn>;
415
416    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
417        <(O, Self) as LoadQuery<'query, SqliteConnection, U, B>>::internal_load(
418            (O::default(), self),
419            conn,
420        )
421    }
422}
423
424impl<V, T, QId, Op, O, const STATIC_QUERY_ID: bool> RunQueryDsl<SqliteConnection>
425    for (
426        O,
427        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>,
428    )
429where
430    T: QuerySource,
431    V: ContainsDefaultableValue<Out = O>,
432    O: Default,
433    InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op>:
434        RunQueryDsl<SqliteConnection>,
435{
436}
437
438impl<V, T, QId, Op, Ret, O, const STATIC_QUERY_ID: bool> RunQueryDsl<SqliteConnection>
439    for (
440        O,
441        InsertStatement<
442            T,
443            BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
444            Op,
445            ReturningClause<Ret>,
446        >,
447    )
448where
449    T: QuerySource,
450    V: ContainsDefaultableValue<Out = O>,
451    O: Default,
452    InsertStatement<
453        T,
454        BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
455        Op,
456        ReturningClause<Ret>,
457    >: RunQueryDsl<SqliteConnection>,
458{
459}
460
461impl<V, T, QId, Op, O, Target, ConflictOpt, const STATIC_QUERY_ID: bool>
462    RunQueryDsl<SqliteConnection>
463    for (
464        O,
465        InsertStatement<
466            T,
467            OnConflictValues<
468                BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
469                Target,
470                ConflictOpt,
471            >,
472            Op,
473        >,
474    )
475where
476    T: QuerySource,
477    V: ContainsDefaultableValue<Out = O>,
478    O: Default,
479    InsertStatement<
480        T,
481        OnConflictValues<
482            BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
483            Target,
484            ConflictOpt,
485        >,
486        Op,
487    >: RunQueryDsl<SqliteConnection>,
488{
489}
490
491impl<V, T, QId, Op, Ret, O, Target, ConflictOpt, const STATIC_QUERY_ID: bool>
492    RunQueryDsl<SqliteConnection>
493    for (
494        O,
495        InsertStatement<
496            T,
497            OnConflictValues<
498                BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
499                Target,
500                ConflictOpt,
501            >,
502            Op,
503            ReturningClause<Ret>,
504        >,
505    )
506where
507    T: QuerySource,
508    V: ContainsDefaultableValue<Out = O>,
509    O: Default,
510    InsertStatement<
511        T,
512        OnConflictValues<
513            BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
514            Target,
515            ConflictOpt,
516        >,
517        Op,
518        ReturningClause<Ret>,
519    >: RunQueryDsl<SqliteConnection>,
520{
521}
522
523#[diagnostic::do_not_recommend]
524impl<'query, V, T, QId, Op, Ret, U, B, const STATIC_QUERY_ID: bool>
525    LoadQuery<'query, SqliteConnection, U, B>
526    for (
527        Yes,
528        InsertStatement<T, BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>, Op, Ret>,
529    )
530where
531    T: Table + Copy + QueryId + 'static,
532    Op: Copy + QueryId + QueryFragment<Sqlite>,
533    Ret: Copy,
534    InsertStatement<T, ValuesClause<V, T>, Op, Ret>: LoadQuery<'query, SqliteConnection, U, B>,
535    Self: RunQueryDsl<SqliteConnection>,
536{
537    type RowIter<'conn> = alloc::vec::IntoIter<QueryResult<U>>;
538
539    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
540        let (Yes, query) = self;
541
542        conn.transaction(|conn| {
543            let mut results = Vec::with_capacity(query.records.values.len());
544
545            for record in query.records.values {
546                let stmt =
547                    InsertStatement::new(query.target, record, query.operator, query.returning);
548
549                let result = stmt
550                    .internal_load(conn)?
551                    .next()
552                    .ok_or(crate::result::Error::NotFound)?;
553
554                match &result {
555                    Ok(_) | Err(crate::result::Error::DeserializationError(_)) => {
556                        results.push(result)
557                    }
558                    Err(_) => {
559                        result?;
560                    }
561                };
562            }
563
564            Ok(results.into_iter())
565        })
566    }
567}
568
569#[diagnostic::do_not_recommend]
570impl<'query, V, T, QId, Op, Ret, U, B, Target, ConflictOpt, const STATIC_QUERY_ID: bool>
571    LoadQuery<'query, SqliteConnection, U, B>
572    for (
573        Yes,
574        InsertStatement<
575            T,
576            OnConflictValues<
577                BatchInsert<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>,
578                Target,
579                ConflictOpt,
580            >,
581            Op,
582            Ret,
583        >,
584    )
585where
586    T: Table + Copy + QueryId + 'static,
587    T::FromClause: Copy,
588    Op: Copy,
589    Ret: Copy,
590    Target: Copy,
591    ConflictOpt: Copy,
592    InsertStatement<T, OnConflictValues<ValuesClause<V, T>, Target, ConflictOpt>, Op, Ret>:
593        LoadQuery<'query, SqliteConnection, U, B>,
594    Self: RunQueryDsl<SqliteConnection>,
595{
596    type RowIter<'conn> = alloc::vec::IntoIter<QueryResult<U>>;
597
598    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
599        let (Yes, query) = self;
600
601        conn.transaction(|conn| {
602            let mut results = Vec::with_capacity(query.records.values.values.len());
603
604            for record in query.records.values.values {
605                let stmt = InsertStatement {
606                    operator: query.operator,
607                    target: query.target,
608                    records: OnConflictValues {
609                        values: record,
610                        target: query.records.target,
611                        action: query.records.action,
612                        where_clause: query.records.where_clause,
613                    },
614                    returning: query.returning,
615                    into_clause: query.into_clause,
616                };
617
618                let result = stmt
619                    .internal_load(conn)?
620                    .next()
621                    .ok_or(crate::result::Error::NotFound)?;
622
623                match &result {
624                    Ok(_) | Err(crate::result::Error::DeserializationError(_)) => {
625                        results.push(result)
626                    }
627                    Err(_) => {
628                        result?;
629                    }
630                };
631            }
632
633            Ok(results.into_iter())
634        })
635    }
636}
637
638#[allow(missing_debug_implementations, missing_copy_implementations)]
639#[repr(transparent)]
640pub struct SqliteBatchInsertWrapper<V, T, QId, const STATIC_QUERY_ID: bool>(
641    BatchInsert<V, T, QId, STATIC_QUERY_ID>,
642);
643
644impl<V, T, QId, const STATIC_QUERY_ID: bool> crate::query_builder::returning::InsertStmtKind
645    for SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>
646{
647    type StmtKind = crate::query_builder::returning::InsertStmtWithoutOnConflictDoUpdate;
648}
649
650impl<V, Tab, QId, const STATIC_QUERY_ID: bool> QueryFragment<Sqlite>
651    for SqliteBatchInsertWrapper<Vec<ValuesClause<V, Tab>>, Tab, QId, STATIC_QUERY_ID>
652where
653    ValuesClause<V, Tab>: QueryFragment<Sqlite>,
654    V: QueryFragment<Sqlite>,
655{
656    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Sqlite>) -> QueryResult<()> {
657        if !STATIC_QUERY_ID {
658            out.unsafe_to_cache_prepared();
659        }
660
661        let mut values = self.0.values.iter();
662        if let Some(value) = values.next() {
663            value.walk_ast(out.reborrow())?;
664        }
665        for value in values {
666            out.push_sql(", (");
667            value.values.walk_ast(out.reborrow())?;
668            out.push_sql(")");
669        }
670        Ok(())
671    }
672}
673
674#[allow(missing_copy_implementations, missing_debug_implementations)]
675#[repr(transparent)]
676pub struct SqliteCanInsertInSingleQueryHelper<T: ?Sized>(T);
677
678impl<V, T, QId, const STATIC_QUERY_ID: bool> CanInsertInSingleQuery<Sqlite>
679    for SqliteBatchInsertWrapper<Vec<ValuesClause<V, T>>, T, QId, STATIC_QUERY_ID>
680where
681    // We constrain that here on an internal helper type
682    // to make sure that this does not accidentally leak
683    // so that none does really implement normal batch
684    // insert for inserts with default values here
685    SqliteCanInsertInSingleQueryHelper<V>: CanInsertInSingleQuery<Sqlite>,
686{
687    fn rows_to_insert(&self) -> Option<usize> {
688        Some(self.0.values.len())
689    }
690}
691
692impl<T> CanInsertInSingleQuery<Sqlite> for SqliteCanInsertInSingleQueryHelper<T>
693where
694    T: CanInsertInSingleQuery<Sqlite>,
695{
696    fn rows_to_insert(&self) -> Option<usize> {
697        self.0.rows_to_insert()
698    }
699}
700
701impl<V, T, QId, const STATIC_QUERY_ID: bool> QueryId
702    for SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>
703where
704    BatchInsert<V, T, QId, STATIC_QUERY_ID>: QueryId,
705{
706    type QueryId = <BatchInsert<V, T, QId, STATIC_QUERY_ID> as QueryId>::QueryId;
707
708    const HAS_STATIC_QUERY_ID: bool =
709        <BatchInsert<V, T, QId, STATIC_QUERY_ID> as QueryId>::HAS_STATIC_QUERY_ID;
710}
711
712impl<V, T, QId, C, Op, const STATIC_QUERY_ID: bool> ExecuteDsl<C, Sqlite>
713    for (
714        No,
715        InsertStatement<T, BatchInsert<V, T, QId, STATIC_QUERY_ID>, Op>,
716    )
717where
718    C: Connection<Backend = Sqlite>,
719    T: Table + QueryId + 'static,
720    T::FromClause: QueryFragment<Sqlite>,
721    Op: QueryFragment<Sqlite> + QueryId,
722    SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>:
723        QueryFragment<Sqlite> + QueryId + CanInsertInSingleQuery<Sqlite>,
724{
725    fn execute((No, query): Self, conn: &mut C) -> QueryResult<usize> {
726        let query = InsertStatement {
727            records: SqliteBatchInsertWrapper(query.records),
728            operator: query.operator,
729            target: query.target,
730            returning: query.returning,
731            into_clause: query.into_clause,
732        };
733        query.execute(conn)
734    }
735}
736
737impl<V, T, QId, C, Op, Target, ConflictOpt, const STATIC_QUERY_ID: bool> ExecuteDsl<C, Sqlite>
738    for (
739        No,
740        InsertStatement<
741            T,
742            OnConflictValues<BatchInsert<V, T, QId, STATIC_QUERY_ID>, Target, ConflictOpt>,
743            Op,
744        >,
745    )
746where
747    C: Connection<Backend = Sqlite>,
748    T: Table + QueryId + 'static,
749    T::FromClause: QueryFragment<Sqlite>,
750    Op: QueryFragment<Sqlite> + QueryId,
751    OnConflictValues<SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>, Target, ConflictOpt>:
752        QueryFragment<Sqlite> + CanInsertInSingleQuery<Sqlite> + QueryId,
753{
754    fn execute((No, query): Self, conn: &mut C) -> QueryResult<usize> {
755        let query = InsertStatement {
756            operator: query.operator,
757            target: query.target,
758            records: OnConflictValues {
759                values: SqliteBatchInsertWrapper(query.records.values),
760                target: query.records.target,
761                action: query.records.action,
762                where_clause: query.records.where_clause,
763            },
764            returning: query.returning,
765            into_clause: query.into_clause,
766        };
767        query.execute(conn)
768    }
769}
770
771#[diagnostic::do_not_recommend]
772impl<'query, V, T, QId, Op, Ret, U, B, const STATIC_QUERY_ID: bool>
773    LoadQuery<'query, SqliteConnection, U, B>
774    for (
775        No,
776        InsertStatement<T, BatchInsert<V, T, QId, STATIC_QUERY_ID>, Op, Ret>,
777    )
778where
779    T: Table + QueryId + 'static,
780    InsertStatement<T, SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>, Op, Ret>:
781        LoadQuery<'query, SqliteConnection, U, B>,
782    Self: RunQueryDsl<SqliteConnection>,
783{
784    type RowIter<'conn> = <InsertStatement<
785        T,
786        SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>,
787        Op,
788        Ret,
789    > as LoadQuery<'query, SqliteConnection, U, B>>::RowIter<'conn>;
790
791    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
792        let (No, query) = self;
793
794        let query = InsertStatement {
795            records: SqliteBatchInsertWrapper(query.records),
796            operator: query.operator,
797            target: query.target,
798            returning: query.returning,
799            into_clause: query.into_clause,
800        };
801
802        query.internal_load(conn)
803    }
804}
805
806#[diagnostic::do_not_recommend]
807impl<'query, V, T, QId, Op, Ret, U, B, Target, ConflictOpt, const STATIC_QUERY_ID: bool>
808    LoadQuery<'query, SqliteConnection, U, B>
809    for (
810        No,
811        InsertStatement<
812            T,
813            OnConflictValues<BatchInsert<V, T, QId, STATIC_QUERY_ID>, Target, ConflictOpt>,
814            Op,
815            Ret,
816        >,
817    )
818where
819    T: Table + QueryId + 'static,
820    InsertStatement<
821        T,
822        OnConflictValues<SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>, Target, ConflictOpt>,
823        Op,
824        Ret,
825    >: LoadQuery<'query, SqliteConnection, U, B>,
826    Self: RunQueryDsl<SqliteConnection>,
827{
828    type RowIter<'conn> = <InsertStatement<
829        T,
830        OnConflictValues<SqliteBatchInsertWrapper<V, T, QId, STATIC_QUERY_ID>, Target, ConflictOpt>,
831        Op,
832        Ret,
833    > as LoadQuery<'query, SqliteConnection, U, B>>::RowIter<'conn>;
834
835    fn internal_load(self, conn: &mut SqliteConnection) -> QueryResult<Self::RowIter<'_>> {
836        let (No, query) = self;
837
838        let query = InsertStatement {
839            operator: query.operator,
840            target: query.target,
841            records: OnConflictValues {
842                values: SqliteBatchInsertWrapper(query.records.values),
843                target: query.records.target,
844                action: query.records.action,
845                where_clause: query.records.where_clause,
846            },
847            returning: query.returning,
848            into_clause: query.into_clause,
849        };
850
851        query.internal_load(conn)
852    }
853}
854
855macro_rules! tuple_impls {
856        ($(
857            $Tuple:tt {
858                $(($idx:tt) -> $T:ident, $ST:ident, $TT:ident,)+
859            }
860        )+) => {
861            $(
862                impl_contains_defaultable_value!($($T,)*);
863            )*
864        }
865    }
866
867macro_rules! impl_contains_defaultable_value {
868      (
869        @build
870        start_ts = [$($ST: ident,)*],
871        ts = [$T1: ident,],
872        bounds = [$($bounds: tt)*],
873        out = [$($out: tt)*],
874    )=> {
875        impl<$($ST,)*> ContainsDefaultableValue for ($($ST,)*)
876        where
877            $($ST: ContainsDefaultableValue,)*
878            $($bounds)*
879            $T1::Out: Any<$($out)*>,
880        {
881            type Out = <$T1::Out as Any<$($out)*>>::Out;
882        }
883
884    };
885    (
886        @build
887        start_ts = [$($ST: ident,)*],
888        ts = [$T1: ident, $($T: ident,)+],
889        bounds = [$($bounds: tt)*],
890        out = [$($out: tt)*],
891    )=> {
892        impl_contains_defaultable_value! {
893            @build
894            start_ts = [$($ST,)*],
895            ts = [$($T,)*],
896            bounds = [$($bounds)* $T1::Out: Any<$($out)*>,],
897            out = [<$T1::Out as Any<$($out)*>>::Out],
898        }
899    };
900    ($T1: ident, $($T: ident,)+) => {
901        impl_contains_defaultable_value! {
902            @build
903            start_ts = [$T1, $($T,)*],
904            ts = [$($T,)*],
905            bounds = [],
906            out = [$T1::Out],
907        }
908    };
909    ($T1: ident,) => {
910        impl<$T1> ContainsDefaultableValue for ($T1,)
911        where $T1: ContainsDefaultableValue,
912        {
913            type Out = <$T1 as ContainsDefaultableValue>::Out;
914        }
915    }
916}
917
918crate::for_each_tuple!(tuple_impls);