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
use aws_sdk_dynamodb::{
operation::delete_item::DeleteItemOutput,
operation::put_item::PutItemOutput,
types::AttributeValue,
};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::HashMap;
use crate::error::{Error, Result};
use super::DynamoDbStore;
impl DynamoDbStore {
/// Inserts or updates an item in a DynamoDB table.
///
/// # Arguments
///
/// * `table_name` - The name of the DynamoDB table where the item will be inserted or updated
/// * `item` - A HashMap containing the attribute names and values for the item
///
/// # Returns
///
/// Returns `Ok(PutItemOutput)` on success, containing the response from DynamoDB.
///
/// # Errors
///
/// Returns an error if:
/// - The table name is empty
/// - The item map is empty
/// - AWS credentials are not properly configured
/// - The specified table does not exist
/// - The item exceeds DynamoDB's size limits (400 KB)
/// - Network connectivity issues occur
/// - IAM permissions are insufficient
///
/// # Example
///
/// ```rust,no_run
/// use clean_dynamodb_store::DynamoDbStore;
/// use aws_sdk_dynamodb::types::AttributeValue;
/// use std::collections::HashMap;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let store = DynamoDbStore::new().await?;
///
/// let mut item = HashMap::new();
/// item.insert("id".to_string(), AttributeValue::S("user123".to_string()));
/// item.insert("name".to_string(), AttributeValue::S("John Doe".to_string()));
/// item.insert("age".to_string(), AttributeValue::N("30".to_string()));
///
/// store.put_item("users", item).await?;
/// Ok(())
/// }
/// ```
pub async fn put_item(
&self,
table_name: &str,
item: HashMap<String, AttributeValue>,
) -> Result<PutItemOutput> {
Self::validate_table_name(table_name)?;
Self::validate_not_empty(&item, "Item")?;
let result = self
.client
.put_item()
.table_name(table_name)
.set_item(Some(item))
.send()
.await
.map_err(|e| Error::AwsSdk(Box::new(e.into())))?;
Ok(result)
}
/// Deletes an item from a DynamoDB table.
///
/// # Arguments
///
/// * `table_name` - The name of the DynamoDB table from which the item will be deleted
/// * `key` - A HashMap containing the primary key attributes that identify the item to delete.
/// Must include the partition key and sort key (if the table has one)
///
/// # Returns
///
/// Returns `Ok(DeleteItemOutput)` on success, containing the response from DynamoDB.
/// The operation succeeds even if the item doesn't exist in the table.
///
/// # Errors
///
/// Returns an error if:
/// - The table name is empty
/// - The key map is empty
/// - AWS credentials are not properly configured
/// - The specified table does not exist
/// - The key does not match the table's key schema
/// - Network connectivity issues occur
/// - IAM permissions are insufficient
///
/// # Example
///
/// ```rust,no_run
/// use clean_dynamodb_store::DynamoDbStore;
/// use aws_sdk_dynamodb::types::AttributeValue;
/// use std::collections::HashMap;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let store = DynamoDbStore::new().await?;
///
/// // For a table with partition key "id"
/// let mut key = HashMap::new();
/// key.insert("id".to_string(), AttributeValue::S("user123".to_string()));
///
/// store.delete_item("users", key).await?;
/// Ok(())
/// }
/// ```
///
/// # Example with Sort Key
///
/// ```rust,no_run
/// use clean_dynamodb_store::DynamoDbStore;
/// use aws_sdk_dynamodb::types::AttributeValue;
/// use std::collections::HashMap;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let store = DynamoDbStore::new().await?;
///
/// // For a table with partition key "user_id" and sort key "timestamp"
/// let mut key = HashMap::new();
/// key.insert("user_id".to_string(), AttributeValue::S("user123".to_string()));
/// key.insert("timestamp".to_string(), AttributeValue::N("1640000000".to_string()));
///
/// store.delete_item("events", key).await?;
/// Ok(())
/// }
/// ```
pub async fn delete_item(
&self,
table_name: &str,
key: HashMap<String, AttributeValue>,
) -> Result<DeleteItemOutput> {
Self::validate_table_name(table_name)?;
Self::validate_not_empty(&key, "Key")?;
let result = self
.client
.delete_item()
.table_name(table_name)
.set_key(Some(key))
.send()
.await
.map_err(|e| Error::AwsSdk(Box::new(e.into())))?;
Ok(result)
}
/// Inserts or updates an item using a type-safe struct.
///
/// This is a higher-level alternative to [`put_item`](Self::put_item) that works with
/// any type implementing [`Serialize`]. The struct is automatically converted to
/// DynamoDB's AttributeValue format using `serde_dynamo`.
///
/// # Type Parameters
///
/// * `T` - Any type that implements [`Serialize`]
///
/// # Arguments
///
/// * `table_name` - The name of the DynamoDB table
/// * `item` - A reference to the item to insert or update
///
/// # Returns
///
/// Returns `Ok(PutItemOutput)` on success, containing the response from DynamoDB.
///
/// # Errors
///
/// Returns an error if:
/// - The table name is empty
/// - Serialization fails (invalid struct for DynamoDB)
/// - AWS credentials are not properly configured
/// - The specified table does not exist
/// - The item exceeds DynamoDB's size limits (400 KB)
/// - Network connectivity issues occur
/// - IAM permissions are insufficient
///
/// # Example
///
/// ```rust,no_run
/// use clean_dynamodb_store::DynamoDbStore;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct User {
/// id: String,
/// name: String,
/// age: u32,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let store = DynamoDbStore::new().await?;
///
/// let user = User {
/// id: "user123".to_string(),
/// name: "John Doe".to_string(),
/// age: 30,
/// };
///
/// store.put("users", &user).await?;
/// Ok(())
/// }
/// ```
pub async fn put<T: Serialize>(
&self,
table_name: &str,
item: &T,
) -> Result<PutItemOutput> {
Self::validate_table_name(table_name)?;
let item_map = serde_dynamo::to_item(item)
.map_err(|e| Error::Validation(format!("Failed to serialize item: {}", e)))?;
self.put_item(table_name, item_map).await
}
/// Deletes an item using a type-safe key struct.
///
/// This is a higher-level alternative to [`delete_item`](Self::delete_item) that works with
/// any type implementing [`Serialize`]. The key struct is automatically converted to
/// DynamoDB's AttributeValue format using `serde_dynamo`.
///
/// # Type Parameters
///
/// * `K` - Any type that implements [`Serialize`] representing the primary key
///
/// # Arguments
///
/// * `table_name` - The name of the DynamoDB table
/// * `key` - A reference to the key struct identifying the item to delete
///
/// # Returns
///
/// Returns `Ok(DeleteItemOutput)` on success. The operation succeeds even if the item doesn't exist.
///
/// # Errors
///
/// Returns an error if:
/// - The table name is empty
/// - Serialization fails (invalid key struct for DynamoDB)
/// - AWS credentials are not properly configured
/// - The specified table does not exist
/// - The key does not match the table's key schema
/// - Network connectivity issues occur
/// - IAM permissions are insufficient
///
/// # Example
///
/// ```rust,no_run
/// use clean_dynamodb_store::DynamoDbStore;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct UserKey {
/// id: String,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let store = DynamoDbStore::new().await?;
///
/// let key = UserKey {
/// id: "user123".to_string(),
/// };
///
/// store.delete("users", &key).await?;
/// Ok(())
/// }
/// ```
pub async fn delete<K: Serialize>(
&self,
table_name: &str,
key: &K,
) -> Result<DeleteItemOutput> {
Self::validate_table_name(table_name)?;
let key_map = serde_dynamo::to_item(key)
.map_err(|e| Error::Validation(format!("Failed to serialize key: {}", e)))?;
self.delete_item(table_name, key_map).await
}
/// Retrieves an item from DynamoDB and deserializes it into a type-safe struct.
///
/// This is a high-level method that retrieves an item using a key struct and
/// automatically deserializes the result into the requested type using `serde_dynamo`.
///
/// # Type Parameters
///
/// * `K` - Any type that implements [`Serialize`] representing the primary key
/// * `T` - Any type that implements [`DeserializeOwned`] for the item data
///
/// # Arguments
///
/// * `table_name` - The name of the DynamoDB table
/// * `key` - A reference to the key struct identifying the item to retrieve
///
/// # Returns
///
/// Returns `Ok(Some(T))` if the item exists and was successfully deserialized.
/// Returns `Ok(None)` if the item does not exist in the table.
///
/// # Errors
///
/// Returns an error if:
/// - The table name is empty
/// - Key serialization fails
/// - Item deserialization fails (data doesn't match expected type)
/// - AWS credentials are not properly configured
/// - The specified table does not exist
/// - Network connectivity issues occur
/// - IAM permissions are insufficient
///
/// # Example
///
/// ```rust,no_run
/// use clean_dynamodb_store::DynamoDbStore;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize)]
/// struct UserKey {
/// id: String,
/// }
///
/// #[derive(Deserialize)]
/// struct User {
/// id: String,
/// name: String,
/// age: u32,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let store = DynamoDbStore::new().await?;
///
/// let key = UserKey {
/// id: "user123".to_string(),
/// };
///
/// match store.get::<UserKey, User>("users", &key).await? {
/// Some(user) => println!("Found user: {}", user.name),
/// None => println!("User not found"),
/// }
///
/// Ok(())
/// }
/// ```
pub async fn get<K: Serialize, T: DeserializeOwned>(
&self,
table_name: &str,
key: &K,
) -> Result<Option<T>> {
Self::validate_table_name(table_name)?;
let key_map = serde_dynamo::to_item(key)
.map_err(|e| Error::Validation(format!("Failed to serialize key: {}", e)))?;
let result = self
.client
.get_item()
.table_name(table_name)
.set_key(Some(key_map))
.send()
.await
.map_err(|e| Error::AwsSdk(Box::new(e.into())))?;
match result.item {
Some(item) => {
let deserialized = serde_dynamo::from_item(item)
.map_err(|e| Error::Validation(format!("Failed to deserialize item: {}", e)))?;
Ok(Some(deserialized))
}
None => Ok(None),
}
}
}