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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/// Implements the [`Queryable`][queryable] trait for a given struct. This macro
/// should be called by copy/pasting the definition of the struct into it.
///
/// [queryable]: query_source/trait.Queryable.html
///
/// # Example
///
/// ```no_run
/// # #[macro_use] extern crate diesel;
/// struct User {
///     name: String,
///     hair_color: Option<String>,
/// }
///
/// Queryable! {
///     struct User {
///         name: String,
///         hair_color: Option<String>,
///     }
/// }
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! Queryable {
    // Strip empty argument list if given (Passed by custom_derive macro)
    (() $($body:tt)*) => {
        Queryable! {
            $($body)*
        }
    };

    // Strip meta items, pub (if present) and struct from definition
    (
        $(#[$ignore:meta])*
        $(pub)* struct $($body:tt)*
    ) => {
        Queryable! {
            $($body)*
        }
    };

    // Receive parsed fields of normal struct from `__diesel_parse_struct_body`
    // These patterns must appear above those which start with an ident to compile
    (
        (
            struct_name = $struct_name:ident,
            $($headers:tt)*
        ),
        fields = [$({
            field_name: $field_name:ident,
            column_name: $column_name:ident,
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        })+],
    ) => {
        Queryable! {
            $($headers)*
            row_ty = ($($field_ty,)+),
            row_pat = ($($field_name,)+),
            build_expr = $struct_name { $($field_name: $field_name),+ },
        }
    };

    // Receive parsed fields of tuple struct from `__diesel_parse_struct_body`
    // where the fields were annotated with `#[column_name]`. We don't need the
    // name, so toss it out.
    (
        $headers:tt,
        fields = [$({
            column_name: $column_name:ident,
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        })+],
    ) => {
        Queryable! {
            $headers,
            fields = [$({
                field_ty: $field_ty,
                field_kind: $field_kind,
            })+],
        }
    };

    // Receive parsed fields of tuple struct from `__diesel_parse_struct_body`
    (
        (
            struct_name = $struct_name:ident,
            $($headers:tt)*
        ),
        fields = [$({
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        })+],
    ) => {
        Queryable! {
            $($headers)*
            row_ty = ($($field_ty,)+),
            row_pat = ($($field_kind,)+),
            build_expr = $struct_name($($field_kind),+),
        }
    };

    // Construct the final impl
    (
        struct_ty = $struct_ty:ty,
        generics = ($($generics:ident),*),
        lifetimes = ($($lifetimes:tt),*),
        row_ty = $row_ty:ty,
        row_pat = $row_pat:pat,
        build_expr = $build_expr:expr,
    ) => {
        impl<$($lifetimes,)* $($generics,)* __DB, __ST> $crate::Queryable<__ST, __DB> for $struct_ty where
            __DB: $crate::backend::Backend + $crate::types::HasSqlType<__ST>,
            $row_ty: $crate::types::FromSqlRow<__ST, __DB>,
        {
            type Row = $row_ty;

            fn build(row: Self::Row) -> Self {
                let $row_pat = row;
                $build_expr
            }
        }
    };

    // Handle struct with generics
    (
        $struct_name:ident <$($generics:ident),*>
        $body:tt $(;)*
    ) => {
        __diesel_parse_struct_body! {
            (
                struct_name = $struct_name,
                struct_ty = $struct_name<$($generics),*>,
                generics = ($($generics),*),
                lifetimes = (),
            ),
            callback = Queryable,
            body = $body,
        }
    };

    // Handle struct with no generics
    (
        $struct_name:ident
        $body:tt $(;)*
    ) => {
        __diesel_parse_struct_body! {
            (
                struct_name = $struct_name,
                struct_ty = $struct_name,
                generics = (),
                lifetimes = (),
            ),
            callback = Queryable,
            body = $body,
        }
    };
}

#[cfg(test)]
mod tests {
    use expression::dsl::sql;
    use prelude::*;
    use test_helpers::connection;
    use types::Integer;

    #[test]
    fn named_struct_definition() {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        struct MyStruct {
            foo: i32,
            bar: i32,
        }

        Queryable! {
            #[derive(Debug, Clone, Copy, PartialEq, Eq)]
            struct MyStruct {
                foo: i32,
                bar: i32,
            }
        }

        let conn = connection();
        let data = ::select(sql::<(Integer, Integer)>("1, 2")).get_result(&conn);
        assert_eq!(Ok(MyStruct { foo: 1, bar: 2 }), data);
    }

    #[test]
    fn tuple_struct() {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        struct MyStruct(i32, i32);

        Queryable! {
            #[derive(Debug, Clone, Copy, PartialEq, Eq)]
            struct MyStruct(#[column_name(foo)] i32, #[column_name(bar)] i32);
        }

        let conn = connection();
        let data = ::select(sql::<(Integer, Integer)>("1, 2")).get_result(&conn);
        assert_eq!(Ok(MyStruct(1, 2)), data);
    }

    #[test]
    fn tuple_struct_without_column_name_annotations() {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        struct MyStruct(i32, i32);

        Queryable! {
            #[derive(Debug, Clone, Copy, PartialEq, Eq)]
            struct MyStruct(i32, i32);
        }

        let conn = connection();
        let data = ::select(sql::<(Integer, Integer)>("1, 2")).get_result(&conn);
        assert_eq!(Ok(MyStruct(1, 2)), data);
    }
}