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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
use dynoxide::Database;
use dynoxide::actions::create_table::CreateTableRequest;
use dynoxide::actions::describe_table::DescribeTableRequest;
use dynoxide::actions::update_table::UpdateTableRequest;
use dynoxide::types::{AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType};
use serde_json::json;

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

fn create_simple_table(db: &Database, name: &str) {
    let req = CreateTableRequest {
        table_name: 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(req).unwrap();
}

fn put_item(
    db: &Database,
    table: &str,
    pk: &str,
    sk: &str,
    gsi1pk: Option<&str>,
    gsi1sk: Option<&str>,
) {
    let mut item = json!({
        "PK": {"S": pk},
        "SK": {"S": sk},
    });
    if let Some(gpk) = gsi1pk {
        item["GSI1PK"] = json!({"S": gpk});
    }
    if let Some(gsk) = gsi1sk {
        item["GSI1SK"] = json!({"S": gsk});
    }
    let req = serde_json::from_value(json!({
        "TableName": table,
        "Item": item,
    }))
    .unwrap();
    db.put_item(req).unwrap();
}

#[test]
fn test_update_table_create_gsi() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
            {"AttributeName": "GSI1SK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [
                    {"AttributeName": "GSI1PK", "KeyType": "HASH"},
                    {"AttributeName": "GSI1SK", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();

    let resp = db.update_table(req).unwrap();
    assert_eq!(resp.table_description.table_name, "TestTable");

    let gsis = resp.table_description.global_secondary_indexes.unwrap();
    assert_eq!(gsis.len(), 1);
    assert_eq!(gsis[0].index_name, "GSI1");
    assert_eq!(gsis[0].index_status, "ACTIVE");
}

#[test]
fn test_update_table_create_gsi_backfills_existing_items() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    // Put items BEFORE creating the GSI
    put_item(
        &db,
        "TestTable",
        "user#1",
        "profile",
        Some("org#A"),
        Some("user#1"),
    );
    put_item(
        &db,
        "TestTable",
        "user#2",
        "profile",
        Some("org#A"),
        Some("user#2"),
    );
    put_item(
        &db,
        "TestTable",
        "user#3",
        "profile",
        Some("org#B"),
        Some("user#3"),
    );
    // This item lacks GSI keys — should NOT appear in GSI
    put_item(&db, "TestTable", "user#4", "settings", None, None);

    // Now create the GSI
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
            {"AttributeName": "GSI1SK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [
                    {"AttributeName": "GSI1PK", "KeyType": "HASH"},
                    {"AttributeName": "GSI1SK", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();
    db.update_table(req).unwrap();

    // Query the GSI — should find backfilled items
    let query_req = serde_json::from_value(json!({
        "TableName": "TestTable",
        "IndexName": "GSI1",
        "KeyConditionExpression": "GSI1PK = :pk",
        "ExpressionAttributeValues": {":pk": {"S": "org#A"}},
    }))
    .unwrap();
    let resp = db.query(query_req).unwrap();
    assert_eq!(resp.count, 2);

    // Query org#B
    let query_req = serde_json::from_value(json!({
        "TableName": "TestTable",
        "IndexName": "GSI1",
        "KeyConditionExpression": "GSI1PK = :pk",
        "ExpressionAttributeValues": {":pk": {"S": "org#B"}},
    }))
    .unwrap();
    let resp = db.query(query_req).unwrap();
    assert_eq!(resp.count, 1);
}

/// Backfill excludes an item that has the GSI partition key but not its sort key.
#[test]
fn test_update_table_create_gsi_backfill_skips_item_without_sort_key() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    // Has the GSI partition key but not the sort key — excluded.
    put_item(&db, "TestTable", "user#1", "profile", Some("org#A"), None);
    // Has both GSI keys — included.
    put_item(
        &db,
        "TestTable",
        "user#2",
        "profile",
        Some("org#A"),
        Some("user#2"),
    );

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
            {"AttributeName": "GSI1SK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [
                    {"AttributeName": "GSI1PK", "KeyType": "HASH"},
                    {"AttributeName": "GSI1SK", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();
    db.update_table(req).unwrap();

    let scan_req = serde_json::from_value(json!({
        "TableName": "TestTable",
        "IndexName": "GSI1",
    }))
    .unwrap();
    let resp = db.scan(scan_req).unwrap();
    assert_eq!(resp.count, 1);
}

#[test]
fn test_update_table_delete_gsi() {
    let db = make_db();

    // Create table with a GSI
    let req: CreateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "KeySchema": [
            {"AttributeName": "PK", "KeyType": "HASH"},
            {"AttributeName": "SK", "KeyType": "RANGE"},
        ],
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
            {"AttributeName": "GSI1SK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexes": [{
            "IndexName": "GSI1",
            "KeySchema": [
                {"AttributeName": "GSI1PK", "KeyType": "HASH"},
                {"AttributeName": "GSI1SK", "KeyType": "RANGE"},
            ],
            "Projection": {"ProjectionType": "ALL"},
        }]
    }))
    .unwrap();
    db.create_table(req).unwrap();

    // Delete the GSI via UpdateTable
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "GlobalSecondaryIndexUpdates": [{
            "Delete": {"IndexName": "GSI1"}
        }]
    }))
    .unwrap();

    let resp = db.update_table(req).unwrap();
    assert!(resp.table_description.global_secondary_indexes.is_none());

    // Verify GSI query now fails
    let query_req = serde_json::from_value(json!({
        "TableName": "TestTable",
        "IndexName": "GSI1",
        "KeyConditionExpression": "GSI1PK = :pk",
        "ExpressionAttributeValues": {":pk": {"S": "test"}},
    }))
    .unwrap();
    let err = db.query(query_req).unwrap_err();
    assert!(
        err.to_string()
            .contains("does not have the specified index")
    );
}

#[test]
fn test_update_table_create_duplicate_gsi_fails() {
    let db = make_db();

    let req: CreateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "KeySchema": [{"AttributeName": "PK", "KeyType": "HASH"}],
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexes": [{
            "IndexName": "GSI1",
            "KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"}],
            "Projection": {"ProjectionType": "ALL"},
        }]
    }))
    .unwrap();
    db.create_table(req).unwrap();

    // Try to create the same GSI again
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"}],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(err.to_string().contains("Index already exists"));
}

#[test]
fn test_update_table_delete_nonexistent_gsi_fails() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "GlobalSecondaryIndexUpdates": [{
            "Delete": {"IndexName": "NonexistentGSI"}
        }]
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        matches!(
            &err,
            dynoxide::errors::DynoxideError::ResourceNotFoundException(_)
        ),
        "Expected ResourceNotFoundException, got: {:?}",
        err
    );
    assert!(
        err.to_string().contains("Requested resource not found"),
        "Unexpected message: {}",
        err
    );
}

#[test]
fn test_update_table_nonexistent_table_fails() {
    let db = make_db();

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "DoesNotExist",
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"}],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(err.to_string().contains("not found"));
}

#[test]
fn test_update_table_create_multiple_gsis_sequentially() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    // Add GSI1
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"}],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();
    db.update_table(req).unwrap();

    // Add GSI2 in a separate call
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
            {"AttributeName": "GSI2PK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI2",
                "KeySchema": [{"AttributeName": "GSI2PK", "KeyType": "HASH"}],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();
    let resp = db.update_table(req).unwrap();

    let gsis = resp.table_description.global_secondary_indexes.unwrap();
    assert_eq!(gsis.len(), 2);
    let names: Vec<&str> = gsis.iter().map(|g| g.index_name.as_str()).collect();
    assert!(names.contains(&"GSI1"));
    assert!(names.contains(&"GSI2"));
}

#[test]
fn test_update_table_response_includes_table_description() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"}],
                "Projection": {"ProjectionType": "ALL"},
            }
        }]
    }))
    .unwrap();

    let resp = db.update_table(req).unwrap();
    let desc = &resp.table_description;

    assert_eq!(desc.table_name, "TestTable");
    assert_eq!(desc.table_status, "ACTIVE");
    assert!(!desc.table_arn.is_empty());
    assert!(desc.key_schema.len() == 2);
    assert!(desc.creation_date_time.is_some());
}

#[test]
fn test_update_table_gsi_projection_types() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    // Add item before creating GSIs
    put_item(
        &db,
        "TestTable",
        "user#1",
        "profile",
        Some("org#A"),
        Some("user#1"),
    );
    // Also add a non-key attribute
    let req = serde_json::from_value(json!({
        "TableName": "TestTable",
        "Item": {
            "PK": {"S": "user#2"},
            "SK": {"S": "profile"},
            "GSI1PK": {"S": "org#A"},
            "GSI1SK": {"S": "user#2"},
            "email": {"S": "user2@example.com"},
            "name": {"S": "User Two"},
        }
    }))
    .unwrap();
    db.put_item(req).unwrap();

    // Create GSI with KEYS_ONLY projection
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
            {"AttributeName": "GSI1SK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{
            "Create": {
                "IndexName": "GSI1",
                "KeySchema": [
                    {"AttributeName": "GSI1PK", "KeyType": "HASH"},
                    {"AttributeName": "GSI1SK", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "KEYS_ONLY"},
            }
        }]
    }))
    .unwrap();
    db.update_table(req).unwrap();

    // Query GSI — should only return key attributes
    let query_req = serde_json::from_value(json!({
        "TableName": "TestTable",
        "IndexName": "GSI1",
        "KeyConditionExpression": "GSI1PK = :pk",
        "ExpressionAttributeValues": {":pk": {"S": "org#A"}},
    }))
    .unwrap();
    let resp = db.query(query_req).unwrap();
    assert_eq!(resp.count, 2);

    // Verify the backfilled items only have key attributes
    let items = resp.items.unwrap();
    for item in &items {
        assert!(item.contains_key("PK"));
        assert!(item.contains_key("SK"));
        assert!(item.contains_key("GSI1PK"));
        assert!(item.contains_key("GSI1SK"));
        // Non-key attributes should NOT be present
        assert!(!item.contains_key("email"));
        assert!(!item.contains_key("name"));
    }
}

#[test]
fn test_update_table_cache_invalidation() {
    let db = make_db();
    create_simple_table(&db, "TestTable");

    // DescribeTable to populate any internal cache
    let desc_req = serde_json::from_value(serde_json::json!({"TableName": "TestTable"})).unwrap();
    let resp = db.describe_table(desc_req).unwrap();
    assert!(resp.table.global_secondary_indexes.is_none());

    // Add a GSI via UpdateTable
    let req: UpdateTableRequest = serde_json::from_value(serde_json::json!({
        "TableName": "TestTable",
        "AttributeDefinitions": [
            {"AttributeName": "PK", "AttributeType": "S"},
            {"AttributeName": "SK", "AttributeType": "S"},
            {"AttributeName": "GSI1PK", "AttributeType": "S"},
        ],
        "GlobalSecondaryIndexUpdates": [{"Create": {
            "IndexName": "GSI1",
            "KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"}],
            "Projection": {"ProjectionType": "ALL"},
        }}]
    }))
    .unwrap();
    db.update_table(req).unwrap();

    // DescribeTable should reflect the new GSI (not stale cached data)
    let desc_req = serde_json::from_value(serde_json::json!({"TableName": "TestTable"})).unwrap();
    let resp = db.describe_table(desc_req).unwrap();
    let gsis = resp.table.global_secondary_indexes.unwrap();
    assert_eq!(gsis.len(), 1);
    assert_eq!(gsis[0].index_name, "GSI1");
}

fn create_pay_per_request_table(db: &Database, name: &str) {
    let req: CreateTableRequest = serde_json::from_value(json!({
        "TableName": name,
        "KeySchema": [{"AttributeName": "a", "KeyType": "HASH"}],
        "AttributeDefinitions": [{"AttributeName": "a", "AttributeType": "N"}],
        "BillingMode": "PAY_PER_REQUEST"
    }))
    .unwrap();
    db.create_table(req).unwrap();
}

fn create_provisioned_table(db: &Database, name: &str, rcu: i64, wcu: i64) {
    let req: CreateTableRequest = serde_json::from_value(json!({
        "TableName": name,
        "KeySchema": [{"AttributeName": "a", "KeyType": "HASH"}],
        "AttributeDefinitions": [{"AttributeName": "a", "AttributeType": "S"}],
        "ProvisionedThroughput": {
            "ReadCapacityUnits": rcu,
            "WriteCapacityUnits": wcu
        }
    }))
    .unwrap();
    db.create_table(req).unwrap();
}

#[test]
fn test_limit_exceeded_too_many_gsi_updates() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 10, 5);

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "GlobalSecondaryIndexUpdates": [
            {"Delete": {"IndexName": "abc"}},
            {"Delete": {"IndexName": "abd"}},
            {"Delete": {"IndexName": "abe"}},
            {"Delete": {"IndexName": "abf"}},
            {"Delete": {"IndexName": "abg"}},
            {"Delete": {"IndexName": "abh"}}
        ]
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string().contains("Subscriber limit exceeded"),
        "Expected LimitExceededException, got: {}",
        err
    );
    assert_eq!(
        err.error_type(),
        "com.amazonaws.dynamodb.v20120810#LimitExceededException"
    );
}

#[test]
fn test_provisioned_without_provisioned_throughput() {
    let db = make_db();
    create_pay_per_request_table(&db, "TestTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "PROVISIONED"
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string()
            .contains("ProvisionedThroughput must be specified when BillingMode is PROVISIONED"),
        "Expected validation about missing PT, got: {}",
        err
    );
}

#[test]
fn test_provisioned_throughput_update_when_pay_per_request() {
    let db = make_db();
    create_pay_per_request_table(&db, "TestTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string().contains(
            "Neither ReadCapacityUnits nor WriteCapacityUnits can be specified when BillingMode is PAY_PER_REQUEST"
        ),
        "Expected PAY_PER_REQUEST validation, got: {}",
        err
    );
}

#[test]
fn test_high_index_capacity_when_index_does_not_exist() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 10, 5);

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "GlobalSecondaryIndexUpdates": [{
            "Update": {
                "IndexName": "abc",
                "ProvisionedThroughput": {
                    "ReadCapacityUnits": 1000000000001_i64,
                    "WriteCapacityUnits": 1000000000001_i64
                }
            }
        }]
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string().contains("Action Blocked: IndexUpdate"),
        "Expected Action Blocked error, got: {}",
        err
    );
}

#[test]
fn test_same_read_write_validation() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 10, 5);

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "ProvisionedThroughput": {"ReadCapacityUnits": 10, "WriteCapacityUnits": 5}
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string()
            .contains("The provisioned throughput for the table will not change"),
        "Expected same-values validation, got: {}",
        err
    );
}

#[test]
fn test_triple_rates_and_reduce() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 10, 5);

    // Triple the rates
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "ProvisionedThroughput": {"ReadCapacityUnits": 30, "WriteCapacityUnits": 15}
    }))
    .unwrap();

    let resp = db.update_table(req).unwrap();
    let desc = &resp.table_description;
    assert_eq!(desc.table_status, "UPDATING");

    // Immediate response shows old values
    let pt = desc.provisioned_throughput.as_ref().unwrap();
    assert_eq!(pt.read_capacity_units, 10);
    assert_eq!(pt.write_capacity_units, 5);
    assert!(pt.last_increase_date_time.is_some());

    // DescribeTable should show the new values (we apply instantly)
    let desc_req = serde_json::from_value(serde_json::json!({"TableName": "TestTable"})).unwrap();
    let desc_resp = db.describe_table(desc_req).unwrap();
    let dt = &desc_resp.table;
    let pt2 = dt.provisioned_throughput.as_ref().unwrap();
    assert_eq!(pt2.read_capacity_units, 30);
    assert_eq!(pt2.write_capacity_units, 15);

    // Now reduce back
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "ProvisionedThroughput": {"ReadCapacityUnits": 10, "WriteCapacityUnits": 5}
    }))
    .unwrap();

    let resp = db.update_table(req).unwrap();
    let desc = &resp.table_description;
    assert_eq!(desc.table_status, "UPDATING");
    let pt3 = desc.provisioned_throughput.as_ref().unwrap();
    // Shows old values (30/15) while UPDATING
    assert_eq!(pt3.read_capacity_units, 30);
    assert_eq!(pt3.write_capacity_units, 15);
    assert!(pt3.last_decrease_date_time.is_some());

    // After "settling", DescribeTable shows new values
    let desc_req = serde_json::from_value(serde_json::json!({"TableName": "TestTable"})).unwrap();
    let desc_resp = db.describe_table(desc_req).unwrap();
    let pt4 = desc_resp.table.provisioned_throughput.as_ref().unwrap();
    assert_eq!(pt4.read_capacity_units, 10);
    assert_eq!(pt4.write_capacity_units, 5);
    assert_eq!(pt4.number_of_decreases_today, 1);
}

#[test]
fn test_switch_provisioned_to_pay_per_request() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 5, 5);

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "PAY_PER_REQUEST"
    }))
    .unwrap();

    db.update_table(req).unwrap();

    // DescribeTable should reflect PAY_PER_REQUEST
    let desc_req = serde_json::from_value(json!({"TableName": "TestTable"})).unwrap();
    let desc_resp = db.describe_table(desc_req).unwrap();
    let bms = desc_resp
        .table
        .billing_mode_summary
        .as_ref()
        .expect("BillingModeSummary should be present");
    assert_eq!(bms.billing_mode, "PAY_PER_REQUEST");
}

#[test]
fn test_switch_pay_per_request_to_provisioned() {
    let db = make_db();
    create_pay_per_request_table(&db, "TestTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "PROVISIONED",
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        }
    }))
    .unwrap();

    db.update_table(req).unwrap();

    // DescribeTable should reflect PROVISIONED with throughput values
    let desc_req = serde_json::from_value(json!({"TableName": "TestTable"})).unwrap();
    let desc_resp = db.describe_table(desc_req).unwrap();
    // BillingModeSummary should be absent for PROVISIONED tables
    assert!(
        desc_resp.table.billing_mode_summary.is_none(),
        "BillingModeSummary should be None for PROVISIONED tables"
    );
    let pt = desc_resp
        .table
        .provisioned_throughput
        .as_ref()
        .expect("ProvisionedThroughput should be present");
    assert_eq!(pt.read_capacity_units, 5);
    assert_eq!(pt.write_capacity_units, 5);
}

#[test]
fn test_reject_pay_per_request_with_provisioned_throughput() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 5, 5);

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "PAY_PER_REQUEST",
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        }
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string().contains(
            "Neither ReadCapacityUnits nor WriteCapacityUnits can be specified when BillingMode is PAY_PER_REQUEST"
        ),
        "Expected PAY_PER_REQUEST + PT validation, got: {}",
        err
    );
}

#[test]
fn test_reject_invalid_billing_mode() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 5, 5);

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "INVALID_MODE"
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string()
            .contains("failed to satisfy constraint: Member must satisfy enum value set"),
        "Expected enum validation, got: {}",
        err
    );
}

#[test]
fn test_provisioned_to_provisioned_same_throughput_rejected() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 5, 5);

    // Explicitly setting BillingMode: PROVISIONED with same throughput should fail
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "PROVISIONED",
        "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}
    }))
    .unwrap();

    let err = db.update_table(req).unwrap_err();
    assert!(
        err.to_string()
            .contains("The provisioned throughput for the table will not change"),
        "Expected same-values validation, got: {}",
        err
    );
}

#[test]
fn test_provisioned_to_provisioned_different_throughput_accepted() {
    let db = make_db();
    create_provisioned_table(&db, "TestTable", 5, 5);

    // Explicitly setting BillingMode: PROVISIONED with different throughput should succeed
    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TestTable",
        "BillingMode": "PROVISIONED",
        "ProvisionedThroughput": {"ReadCapacityUnits": 10, "WriteCapacityUnits": 5}
    }))
    .unwrap();

    db.update_table(req).unwrap();
}

fn describe(db: &Database, name: &str) -> dynoxide::actions::TableDescription {
    db.describe_table(DescribeTableRequest {
        table_name: name.to_string(),
    })
    .unwrap()
    .table
}

#[test]
fn test_update_table_single_field_table_class() {
    // Issue #45: a lone TableClass change must be accepted and persisted, not
    // rejected with "At least one of ...".
    let db = make_db();
    create_simple_table(&db, "TcTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TcTable",
        "TableClass": "STANDARD_INFREQUENT_ACCESS",
    }))
    .unwrap();
    db.update_table(req).unwrap();

    let summary = describe(&db, "TcTable")
        .table_class_summary
        .expect("TableClassSummary should be present after update");
    assert_eq!(summary.table_class, "STANDARD_INFREQUENT_ACCESS");
}

#[test]
fn test_update_table_single_field_on_demand_throughput() {
    // Issue #45: a lone OnDemandThroughput change must be accepted and persisted.
    let db = make_db();
    create_simple_table(&db, "OdtTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "OdtTable",
        "OnDemandThroughput": {"MaxReadRequestUnits": 20, "MaxWriteRequestUnits": 15},
    }))
    .unwrap();
    db.update_table(req).unwrap();

    let odt = describe(&db, "OdtTable")
        .on_demand_throughput
        .expect("OnDemandThroughput should be present after update");
    assert_eq!(odt.max_read_request_units, Some(20));
    assert_eq!(odt.max_write_request_units, Some(15));
}

#[test]
fn test_update_table_single_field_table_class_with_empty_gsi_updates() {
    // Issue #45 edge: a lone TableClass change paired with an empty
    // GlobalSecondaryIndexUpdates array must still be accepted, not rejected by
    // the "at least one of ..." guard.
    let db = make_db();
    create_simple_table(&db, "TcEmptyGsi");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "TcEmptyGsi",
        "GlobalSecondaryIndexUpdates": [],
        "TableClass": "STANDARD_INFREQUENT_ACCESS",
    }))
    .unwrap();
    db.update_table(req).unwrap();

    let summary = describe(&db, "TcEmptyGsi")
        .table_class_summary
        .expect("TableClassSummary should be present after update");
    assert_eq!(summary.table_class, "STANDARD_INFREQUENT_ACCESS");
}

#[test]
fn test_update_table_empty_request_still_rejected() {
    // Regression: a request that changes nothing must still be rejected.
    let db = make_db();
    create_simple_table(&db, "NoChange");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "NoChange",
        "GlobalSecondaryIndexUpdates": [],
    }))
    .unwrap();
    let err = db
        .update_table(req)
        .expect_err("a no-op UpdateTable must be rejected");
    assert!(
        matches!(err, dynoxide::errors::DynoxideError::ValidationException(_)),
        "expected ValidationException, got: {err:?}"
    );
}

#[test]
fn test_update_table_invalid_table_class_rejected() {
    // Issue #45: an invalid TableClass enum value is a ValidationException.
    let db = make_db();
    create_simple_table(&db, "BadTcTable");

    let req: UpdateTableRequest = serde_json::from_value(json!({
        "TableName": "BadTcTable",
        "TableClass": "PREMIUM_NONSENSE",
    }))
    .unwrap();
    let err = db
        .update_table(req)
        .expect_err("invalid TableClass must be rejected");
    assert!(
        matches!(err, dynoxide::errors::DynoxideError::ValidationException(_)),
        "expected ValidationException, got: {err:?}"
    );
}