clean_dynamodb_store 0.1.0

A library which follows clean architecture principles and provides a DynamoDB store implementation.
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
# AWS Clean DynamoDB Store

`clean_dynamodb_store` is a Rust library designed to follow clean architecture principles, offering a straightforward and efficient DynamoDB store implementation. It simplifies interactions with AWS DynamoDB, making it easier to perform common database operations such as inserting and deleting items in a DynamoDB table.

## Features

- **Complete CRUD Operations** - Put, Get, Delete, Update with type-safe and low-level APIs
- **Advanced Querying** - Query and Scan operations with filter expressions
- **Batch Operations** - Efficient batch reads and writes with automatic chunking
- **Type-safe API** - Work with your own Rust structs using serde
- **Efficient client reuse** - Following AWS SDK best practices
- **Optimized for AWS Lambda** - Minimal cold start overhead
- **Dual API** - High-level type-safe methods + low-level HashMap methods
- **Full serde support** - Flattening, enums, custom serialization
- **Update Expressions** - Partial updates with SET, ADD, REMOVE, DELETE
- **Pagination Support** - Query and Scan with `last_evaluated_key`
- **Input validation** - Table names and items/keys
- **Custom error types** - Better error handling with thiserror
- **Clean architecture** - Designed with SOLID principles in mind

## Prerequisites

Before you begin, ensure you have met the following requirements:

- Rust 2024 edition or later
- AWS account and configured AWS CLI or environment variables for AWS access

## Installation

Add `clean_dynamodb_store` to your `Cargo.toml`:

```toml
[dependencies]
clean_dynamodb_store = "0.1.0"
```
## Usage

Create a `DynamoDbStore` once and reuse it across operations for optimal performance.

### Type-Safe API (Recommended)

Work with your own structs using serde - no manual AttributeValue construction needed:

```rust
use clean_dynamodb_store::DynamoDbStore;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct User {
    id: String,
    name: String,
    age: u32,
}

#[derive(Serialize)]
struct UserKey {
    id: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create store once, reuse many times
    let store = DynamoDbStore::new().await?;

    // Put an item
    let user = User {
        id: "user123".to_string(),
        name: "John Doe".to_string(),
        age: 30,
    };
    store.put("users", &user).await?;

    // Get an item
    let key = UserKey { id: "user123".to_string() };
    let user: Option<User> = store.get("users", &key).await?;

    if let Some(user) = user {
        println!("Found user: {} (age {})", user.name, user.age);
    }

    // Delete an item
    store.delete("users", &key).await?;

    Ok(())
}
```

### Table-Scoped API (Repository Pattern)

For implementing the repository pattern or working extensively with specific tables, you can create table-bound stores:

```rust
use clean_dynamodb_store::DynamoDbStore;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct User {
    id: String,
    name: String,
}

#[derive(Serialize)]
struct UserKey {
    id: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let store = DynamoDbStore::new().await?;

    // Create table-bound stores - great for repository pattern
    let users = store.for_table("users");
    let orders = store.for_table("orders");

    // Use without passing table name on each call
    let user = User {
        id: "user123".to_string(),
        name: "John Doe".to_string(),
    };
    users.put(&user).await?;

    let key = UserKey { id: "user123".to_string() };
    let user: Option<User> = users.get(&key).await?;

    users.delete(&key).await?;

    Ok(())
}
```

**When to use table-scoped stores:**
- Implementing repository pattern (one repository per entity/table)
- Building domain models with clean architecture principles
- Working extensively with specific tables
- Want cleaner method signatures without table name repetition

### Low-Level API

For advanced use cases, you can work directly with DynamoDB's AttributeValue types:

```rust
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?;

    // Put an item
    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()));
    store.put_item("users", item).await?;

    // Delete an item
    let mut key = HashMap::new();
    key.insert("id".to_string(), AttributeValue::S("user123".to_string()));
    store.delete_item("users", key).await?;

    Ok(())
}
```

### Update Operations

For partial item updates without replacing the entire item:

```rust
use clean_dynamodb_store::DynamoDbStore;
use aws_sdk_dynamodb::types::AttributeValue;
use serde::Serialize;
use std::collections::HashMap;

#[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".into() };

    // Update specific attributes using update expressions
    let update_expression = "SET age = :age, #n = :name".to_string();

    let mut values = HashMap::new();
    values.insert(":age".to_string(), AttributeValue::N("31".to_string()));
    values.insert(":name".to_string(), AttributeValue::S("John Updated".to_string()));

    let mut names = HashMap::new();
    names.insert("#n".to_string(), "name".to_string()); // 'name' is a reserved keyword

    store.update("users", &key, update_expression, Some(values), Some(names)).await?;

    Ok(())
}
```

**Update expression actions:**
- `SET` - Add or update attributes
- `REMOVE` - Delete attributes
- `ADD` - Increment numbers or add to sets
- `DELETE` - Remove from sets

### Query Operations

Efficiently retrieve items by partition key (and optional sort key):

```rust
use clean_dynamodb_store::DynamoDbStore;
use aws_sdk_dynamodb::types::AttributeValue;
use serde::Deserialize;
use std::collections::HashMap;

#[derive(Deserialize)]
struct Order {
    user_id: String,
    order_id: String,
    total: f64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let store = DynamoDbStore::new().await?;

    // Query all orders for a specific user
    let key_condition = "user_id = :user_id".to_string();

    let mut values = HashMap::new();
    values.insert(":user_id".to_string(), AttributeValue::S("user123".to_string()));

    let result = store.query::<Order>("orders", key_condition, values, None).await?;

    println!("Found {} orders", result.count);
    for order in result.items {
        println!("Order {}: ${}", order.order_id, order.total);
    }

    // Handle pagination if needed
    if let Some(last_key) = result.last_evaluated_key {
        // Use last_key for next query
    }

    Ok(())
}
```

### Scan Operations

Scan entire table (use sparingly, prefer Query when possible):

```rust
use clean_dynamodb_store::DynamoDbStore;
use aws_sdk_dynamodb::types::AttributeValue;
use serde::Deserialize;
use std::collections::HashMap;

#[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?;

    // Scan with filter
    let filter = Some("age > :min_age".to_string());

    let mut values = HashMap::new();
    values.insert(":min_age".to_string(), AttributeValue::N("18".to_string()));

    let result = store.scan::<User>("users", filter, Some(values), None).await?;

    println!("Found {} users (scanned {})", result.count, result.scanned_count);

    Ok(())
}
```

### Batch Operations

Efficiently write or read large numbers of items using batch operations. The library automatically handles chunking and retries with exponential backoff.

#### Batch Write

For writing large numbers of items, batch operations chunk into groups of 25 (DynamoDB's BatchWriteItem limit):

```rust
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?;

    // Create 1000 users
    let users: Vec<User> = (0..1000)
        .map(|i| User {
            id: format!("user{}", i),
            name: format!("User {}", i),
            age: 20 + (i % 50),
        })
        .collect();

    // Batch write - automatically chunks into groups of 25 and retries failures
    let result = store.batch_put("users", &users).await?;

    println!("Successfully wrote {} items", result.successful);
    if result.failed > 0 {
        println!("Failed to write {} items", result.failed);
        for failed in &result.failed_items {
            println!("  Error: {}", failed.error);
        }
    }

    Ok(())
}
```

#### Batch Get

For retrieving large numbers of items, batch operations chunk into groups of 100 (DynamoDB's BatchGetItem limit):

```rust
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?;

    // Create 250 keys to retrieve
    let keys: Vec<UserKey> = (0..250)
        .map(|i| UserKey {
            id: format!("user{}", i),
        })
        .collect();

    // Batch get - automatically chunks into groups of 100 and retries failures
    let result = store.batch_get::<UserKey, User>("users", &keys).await?;

    println!("Successfully retrieved {} items", result.successful);
    for user in &result.items {
        println!("User: {} (age {})", user.name, user.age);
    }

    if result.failed > 0 {
        println!("Failed to retrieve {} keys", result.failed);
    }

    Ok(())
}
```

**Batch operations features:**
- Automatic chunking (25 items for write, 100 for get)
- Exponential backoff retry for throttled requests (up to 3 retries)
- Detailed success/failure reporting
- Works with both type-safe API and table-scoped stores

## AWS Lambda Usage

For AWS Lambda functions, initialize the store in `main()` to reuse the client across warm invocations:

```rust
use clean_dynamodb_store::DynamoDbStore;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct User {
    id: String,
    name: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize once during cold start
    let store = DynamoDbStore::new().await?;

    // Pass to handler - reused across warm invocations
    lambda_runtime::run(service_fn(|event| handler(event, &store))).await
}

async fn handler(
    event: Event,
    store: &DynamoDbStore,
) -> Result<Response, Box<dyn std::error::Error>> {
    // Use store with type-safe API - no client creation overhead!
    let user = User {
        id: event.id,
        name: event.name,
    };
    store.put("users", &user).await?;

    Ok(Response::success())
}
```

## License

Distributed under the MIT License. See LICENSE for more information.

## Contact

Ivan Videnovic - videnovici@yahoo.com