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
use std::marker::PhantomData;

use backend::{Backend, SupportsDefaultKeyword};
use expression::Expression;
use query_builder::{QueryBuilder, BuildQueryResult};
use query_source::{Table, Column};

/// Represents that a structure can be used to to insert a new row into the database.
/// Implementations can be automatically generated by
/// [`#[insertable_into]`](https://github.com/sgrif/diesel/tree/master/diesel_codegen#insertable_intotable_name).
/// This is automatically implemented for `&[T]` and `&Vec<T>` for inserting more than
/// one record.
pub trait Insertable<T: Table, DB: Backend> {
    type Values: InsertValues<DB>;

    fn values(self) -> Self::Values;
}

pub trait InsertValues<DB: Backend> {
    fn column_names(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult;
    fn values_clause(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult;
}

pub enum ColumnInsertValue<Col, Expr> where
    Col: Column,
    Expr: Expression<SqlType=Col::SqlType>,
{
    Expression(Col, Expr),
    Default(Col),
}

impl<'a, T, U: 'a, DB> Insertable<T, DB> for &'a [U] where
    T: Table,
    DB: Backend,
    &'a U: Insertable<T, DB>,
    DB: SupportsDefaultKeyword,
{
    type Values = BatchInsertValues<'a, T, U, DB>;

    fn values(self) -> Self::Values {
        BatchInsertValues {
            values: self,
            _marker: PhantomData,
        }
    }
}

impl<'a, T, U, DB> Insertable<T, DB> for &'a Vec<U> where
    T: Table,
    DB: Backend,
    &'a [U]: Insertable<T, DB>,
{
    type Values = <&'a [U] as Insertable<T, DB>>::Values;

    fn values(self) -> Self::Values {
        (self as &'a [U]).values()
    }
}


pub struct BatchInsertValues<'a, T, U: 'a, DB> {
    values: &'a [U],
    _marker: PhantomData<(T, DB)>,
}

impl<'a, T, U: 'a, DB> InsertValues<DB> for BatchInsertValues<'a, T, U, DB> where
    T: Table,
    DB: Backend,
    &'a U: Insertable<T, DB>,
{
    fn column_names(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {
        self.values[0].values().column_names(out)
    }

    fn values_clause(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {
        for (i, record) in self.values.into_iter().enumerate() {
            if i != 0 {
                out.push_sql(", ");
            }
            try!(record.values().values_clause(out));
        }
        Ok(())
    }
}