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
use std::collections::HashMap;

use aws_sdk_dynamodb::model::{update, AttributeValue, TransactWriteItem};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;

use crate::client::{PK, SK};
use crate::condition_check::{condition_check_exists, ConditionCheckInfo};
use crate::{Client, DynarustError, Resource};

impl Client {
    /// Updates a resource. It returns an error if the resource does not exist.
    ///
    /// # arguments
    ///
    /// * `resource` - the resource that will get updated.
    /// * `request` - serde Object with the info for updating the request. If the requests tries
    ///   to update the resource in a way that deserializing it will no longer be compatible with
    ///   type T, it fails at runtime.
    ///
    /// # examples
    ///
    /// ```
    /// use serde_json::json;
    /// async {
    ///    let updated = client
    ///       .update(
    ///           &person,
    ///           json!({ "name": "John", "age":  28 }),
    ///       )
    ///       .await?;
    /// }
    /// ```
    pub async fn update<T: Resource + Serialize + DeserializeOwned>(
        &self,
        resource: &T,
        request: Value,
    ) -> Result<T, DynarustError> {
        self.update_with_checks(resource, request, vec![]).await
    }

    /// Updates a resource with additional condition checks. It returns an error if the resource does not exist.
    ///
    /// # arguments
    ///
    /// * `resource` - the resource that will get updated.
    /// * `request` - serde Object with the info for updating the request. If the requests tries
    ///   to update the resource in a way that deserializing it will no longer be compatible with
    ///   type T, it fails at runtime.
    /// * `condition_checks` - The condition checks that will be added to the transaction item.
    ///
    /// # examples
    ///
    /// ```
    /// use serde_json::json;
    /// async {
    ///    let updated = client
    ///       .update(
    ///           &person,
    ///           json!({ "name": "John", "age":  28 }),
    ///           vec![dynarust::condition_check_number("age", dynarust::DynamoOperator::Gt, 21)],
    ///       )
    ///       .await?;
    /// }
    /// ```
    pub async fn update_with_checks<T: Resource + Serialize + DeserializeOwned>(
        &self,
        resource: &T,
        request: Value,
        condition_checks: Vec<ConditionCheckInfo>,
    ) -> Result<T, DynarustError> {
        let mut object = Self::resource_as_object(resource)?;

        let request: HashMap<String, Value> = serde_json::from_value(request)?;

        for (k, new_v) in request.iter() {
            object[k] = new_v.clone()
        }
        let updated: T = serde_json::from_value(Value::Object(object))?;

        if request.is_empty() {
            return Ok(updated);
        }

        if updated.pk_sk() != resource.pk_sk() {
            return Err(DynarustError::InvalidRequestError(
                "Cannot update PK and/or SK".into(),
            ));
        }

        let condition_check = condition_check_exists().merge(condition_checks);

        let (pk, sk) = resource.pk_sk();
        let mut builder = self
            .client
            .update_item()
            .table_name(T::table())
            .key(PK, AttributeValue::S(pk))
            .key(SK, AttributeValue::S(sk));

        let mut update_expression = "set ".to_string();
        let request_len = request.len();
        for (i, (k, v)) in request.into_iter().enumerate() {
            let name = format!("#updateAttr{}", i);
            let value = format!(":updateAttr{}", i);
            update_expression += &format!("{} = {}", name, value);
            if i < request_len - 1 {
                update_expression += ", "
            }
            builder = builder.expression_attribute_names(name, k);
            builder = builder.expression_attribute_values(value, Self::value2attr(&v)?);
        }

        builder = condition_check.dump_in_update_item(builder);

        builder.update_expression(update_expression).send().await?;

        Ok(updated)
    }
}

/// Adds an update operation to the transaction context.
///
/// # arguments
///
/// * `resource` - the resource that will get updated.
/// * `request` - serde Object with the info for updating the request. If the requests tries
///   to update the resource in a way that deserializing it will no longer be compatible with
///   type T, it fails at runtime.
/// * `transaction_context` - The transaction context to which the create operation will be added.
///
/// # examples
///
/// ```
/// use serde_json::json;
/// async {
///     let mut context = dynarust::begin_transaction();
///     client.transact_update(
///         &person,
///         json!({ "name": "John", "age":  28 }),
///         &mut context
///     )?;
///     client.execute_transaction(context).await?;
/// }
/// ```
pub fn transact_update<T: Resource + Serialize + DeserializeOwned>(
    resource: &T,
    request: Value,
    transaction_context: &mut Vec<TransactWriteItem>,
) -> Result<T, DynarustError> {
    transact_update_with_checks(resource, request, vec![], transaction_context)
}

/// Adds an update operation to the transaction context, with additional condition checks
///
/// # arguments
///
/// * `resource` - the resource that will get updated.
/// * `request` - serde Object with the info for updating the request. If the requests tries
///   to update the resource in a way that deserializing it will no longer be compatible with
///   type T, it fails at runtime.
/// * `condition_checks` - The condition checks that will be added to the transaction item.
/// * `transaction_context` - The transaction context to which the create operation will be added.
///
/// # examples
///
/// ```
/// use serde_json::json;
/// async {
///     let mut context = dynarust::begin_transaction();
///     client.transact_update(
///         &person,
///         json!({ "name": "John", "age":  28 }),
///         vec![dynarust::condition_check_number("age", dynarust::DynamoOperator::Gt, 21)],
///         &mut context
///     )?;
///     client.execute_transaction(context).await?;
/// }
/// ```
pub fn transact_update_with_checks<T: Resource + Serialize + DeserializeOwned>(
    resource: &T,
    request: Value,
    condition_checks: Vec<ConditionCheckInfo>,
    transaction_context: &mut Vec<TransactWriteItem>,
) -> Result<T, DynarustError> {
    let mut object = Client::resource_as_object(resource)?;

    let request: HashMap<String, Value> = serde_json::from_value(request)?;

    for (k, new_v) in request.iter() {
        object[k] = new_v.clone()
    }
    let updated: T = serde_json::from_value(Value::Object(object))?;

    if request.is_empty() {
        return Ok(updated);
    }

    if updated.pk_sk() != resource.pk_sk() {
        return Err(DynarustError::InvalidRequestError(
            "Cannot update PK and/or SK".into(),
        ));
    }

    let condition_check = condition_check_exists().merge(condition_checks);

    let (pk, sk) = resource.pk_sk();
    let mut builder = update::Builder::default()
        .table_name(T::table())
        .key(PK, AttributeValue::S(pk))
        .key(SK, AttributeValue::S(sk));

    let mut update_expression = "set ".to_string();
    let request_len = request.len();
    for (i, (k, v)) in request.into_iter().enumerate() {
        let name = format!("#updateAttr{}", i);
        let value = format!(":updateAttr{}", i);
        update_expression += &format!("{} = {}", name, value);
        if i < request_len - 1 {
            update_expression += ", "
        }
        builder = builder.expression_attribute_names(name, k);
        builder = builder.expression_attribute_values(value, Client::value2attr(&v)?);
    }

    builder = condition_check.dump_in_update(builder);

    let update = builder.update_expression(update_expression).build();
    transaction_context.push(TransactWriteItem::builder().update(update).build());

    Ok(updated)
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use crate::client::tests::TestResource;
    use crate::condition_check::condition_check_number;
    use crate::create::transact_create;
    use crate::update::transact_update;
    use crate::{begin_transaction, Client, DynamoOperator, Resource};

    #[tokio::test]
    async fn creates_updates_gets_resource() {
        let client = Client::local().await;
        client.create_table::<TestResource>(None).await.unwrap();
        let resource = TestResource {
            pk: "creates_updates_gets_resource".to_string(),
            sk: "1".to_string(),
            string: "asda".to_string(),
            ..Default::default()
        };
        client.create(&resource).await.unwrap();

        let updated = client
            .update(
                &resource,
                json!({
                    "string": "updated",
                    "string_arr": vec!["foo".to_string()]
                }),
            )
            .await
            .unwrap();

        let retrieved = client.get::<TestResource>(resource.pk_sk()).await.unwrap();
        assert_eq!(retrieved, Some(updated))
    }

    #[tokio::test]
    async fn updates_null_field() {
        let client = Client::local().await;
        client.create_table::<TestResource>(None).await.unwrap();
        let resource = TestResource {
            pk: "updates_null_field".to_string(),
            sk: "1".to_string(),
            ..Default::default()
        };
        client.create(&resource).await.unwrap();

        let updated = client
            .update(
                &resource,
                json!({
                    "nullable": "updated"
                }),
            )
            .await
            .unwrap();

        let retrieved = client.get::<TestResource>(resource.pk_sk()).await.unwrap();
        assert_eq!(retrieved, Some(updated))
    }

    #[tokio::test]
    async fn creates_updates_conditional_check_fails() {
        let client = Client::local().await;
        client.create_table::<TestResource>(None).await.unwrap();
        let resource = TestResource {
            pk: "creates_updates_conditional_check_fails".to_string(),
            sk: "1".to_string(),
            string: "asda".to_string(),
            int: 0,
            ..Default::default()
        };
        client.create(&resource).await.unwrap();

        client
            .update_with_checks(
                &resource,
                json!({
                    "int": 1
                }),
                vec![condition_check_number("int", DynamoOperator::NEq, 1)],
            )
            .await
            .unwrap();

        let err = client
            .update_with_checks(
                &resource,
                json!({
                    "int": 2
                }),
                vec![condition_check_number("int", DynamoOperator::NEq, 1)],
            )
            .await
            .unwrap_err();

        assert_eq!(err.to_string(), "The conditional request failed")
    }

    #[tokio::test]
    async fn creates_and_updates_resources_transactionally() {
        let client = Client::local().await;
        client.create_table::<TestResource>(None).await.unwrap();

        let resource_1 = TestResource {
            pk: "creates_and_updates_resources_transactionally".to_string(),
            sk: "1".to_string(),
            ..Default::default()
        };

        client.create(&resource_1).await.unwrap();

        let resource_2 = TestResource {
            pk: "creates_and_updates_resources_transactionally".to_string(),
            sk: "2".to_string(),
            ..Default::default()
        };

        let mut context = begin_transaction();
        let updated_resource_1 = transact_update(
            &resource_1,
            json!({
                "string": "updated"
            }),
            &mut context,
        )
        .unwrap();
        transact_create(&resource_2, &mut context).unwrap();
        client.execute_transaction(context).await.unwrap();

        let retrieved_1 = client
            .get::<TestResource>(updated_resource_1.pk_sk())
            .await
            .unwrap();
        assert_eq!(retrieved_1, Some(updated_resource_1));

        let retrieved_2 = client
            .get::<TestResource>(resource_2.pk_sk())
            .await
            .unwrap();
        assert_eq!(retrieved_2, Some(resource_2))
    }
}