dynoxide-rs 0.11.1

A lightweight, embeddable DynamoDB emulator backed by SQLite
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
use dynoxide::actions::create_table::StreamSpecification;
use dynoxide::{AttributeValue, Database, ImportOptions};
use std::collections::HashMap;

fn create_test_db() -> Database {
    Database::memory().unwrap()
}

fn create_table(db: &Database, table_name: &str) {
    use dynoxide::actions::create_table::CreateTableRequest;
    use dynoxide::types::{AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType};

    let request = CreateTableRequest {
        table_name: table_name.to_string(),
        key_schema: vec![
            KeySchemaElement {
                attribute_name: "pk".to_string(),
                key_type: KeyType::HASH,
            },
            KeySchemaElement {
                attribute_name: "sk".to_string(),
                key_type: KeyType::RANGE,
            },
        ],
        attribute_definitions: vec![
            AttributeDefinition {
                attribute_name: "pk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
            AttributeDefinition {
                attribute_name: "sk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
        ],
        ..Default::default()
    };
    db.create_table(request).unwrap();
}

fn create_table_with_gsi(db: &Database, table_name: &str) {
    use dynoxide::actions::create_table::CreateTableRequest;
    use dynoxide::types::{
        AttributeDefinition, GlobalSecondaryIndex, KeySchemaElement, KeyType, Projection,
        ProjectionType, ScalarAttributeType,
    };

    let request = CreateTableRequest {
        table_name: table_name.to_string(),
        key_schema: vec![
            KeySchemaElement {
                attribute_name: "pk".to_string(),
                key_type: KeyType::HASH,
            },
            KeySchemaElement {
                attribute_name: "sk".to_string(),
                key_type: KeyType::RANGE,
            },
        ],
        attribute_definitions: vec![
            AttributeDefinition {
                attribute_name: "pk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
            AttributeDefinition {
                attribute_name: "sk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
            AttributeDefinition {
                attribute_name: "email".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
        ],
        global_secondary_indexes: Some(vec![GlobalSecondaryIndex {
            index_name: "email-index".to_string(),
            key_schema: vec![KeySchemaElement {
                attribute_name: "email".to_string(),
                key_type: KeyType::HASH,
            }],
            projection: Projection {
                projection_type: Some(ProjectionType::ALL),
                non_key_attributes: None,
            },
            provisioned_throughput: None,
        }]),
        ..Default::default()
    };
    db.create_table(request).unwrap();
}

fn get_item(
    db: &Database,
    table_name: &str,
    pk: &str,
    sk: &str,
) -> Option<HashMap<String, AttributeValue>> {
    use dynoxide::actions::get_item::GetItemRequest;

    let request = GetItemRequest {
        table_name: table_name.to_string(),
        key: dynoxide::item! {
            "pk" => pk,
            "sk" => sk,
        },
        ..Default::default()
    };
    db.get_item(request).unwrap().item
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[test]
fn import_basic() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![
        dynoxide::item! { "pk" => "user#1", "sk" => "PROFILE", "name" => "Alice" },
        dynoxide::item! { "pk" => "user#2", "sk" => "PROFILE", "name" => "Bob" },
    ];

    let result = db
        .import_items("Users", items, ImportOptions::default())
        .unwrap();

    assert_eq!(result.items_imported, 2);
    assert!(result.bytes_imported > 0);

    // Verify items are readable
    let item1 = get_item(&db, "Users", "user#1", "PROFILE");
    assert!(item1.is_some());
    assert_eq!(
        item1.unwrap()["name"],
        AttributeValue::S("Alice".to_string())
    );

    let item2 = get_item(&db, "Users", "user#2", "PROFILE");
    assert!(item2.is_some());
    assert_eq!(item2.unwrap()["name"], AttributeValue::S("Bob".to_string()));
}

#[test]
fn import_empty_vec() {
    let db = create_test_db();
    create_table(&db, "Users");

    let result = db
        .import_items("Users", vec![], ImportOptions::default())
        .unwrap();

    assert_eq!(result.items_imported, 0);
    assert_eq!(result.bytes_imported, 0);
}

#[test]
fn import_nonexistent_table() {
    let db = create_test_db();

    let result = db.import_items("NoSuchTable", vec![], ImportOptions::default());
    assert!(result.is_err());
}

#[test]
fn import_duplicate_keys_last_wins() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![
        dynoxide::item! { "pk" => "user#1", "sk" => "PROFILE", "name" => "Alice" },
        dynoxide::item! { "pk" => "user#1", "sk" => "PROFILE", "name" => "Bob" },
    ];

    db.import_items("Users", items, ImportOptions::default())
        .unwrap();

    let item = get_item(&db, "Users", "user#1", "PROFILE").unwrap();
    assert_eq!(item["name"], AttributeValue::S("Bob".to_string()));
}

#[test]
fn import_maintains_gsi() {
    let db = create_test_db();
    create_table_with_gsi(&db, "Users");

    let items = vec![dynoxide::item! {
        "pk" => "user#1",
        "sk" => "PROFILE",
        "email" => "alice@example.com",
    }];

    db.import_items("Users", items, ImportOptions::default())
        .unwrap();

    // Query the GSI
    use dynoxide::actions::query::QueryRequest;
    let resp = db
        .query({
            QueryRequest {
                table_name: "Users".to_string(),
                index_name: Some("email-index".to_string()),
                key_condition_expression: Some("email = :email".to_string()),
                expression_attribute_values: Some(
                    dynoxide::item! { ":email" => "alice@example.com" },
                ),
                ..Default::default()
            }
        })
        .unwrap();

    let items = resp.items.unwrap();
    assert_eq!(items.len(), 1);
    assert_eq!(items[0]["pk"], AttributeValue::S("user#1".to_string()));
}

#[test]
fn import_sparse_gsi_skips_items_without_gsi_key() {
    let db = create_test_db();
    create_table_with_gsi(&db, "Users");

    // Item without the "email" attribute (GSI pk)
    let items = vec![dynoxide::item! {
        "pk" => "user#1",
        "sk" => "PROFILE",
    }];

    db.import_items("Users", items, ImportOptions::default())
        .unwrap();

    // Item exists in base table
    let item = get_item(&db, "Users", "user#1", "PROFILE");
    assert!(item.is_some());

    // But NOT in the GSI
    use dynoxide::actions::scan::ScanRequest;
    let resp = db
        .scan({
            ScanRequest {
                table_name: "Users".to_string(),
                index_name: Some("email-index".to_string()),
                ..Default::default()
            }
        })
        .unwrap();
    let gsi_items = resp.items.unwrap_or_default();
    assert_eq!(gsi_items.len(), 0);
}

/// Table with a composite GSI whose sort key is a non-key attribute.
fn create_table_with_composite_gsi(db: &Database, table_name: &str) {
    use dynoxide::actions::create_table::CreateTableRequest;
    use dynoxide::types::{
        AttributeDefinition, GlobalSecondaryIndex, KeySchemaElement, KeyType, Projection,
        ProjectionType, ScalarAttributeType,
    };

    let request = CreateTableRequest {
        table_name: table_name.to_string(),
        key_schema: vec![
            KeySchemaElement {
                attribute_name: "pk".to_string(),
                key_type: KeyType::HASH,
            },
            KeySchemaElement {
                attribute_name: "sk".to_string(),
                key_type: KeyType::RANGE,
            },
        ],
        attribute_definitions: vec![
            AttributeDefinition {
                attribute_name: "pk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
            AttributeDefinition {
                attribute_name: "sk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
            AttributeDefinition {
                attribute_name: "sparse_attribute".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
        ],
        global_secondary_indexes: Some(vec![GlobalSecondaryIndex {
            index_name: "sparse-index".to_string(),
            key_schema: vec![
                KeySchemaElement {
                    attribute_name: "pk".to_string(),
                    key_type: KeyType::HASH,
                },
                KeySchemaElement {
                    attribute_name: "sparse_attribute".to_string(),
                    key_type: KeyType::RANGE,
                },
            ],
            projection: Projection {
                projection_type: Some(ProjectionType::ALL),
                non_key_attributes: None,
            },
            provisioned_throughput: None,
        }]),
        ..Default::default()
    };
    db.create_table(request).unwrap();
}

/// Sort-key absence (not just partition-key absence) excludes an item on import.
#[test]
fn import_sparse_gsi_skips_items_without_gsi_sort_key() {
    let db = create_test_db();
    create_table_with_composite_gsi(&db, "Events");

    let items = vec![
        dynoxide::item! { "pk" => "e#1", "sk" => "A" },
        dynoxide::item! { "pk" => "e#2", "sk" => "B", "sparse_attribute" => "x" },
    ];
    db.import_items("Events", items, ImportOptions::default())
        .unwrap();

    use dynoxide::actions::scan::ScanRequest;
    let resp = db
        .scan(ScanRequest {
            table_name: "Events".to_string(),
            index_name: Some("sparse-index".to_string()),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(resp.items.unwrap_or_default().len(), 1);
}

#[test]
fn import_with_cached_at() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![dynoxide::item! {
        "pk" => "user#1",
        "sk" => "PROFILE",
    }];

    let opts = ImportOptions {
        set_cached_at: true,
        ..Default::default()
    };
    db.import_items("Users", items, opts).unwrap();

    // Verify cached_at is set by checking LRU items
    let lru = db.get_lru_items("Users", 10).unwrap();
    assert_eq!(lru.len(), 1);
    // pk is stored as a key string (e.g. "S:user#1")
    assert!(lru[0].0.contains("user#1"));
}

#[test]
fn import_without_cached_at_not_in_lru() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![dynoxide::item! {
        "pk" => "user#1",
        "sk" => "PROFILE",
    }];

    db.import_items("Users", items, ImportOptions::default())
        .unwrap();

    // Without set_cached_at, items should NOT appear in LRU (NULL cached_at)
    let lru = db.get_lru_items("Users", 10).unwrap();
    assert_eq!(lru.len(), 0);
}

#[test]
fn import_missing_partition_key_fails_and_rolls_back() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![
        dynoxide::item! { "pk" => "user#1", "sk" => "PROFILE", "name" => "Alice" },
        // Missing "pk" attribute -- should cause the whole import to fail
        dynoxide::item! { "sk" => "PROFILE", "name" => "Bob" },
    ];

    let result = db.import_items("Users", items, ImportOptions::default());
    assert!(result.is_err());

    // First item should NOT be persisted (entire transaction rolled back)
    let item = get_item(&db, "Users", "user#1", "PROFILE");
    assert!(item.is_none());
}

#[test]
fn import_missing_sort_key_fails_and_rolls_back() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![
        dynoxide::item! { "pk" => "user#1", "sk" => "PROFILE", "name" => "Alice" },
        // Missing "sk" attribute
        dynoxide::item! { "pk" => "user#2", "name" => "Bob" },
    ];

    let result = db.import_items("Users", items, ImportOptions::default());
    assert!(result.is_err());

    // First item should NOT be persisted
    let item = get_item(&db, "Users", "user#1", "PROFILE");
    assert!(item.is_none());
}

#[test]
fn import_calculates_item_size() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items = vec![dynoxide::item! {
        "pk" => "user#1",
        "sk" => "PROFILE",
        "name" => "Alice",
    }];

    let result = db
        .import_items("Users", items, ImportOptions::default())
        .unwrap();

    assert_eq!(result.items_imported, 1);
    assert!(result.bytes_imported > 0);
}

#[test]
fn import_large_batch() {
    let db = create_test_db();
    create_table(&db, "Users");

    let items: Vec<_> = (0..500)
        .map(|i| {
            dynoxide::item! {
                "pk" => format!("user#{i}"),
                "sk" => "PROFILE",
                "index" => i as i64,
            }
        })
        .collect();

    let result = db
        .import_items("Users", items, ImportOptions::default())
        .unwrap();

    assert_eq!(result.items_imported, 500);

    // Spot-check a few items
    assert!(get_item(&db, "Users", "user#0", "PROFILE").is_some());
    assert!(get_item(&db, "Users", "user#499", "PROFILE").is_some());
}

#[test]
fn import_with_record_streams() {
    use dynoxide::actions::create_table::CreateTableRequest;
    use dynoxide::actions::get_records::GetRecordsRequest;
    use dynoxide::actions::get_shard_iterator::GetShardIteratorRequest;
    use dynoxide::actions::list_streams::ListStreamsRequest;
    use dynoxide::types::{AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType};

    let db = create_test_db();

    // Create table with streams enabled
    let request = CreateTableRequest {
        table_name: "StreamTable".to_string(),
        key_schema: vec![
            KeySchemaElement {
                attribute_name: "pk".to_string(),
                key_type: KeyType::HASH,
            },
            KeySchemaElement {
                attribute_name: "sk".to_string(),
                key_type: KeyType::RANGE,
            },
        ],
        attribute_definitions: vec![
            AttributeDefinition {
                attribute_name: "pk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
            AttributeDefinition {
                attribute_name: "sk".to_string(),
                attribute_type: ScalarAttributeType::S,
            },
        ],
        stream_specification: Some(StreamSpecification {
            stream_enabled: true,
            stream_view_type: Some("NEW_AND_OLD_IMAGES".to_string()),
        }),
        ..Default::default()
    };
    db.create_table(request).unwrap();

    // Import with record_streams enabled
    let items = vec![
        dynoxide::item! { "pk" => "user#1", "sk" => "PROFILE", "name" => "Alice" },
        dynoxide::item! { "pk" => "user#2", "sk" => "PROFILE", "name" => "Bob" },
    ];
    let opts = ImportOptions {
        record_streams: true,
        ..Default::default()
    };
    let result = db.import_items("StreamTable", items, opts).unwrap();
    assert_eq!(result.items_imported, 2);

    // Verify stream records were created
    let streams_resp = db
        .list_streams(ListStreamsRequest {
            table_name: Some("StreamTable".to_string()),
            exclusive_start_stream_arn: None,
            limit: None,
        })
        .unwrap();
    assert_eq!(streams_resp.streams.len(), 1);
    let stream_arn = &streams_resp.streams[0].stream_arn;

    let iter_resp = db
        .get_shard_iterator(GetShardIteratorRequest {
            stream_arn: stream_arn.clone(),
            shard_id: "shardId-StreamTable-000000".to_string(),
            shard_iterator_type: "TRIM_HORIZON".to_string(),
            sequence_number: None,
        })
        .unwrap();

    let records_resp = db
        .get_records(GetRecordsRequest {
            shard_iterator: iter_resp.shard_iterator.unwrap(),
            limit: None,
        })
        .unwrap();

    // Should have 2 INSERT records (one per imported item)
    assert_eq!(records_resp.records.len(), 2);
    assert_eq!(records_resp.records[0].event_name, "INSERT");
    assert_eq!(records_resp.records[1].event_name, "INSERT");
}