dynamodel 0.6.0

This library provides a derive macro to implement conversions between your object and `HashMap<String, AttributeValue>`.
Documentation
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! # dynamodel
//!
//! This library provides a derive macro to implement conversions between your object and
//! [HashMap](std::collections::HashMap)<[String], [AttributeValue]>.
//!
//! ## Derive macro [`Dynamodel`]
//!
//! The [`Dynamodel`] derive macro implements these three traits to use
//! [`aws-sdk-dynamodb`](https://crates.io/crates/aws-sdk-dynamodb) more comfortably.
//!
//! * `Into<HashMap<String, AttributeValue>>`
//! * `TryFrom<HashMap<String, AttributeValue>>`
//! * The [`AttributeValueConvertible`] trait enables the types that implement it to be converted from and to `AttributeValue`.
//!
//! ```ignore
//! #[derive(Dynamodel)]        Convertible
//! struct YourStruct { ... }  <===========>  HashMap<String, AttributeValue>
//!
//! #[derive(Dynamodel)]    Convertible
//! enum YourEnum { ... }  <===========>  HashMap<String, AttributeValue>
//! ```
//!
//! ### Requirements to use [`Dynamodel`]
//!
//! To use the [`Dynamodel`] macro, all types of your object's fields must implement
//! the `AttributeValueConvertible` trait.
//!
//! By default, these types automatically implement the [`AttributeValueConvertible`]
//! trait, so no additional code is required when using these types.
//!
//! | Type | `AttributeValue` variant |
//! |---|---|
//! | `String` | `AttributeValue::S("...")` |
//! | `u8, u16, u32, u64, u128, usize`<br>`i8, i16, i32, i64, i128, isize`<br>`f32, f64` | `AttributeValue::N("...")` |
//! | `bool` | `AttributeValue::Bool(...)` |
//! | `Vec` of any types that implement `AttributeValueConvertible` | `AttributeValue::L([...])` |
//! | Any types that implement `Dynamodel` macro | `AttributeValue::M({ ... })` |
//!
//! The last row of the above table shows that once you apply the [`Dynamodel`] macro to your object,
//! it also implements the [`AttributeValueConvertible`] trait for your object.
//!
//! **So, you can create nested structures of objects that apply the [`Dynamodel`] macro.**
//!
//! If you want to use additional types, you need to implement the `AttributeValueConvertible`
//! trait for your type.
//!
//! ## Usage
//!
//! ```rust
//! use dynamodel::Dynamodel;
//! # use std::collections::HashMap;
//! # use aws_sdk_dynamodb::types::AttributeValue;
//!
//! #[derive(Dynamodel, Debug, Clone, PartialEq)]
//! struct Person {
//!     first_name: String,
//!     last_name: String,
//!     age: u8,
//! }
//!
//! let person = Person {
//!     first_name: "Kanji".into(),
//!     last_name: "Tanaka".into(),
//!     age: 23,
//! };
//!
//! let item: HashMap<String, AttributeValue> = [
//!     ("first_name".to_string(), AttributeValue::S("Kanji".into())),
//!     ("last_name".to_string(), AttributeValue::S("Tanaka".into())),
//!     ("age".to_string(), AttributeValue::N("23".into()))
//! ].into();
//!
//! // Convert from Person into HashMap<String, AttributeValue>.
//! let converted: HashMap<String, AttributeValue> = person.clone().into();
//! assert_eq!(converted, item);
//!
//! // Convert from HashMap<String, AttributeValue> into Person.
//! // This conversion uses std::convert::TryFrom trait, so this returns a Result.
//! let converted: Person = item.try_into().unwrap();
//! assert_eq!(converted, person);
//! ```
//!
//! ### Modifying the default behavior
//!
//! Like the [`Serde`](https://crates.io/crates/serde) crate, you can modify the default behavior
//! through attributes like this.
//!
//! ```rust
//! use dynamodel::{Dynamodel, ConvertError};
//! # use std::collections::HashMap;
//! # use aws_sdk_dynamodb::{types::AttributeValue, primitives::Blob};
//!
//! // Vec<u8> is converted to AttributeValue::L by default,
//! // but this case, the `data` field is converted to AttributeValue::B.
//! #[derive(Dynamodel)]
//! struct BinaryData {
//!     #[dynamodel(into = "to_blob", try_from = "from_blob")]
//!     data: Vec<u8>
//! }
//!
//! fn to_blob(value: Vec<u8>) -> AttributeValue {
//!     AttributeValue::B(Blob::new(value))
//! }
//!
//! fn from_blob(value: &AttributeValue) -> Result<Vec<u8>, ConvertError> {
//!     value.as_b()
//!         .map(|b| b.clone().into_inner())
//!         .map_err(|err| ConvertError::AttributeValueUnmatched("B".to_string(), err.clone()))
//! }
//! ```
//!
//! The function definition must meet these conditions.
//!
//! | Field attribute | Argument | Return |
//! |---|---|---|
//! | `#[dynamodel(into = "...")]`| `field type` | `AttributeValue` |
//! | `#[dynamodel(try_from = "...")]` | `&AttributeValue` | `Result<field type, ConvertError>` |
//!
//! ## Example
//!
//! ### Single-table design
//!
//! The following diagram shows that both `Video` and `VideoStats` are stored in the same table.
//!
//! ![videos table](https://github.com/kaicoh/dynamodel/blob/images/videos_table.png?raw=true)
//!
//! ```rust
//! use dynamodel::{Dynamodel, ConvertError};
//! # use std::collections::HashMap;
//! # use aws_sdk_dynamodb::{types::AttributeValue, primitives::Blob};
//!
//! #[derive(Dynamodel, Debug, Clone, PartialEq)]
//! #[dynamodel(extra = "VideoStats::sort_key", rename_all = "PascalCase")]
//! struct VideoStats {
//!     #[dynamodel(rename = "PK")]
//!     id: String,
//!     view_count: u64,
//! }
//!
//! impl VideoStats {
//!     fn sort_key(&self) -> HashMap<String, AttributeValue> {
//!         [
//!             ("SK".to_string(), AttributeValue::S("VideoStats".into())),
//!         ].into()
//!     }
//! }
//!
//! let stats = VideoStats {
//!     id: "7cf27a02".into(),
//!     view_count: 147,
//! };
//!
//! let item: HashMap<String, AttributeValue> = [
//!     ("PK".to_string(), AttributeValue::S("7cf27a02".into())),
//!     ("SK".to_string(), AttributeValue::S("VideoStats".into())),
//!     ("ViewCount".to_string(), AttributeValue::N("147".into())),
//! ].into();
//!
//! let converted: HashMap<String, AttributeValue> = stats.clone().into();
//! assert_eq!(converted, item);
//!
//! let converted: VideoStats = item.try_into().unwrap();
//! assert_eq!(converted, stats);
//! ```
//!
//! And suppose you want to add a `VideoComment` object that is sortable by timestamp,
//! like this.
//!
//! ![video comments object](https://github.com/kaicoh/dynamodel/blob/images/videos_table_2.png?raw=true)
//!
//! ```rust
//! use dynamodel::{Dynamodel, ConvertError};
//! # use std::collections::HashMap;
//! # use aws_sdk_dynamodb::{types::AttributeValue, primitives::Blob};
//!
//! #[derive(Dynamodel, Debug, Clone, PartialEq)]
//! #[dynamodel(rename_all = "PascalCase")]
//! struct VideoComment {
//!     #[dynamodel(rename = "PK")]
//!     id: String,
//!     #[dynamodel(rename = "SK", into = "sort_key", try_from = "get_timestamp")]
//!     timestamp: String,
//!     content: String,
//! }
//!
//! fn sort_key(timestamp: String) -> AttributeValue {
//!     AttributeValue::S(format!("VideoComment#{timestamp}"))
//! }
//!
//! fn get_timestamp(value: &AttributeValue) -> Result<String, ConvertError> {
//!     value.as_s()
//!         .map(|v| v.split('#').last().unwrap().to_string())
//!         .map_err(|e| ConvertError::AttributeValueUnmatched("S".into(), e.clone()))
//! }
//!
//! let comment = VideoComment {
//!     id: "7cf27a02".into(),
//!     content: "Good video!".into(),
//!     timestamp: "2023-04-05T12:34:56".into(),
//! };
//!
//! let item: HashMap<String, AttributeValue> = [
//!     ("PK".to_string(), AttributeValue::S("7cf27a02".into())),
//!     ("SK".to_string(), AttributeValue::S("VideoComment#2023-04-05T12:34:56".into())),
//!     ("Content".to_string(), AttributeValue::S("Good video!".into())),
//! ].into();
//!
//! let converted: HashMap<String, AttributeValue> = comment.clone().into();
//! assert_eq!(converted, item);
//!
//! let converted: VideoComment = item.try_into().unwrap();
//! assert_eq!(converted, comment);
//! ```
//!
//! ## More features
//!
//! For more features, refer to [this wiki](https://github.com/kaicoh/dynamodel/wiki).

/// Derive macro to implement both `Into<HashMap<String, AttributeValue>>` and `TryFrom<HashMap<String, AttributeValue>>` traits.
///
/// For details, refer to [the wiki](https://github.com/kaicoh/dynamodel/wiki).
pub use dynamodel_derive::Dynamodel;

use aws_sdk_dynamodb::types::AttributeValue;
use std::num::{ParseFloatError, ParseIntError};
use thiserror::Error;

/// An error occurs when converting from a `HashMap<String, AttributeValue>` to your object.
#[derive(Debug, Error)]
pub enum ConvertError {
    /// There is no key-value pair for this field in the HashMap.
    #[error("`{0}` field is not set")]
    FieldNotSet(String),

    /// There is a key-value pair for the field, but the type of AttributeValue is not what is expected.
    #[error("expect `{0}` type, but got `{1:?}`")]
    AttributeValueUnmatched(String, AttributeValue),

    /// The value in the HashMap should be an integer, but it isn't.
    #[error("{0}")]
    ParseInt(#[from] ParseIntError),

    /// The value in the HashMap should be a float, but it isn't.
    #[error("{0}")]
    ParseFloat(#[from] ParseFloatError),

    /// There are no vairants for the enum in the HashMap.
    #[error("not found any variant in hashmap")]
    VariantNotFound,

    /// Any other errors when converting from a HashMap to your object.
    /// You can wrap your original errors in this variant.
    #[error(transparent)]
    Other(Box<dyn std::error::Error + Send + Sync>),
}

fn unmatch_err(expected: &str) -> impl Fn(&AttributeValue) -> ConvertError + '_ {
    |value: &AttributeValue| {
        ConvertError::AttributeValueUnmatched(expected.to_string(), value.to_owned())
    }
}

/// Types that implement this trait on objects with the [`Dynamodel`] macro can be
/// implicitly converted from and into [`AttributeValue`].
pub trait AttributeValueConvertible: Sized {
    fn into_attribute_value(self) -> AttributeValue;
    fn try_from_attribute_value(value: &AttributeValue) -> Result<Self, ConvertError>;
}

impl AttributeValueConvertible for String {
    fn into_attribute_value(self) -> AttributeValue {
        AttributeValue::S(self)
    }
    fn try_from_attribute_value(value: &AttributeValue) -> Result<Self, ConvertError> {
        value
            .as_s()
            .map(|v| v.to_string())
            .map_err(unmatch_err("S"))
    }
}

impl AttributeValueConvertible for bool {
    fn into_attribute_value(self) -> AttributeValue {
        AttributeValue::Bool(self)
    }
    fn try_from_attribute_value(value: &AttributeValue) -> Result<Self, ConvertError> {
        value.as_bool().copied().map_err(unmatch_err("Bool"))
    }
}

macro_rules! impl_to_nums {
    ($($ty:ty),*) => {
        $(
            impl AttributeValueConvertible for $ty {
                fn into_attribute_value(self) -> AttributeValue {
                    AttributeValue::N(self.to_string())
                }
                fn try_from_attribute_value(value: &AttributeValue) -> Result<Self, ConvertError> {
                    value.as_n()
                        .map_err(unmatch_err("N"))
                        .and_then(|v| v.parse::<$ty>().map_err(|e| e.into()))
                }
            }
         )*
    }
}

impl_to_nums! {
    u8, u16, u32, u64, u128, usize,
    i8, i16, i32, i64, i128, isize,
    f32, f64
}

impl<T: AttributeValueConvertible> AttributeValueConvertible for Vec<T> {
    fn into_attribute_value(self) -> AttributeValue {
        AttributeValue::L(
            self.into_iter()
                .map(AttributeValueConvertible::into_attribute_value)
                .collect(),
        )
    }
    fn try_from_attribute_value(value: &AttributeValue) -> Result<Self, ConvertError> {
        let mut values: Vec<T> = vec![];
        for v in value.as_l().map_err(unmatch_err("L"))?.iter() {
            let v: T = AttributeValueConvertible::try_from_attribute_value(v)?;
            values.push(v);
        }
        Ok(values)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn string_can_be_converted_into_attribute_value() {
        let value = "Hello".to_string();
        assert_eq!(
            value.into_attribute_value(),
            AttributeValue::S("Hello".into())
        );
    }

    #[test]
    fn string_can_be_converted_from_attribute_value() {
        let value = AttributeValue::S("Hello".into());
        let result: Result<String, ConvertError> =
            AttributeValueConvertible::try_from_attribute_value(&value);
        assert_eq!(result.unwrap(), "Hello".to_string());
    }

    #[test]
    fn boolean_can_be_converted_into_attribute_value() {
        let value = true;
        assert_eq!(value.into_attribute_value(), AttributeValue::Bool(true));
    }

    #[test]
    fn boolean_can_be_converted_from_attribute_value() {
        let value = AttributeValue::Bool(false);
        let result: Result<bool, ConvertError> =
            AttributeValueConvertible::try_from_attribute_value(&value);
        assert!(!result.unwrap());
    }

    #[test]
    fn string_vector_can_be_converted_into_attribute_value() {
        let value = vec!["Hello".to_string(), "World".to_string()];
        assert_eq!(
            value.into_attribute_value(),
            AttributeValue::L(vec![
                AttributeValue::S("Hello".into()),
                AttributeValue::S("World".into())
            ]),
        );
    }

    #[test]
    fn string_vector_can_be_converted_from_attribute_value() {
        let expected = vec!["Hello".to_string(), "World".to_string()];
        let value = AttributeValue::L(vec![
            AttributeValue::S("Hello".into()),
            AttributeValue::S("World".into()),
        ]);
        let result: Result<Vec<String>, ConvertError> =
            AttributeValueConvertible::try_from_attribute_value(&value);
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn boolean_vector_can_be_converted_into_attribute_value() {
        let value = vec![true, false];
        assert_eq!(
            value.into_attribute_value(),
            AttributeValue::L(vec![
                AttributeValue::Bool(true),
                AttributeValue::Bool(false)
            ]),
        );
    }

    #[test]
    fn boolean_vector_can_be_converted_from_attribute_value() {
        let expected = vec![true, false];
        let value = AttributeValue::L(vec![
            AttributeValue::Bool(true),
            AttributeValue::Bool(false),
        ]);
        let result: Result<Vec<bool>, ConvertError> =
            AttributeValueConvertible::try_from_attribute_value(&value);
        assert_eq!(result.unwrap(), expected);
    }

    macro_rules! test_int {
        ($($ty:ty),*) => {
            $(
                paste::item! {
                    #[test]
                    fn [<$ty _can_be_converted_into_attribute_value>]() {
                        let value: $ty = 10;
                        assert_eq!(value.into_attribute_value(), AttributeValue::N("10".into()));
                    }

                    #[test]
                    fn [<$ty _can_be_converted_from_attribute_value>]() {
                        let expected: $ty = 10;
                        let value = AttributeValue::N("10".into());
                        let result: Result<$ty, ConvertError> = AttributeValueConvertible::try_from_attribute_value(&value);
                        assert_eq!(result.unwrap(), expected);
                    }

                    #[test]
                    fn [<$ty _vector_can_be_converted_into_attribute_value>]() {
                        let value: Vec<$ty> = vec![10, 20];
                        assert_eq!(
                            value.into_attribute_value(),
                            AttributeValue::L(vec![AttributeValue::N("10".into()), AttributeValue::N("20".into())]),
                        );
                    }

                    #[test]
                    fn [<$ty _vector_can_be_converted_from_attribute_value>]() {
                        let expected: Vec<$ty> = vec![10, 20];
                        let value = AttributeValue::L(vec![AttributeValue::N("10".into()), AttributeValue::N("20".into())]);
                        let result: Result<Vec<$ty>, ConvertError> = AttributeValueConvertible::try_from_attribute_value(&value);
                        assert_eq!(result.unwrap(), expected);
                    }
                }
            )*
        }
    }

    test_int! { u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize }

    macro_rules! test_float {
        ($($ty:ty),*) => {
            $(
                paste::item! {
                    #[test]
                    fn [<$ty _can_be_converted_into_attribute_value>]() {
                        let value: $ty = 1.2;
                        assert_eq!(value.into_attribute_value(), AttributeValue::N("1.2".into()));
                    }

                    #[test]
                    fn [<$ty _can_be_converted_from_attribute_value>]() {
                        let expected: $ty = 1.2;
                        let value = AttributeValue::N("1.2".into());
                        let result: Result<$ty, ConvertError> = AttributeValueConvertible::try_from_attribute_value(&value);
                        assert_eq!(result.unwrap(), expected);
                    }

                    #[test]
                    fn [<$ty _vector_can_be_converted_into_attribute_value>]() {
                        let value: Vec<$ty> = vec![1.2, 3.45];
                        assert_eq!(
                            value.into_attribute_value(),
                            AttributeValue::L(vec![AttributeValue::N("1.2".into()), AttributeValue::N("3.45".into())]),
                        );
                    }

                    #[test]
                    fn [<$ty _vector_can_be_converted_from_attribute_value>]() {
                        let expected: Vec<$ty> = vec![1.2, 3.45];
                        let value = AttributeValue::L(vec![AttributeValue::N("1.2".into()), AttributeValue::N("3.45".into())]);
                        let result: Result<Vec<$ty>, ConvertError> = AttributeValueConvertible::try_from_attribute_value(&value);
                        assert_eq!(result.unwrap(), expected);
                    }
                }
            )*
        }
    }

    test_float! { f32, f64 }
}