modyne 0.3.0

High-level crate for interacting with single-table DynamoDB instances
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
#![doc = include_str!("../docs/modyne.md")]
#![warn(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(rustdoc::broken_intra_doc_links)]

mod error;
pub mod expr;
pub mod keys;
pub mod model;
pub mod types;

use std::collections::HashMap;

#[doc(inline)]
pub use aws_sdk_dynamodb::types::AttributeValue;
use keys::{IndexKeys, PrimaryKey};
use model::{ConditionCheck, ConditionalPut, Delete, Get, Put, Query, Scan, Update};
/// Derive macro for the [`trait@EntityDef`] trait
///
/// This macro piggy-backs on the attributes used by the `serde_derive`
/// crate. Note that using `flatten` will result in an empty projection
/// expression, pulling _all_ attributes on the item because this macro
/// cannot identify the field names used in the flattened structure.
#[cfg(feature = "derive")]
pub use modyne_derive::EntityDef;
/// Derive macro for the [`trait@Projection`] trait
///
/// Like [`derive@EntityDef`], this macro piggy-backs on the attributes used by
/// the `serde_derive` crate. Note that using `flatten` will result in
/// an empty projection expression, pulling _all_ attributes on the item
/// because this macro cannot identify the field names used in the
/// flattened structure.
///
/// Usage of this macro requires specifying the "parent" entity. For
/// example, with an entity called `MyEntity`, the projection should
/// have the following attribute: `#[entity(MyEntity)]`
#[cfg(feature = "derive")]
pub use modyne_derive::Projection;
use serde_dynamo::aws_sdk_dynamodb_1 as codec;

pub use crate::error::{Error, MalformedEntityTypeError};

/// An alias for a DynamoDB item
pub type Item = HashMap<String, AttributeValue>;

/// The name for a DynamoDB entity type
#[aliri_braid::braid(serde)]
pub struct EntityTypeName;

/// A description of a DynamoDB table
pub trait Table {
    /// The attribute name used for storing the entity type
    const ENTITY_TYPE_ATTRIBUTE: &'static str = "entity_type";

    /// The primary key to be used for the table
    type PrimaryKey: keys::PrimaryKey;

    /// Indexes defined on the table
    type IndexKeys: IndexKeys;

    /// Returns the name of the DynamoDB table
    fn table_name(&self) -> &str;

    /// Returns a reference to the DynamoDB client used by this table
    fn client(&self) -> &aws_sdk_dynamodb::Client;

    /// Deserializes the entity type from an attribute value
    ///
    /// In general, this function should not need to be overriden, but an override
    /// may be used in non-standard use cases, or for compatibility with
    /// existing systems.
    #[inline]
    fn deserialize_entity_type(
        attr: &AttributeValue,
    ) -> Result<&EntityTypeNameRef, MalformedEntityTypeError> {
        let Ok(value) = attr.as_s() else {
            return Err(MalformedEntityTypeError::ExpectedStringValue);
        };

        Ok(EntityTypeNameRef::from_str(value.as_str()))
    }

    /// Serializes the entity type as an attribute value
    ///
    /// In general, this function should not need to be overriden, but an override
    /// may be used in non-standard use cases, or for compatibility with
    /// existing systems.
    #[inline]
    fn serialize_entity_type(entity_type: &EntityTypeNameRef) -> AttributeValue {
        AttributeValue::S(entity_type.to_string())
    }
}

/// The name and attribute definition for an [`Entity`]
///
/// This trait is used to define the structure of an entity type in a
/// DynamoDB table and how the entity may be queried.
///
/// This trait can be implemented manually, but may be better implemented
/// using the [`derive@EntityDef`] derive macro exposed when
/// using the `derive` feature on this crate. Manual implementation may
/// lead to the projected attributes going out of sync with the
/// entity's attributes.
///
/// ## Example
///
/// ```
/// use modyne::EntityDef;
///
/// #[derive(EntityDef)]
/// #[serde(rename = "orange", rename_all = "kebab-case")]
/// struct MyStruct {
///     field_1: u32,
///     #[serde(rename = "second-field")]
///     field_2: u32,
/// }
/// ```
///
/// The above is equivalent to the following manual definition:
///
/// ```
/// use modyne::{EntityDef, EntityTypeNameRef};
///
/// struct MyStruct {
///     field_1: u32,
///     field_2: u32,
/// }
///
/// impl EntityDef for MyStruct {
///     const ENTITY_TYPE: &'static EntityTypeNameRef =
///         EntityTypeNameRef::from_static("orange");
///
///     const PROJECTED_ATTRIBUTES: &'static [&'static str] = &[
///         "field_1",
///         "second-field",
///     ];
/// }
/// ```
///
/// If a field is marked with serde's `flatten` modifier, then the projected
/// attributes array will be empty due to the inability of the derive macro
/// to inspect the fields that are available on the flattened type.
pub trait EntityDef {
    /// The name of the entity type
    ///
    /// This value will be used to set the `entity_type` attribute on
    /// all items of this entity type in the DynamoDB table and should
    /// be unique across all entity types in the table.
    const ENTITY_TYPE: &'static EntityTypeNameRef;

    /// The set of attributes that are projected into the entity
    ///
    /// By default, all attributes, including the index keys, are
    /// projected into the entity. This can be overridden to only
    /// project the subset of attributes that are needed for the
    /// entity's use cases.
    ///
    /// Use of this attribute is optional, but recommended. If not
    /// specified, then any aggregate that uses this entity type will
    /// return the entire item from DynamoDB, which can lead to
    /// unnecessary network and deserialization overhead.
    const PROJECTED_ATTRIBUTES: &'static [&'static str] = &[];
}

/// An entity in a DynamoDB table
///
/// This trait is used to define the structure of an entity type in a
/// DynamoDB table and how the entity may be queried.
///
/// Projections of the entity can be defined using the [`Projection`] trait.
///
/// # Example
///
/// Here we define a simple order entity type. To support write patterns, the
/// order's primary key only requires the order's ID. However, to support an
/// access pattern where we want to query all orders for a given user, we
/// define a global secondary index with a partition key of `USER#<user_id>`
/// and a sort key that includes the order's date, which allows us to more
/// efficiently query for recent orders for a given user.
///
/// ```
/// use modyne::{keys, Entity, EntityDef};
/// # use time::format_description::well_known::Rfc3339;
/// #
/// # struct App;
/// # impl modyne::Table for App {
/// #     type PrimaryKey = keys::Primary;
/// #     type IndexKeys = keys::Gsi1;
/// #     fn table_name(&self) -> &str { unimplemented!() }
/// #     fn client(&self) -> &aws_sdk_dynamodb::Client { unimplemented!() }
/// # }
///
/// #[derive(Debug, EntityDef, serde::Serialize, serde::Deserialize)]
/// struct Order {
///     user_id: String,
///     order_id: String,
///     #[serde(with = "time::serde::rfc3339")]
///     order_date: time::OffsetDateTime,
///     items: Vec<OrderItem>,
/// }
///
/// #[derive(Debug, serde::Serialize, serde::Deserialize)]
/// struct OrderItem {
///     item_id: String,
///     quantity: u32,
/// }
///
/// struct OrderKeyInput<'a> {
///     order_id: &'a str,
/// }
///
/// impl Entity for Order {
///     type KeyInput<'a> = OrderKeyInput<'a>;
///     type Table = App;
///     type IndexKeys = keys::Gsi1;
///
///     fn primary_key(input: Self::KeyInput<'_>) -> keys::Primary {
///         keys::Primary {
///             hash: format!("ORDER#{}", input.order_id),
///             range: format!("ORDER#{}", input.order_id),
///         }
///     }
///
///     fn full_key(&self) -> keys::FullKey<keys::Primary, Self::IndexKeys> {
///         let order_date = self.order_date.format(&Rfc3339).unwrap();
///         keys::FullKey {
///             primary: Self::primary_key(OrderKeyInput { order_id: &self.order_id }),
///             indexes: keys::Gsi1 {
///                  hash: format!("USER#{}", self.user_id),
///                  range: format!("ORDER#{}", order_date),
///             },
///         }
///     }
/// }
/// ```
pub trait Entity: EntityDef + Sized {
    /// The inputs required to generate the entity's primary key.
    ///
    /// This can be a single type or a tuple of types. Note that all
    /// the values required to generate the primary key must also be
    /// attributes of the entity itself.
    ///
    /// These input should be chosen to support write patterns for the
    /// entity, preferrably so that the primary key can be generated
    /// without having to read the entity from the database using a
    /// secondary index.
    ///
    /// # Example
    ///
    /// Using a structured type as the input for the primary key:
    ///
    /// ```
    /// struct MyInputs<'a> {
    ///     item_id: &'a str,
    ///     order_date: time::OffsetDateTime,
    /// }
    ///
    /// type KeyInput<'a> = MyInputs<'a>;
    /// ```
    ///
    /// Using a tuple as the input for the primary key:
    ///
    /// ```
    /// type KeyInput<'a> = (&'a str, time::OffsetDateTime);
    /// ```
    type KeyInput<'a>;

    /// The primary key for the entity
    ///
    /// Often this should be [`keys::Primary`] unless using a different
    /// primary key type.
    type Table: Table;

    /// The set of keys used to index the entity
    ///
    /// Multiple keys can be specified to support multiple indexes. Many types
    /// of index keys have already been defined in the [`keys`] module.
    ///
    /// # Example
    ///
    /// Using a single index key:
    ///
    /// ```
    /// # use modyne::keys;
    /// type IndexKeys = keys::Gsi1;
    /// ```
    ///
    /// Specifying a two global secondary indexes:
    ///
    /// ```
    /// # use modyne::keys;
    /// type IndexKeys = (keys::Gsi1, keys::Gsi2);
    /// ```
    type IndexKeys: keys::IndexKeys;

    /// Generate the primary key for an entity
    ///
    /// This is primarily used when retrieving, updating, or deleting a
    /// specific entity.
    fn primary_key(input: Self::KeyInput<'_>) -> <Self::Table as Table>::PrimaryKey;

    /// Generate the full set of keys for an entity
    ///
    /// This is primarily used when upserting an entity into the database.
    fn full_key(&self) -> keys::FullKey<<Self::Table as Table>::PrimaryKey, Self::IndexKeys>;
}

/// Extension trait for [`Entity`] types
pub trait EntityExt: Entity {
    /// The definition for the entity's primary key
    const KEY_DEFINITION: keys::PrimaryKeyDefinition =
        <<Self::Table as Table>::PrimaryKey as keys::PrimaryKey>::PRIMARY_KEY_DEFINITION;

    /// Convert the entity into a DynamoDB item
    ///
    /// The generated item will include all of the entity's attributes, as well
    /// as the entity type and all index key attributes.
    fn into_item(self) -> Item
    where
        Self: serde::Serialize,
    {
        let full_entity = FullEntity {
            keys: self.full_key(),
            entity: self,
        };

        let mut item = crate::codec::to_item(full_entity).unwrap();
        if item
            .insert(
                <Self::Table as Table>::ENTITY_TYPE_ATTRIBUTE.to_string(),
                <Self::Table as Table>::serialize_entity_type(Self::ENTITY_TYPE),
            )
            .is_some()
        {
            tracing::warn!(
                "serialized entity had attribute collision with entity type attribute `{}`",
                <Self::Table as Table>::ENTITY_TYPE_ATTRIBUTE,
            );
        }
        item
    }

    /// Prepares a get operation for the entity
    #[inline]
    fn get(input: Self::KeyInput<'_>) -> Get {
        Get::new(Self::primary_key(input).into_key())
    }

    /// Prepares a put operation for the entity
    #[inline]
    fn put(self) -> Put
    where
        Self: serde::Serialize,
    {
        Put::new(self.into_item())
    }

    /// Prepares a put operation for the entity that requires that
    /// no entity already exist with the same key
    #[inline]
    fn create(self) -> ConditionalPut
    where
        Self: serde::Serialize,
    {
        let condition = expr::Condition::new("attribute_not_exists(#PK)").name(
            "#PK",
            <<Self::Table as Table>::PrimaryKey as keys::PrimaryKey>::PRIMARY_KEY_DEFINITION
                .hash_key,
        );
        self.put().condition(condition)
    }

    /// Prepares a put operation for the entity that requires that
    /// an entity already exist with the same key
    #[inline]
    fn replace(self) -> ConditionalPut
    where
        Self: serde::Serialize,
    {
        let condition = expr::Condition::new("attribute_exists(#PK)").name(
            "#PK",
            <<Self::Table as Table>::PrimaryKey as keys::PrimaryKey>::PRIMARY_KEY_DEFINITION
                .hash_key,
        );
        self.put().condition(condition)
    }

    /// Prepares an update operation for the entity
    ///
    /// # Note
    ///
    /// If this update would change an attribute that is used in the creation of a key attribute,
    /// that key attribute must also be explicitly updated. In cases where the entire state of the
    /// entity is known, using a [`replace()`][EntityExt::replace()] may be better, as that will
    /// also update any computed key attributes.
    #[inline]
    fn update(key: Self::KeyInput<'_>) -> Update {
        Update::new(Self::primary_key(key).into_key())
    }

    /// Prepares a delete operation for the entity
    #[inline]
    fn delete(key: Self::KeyInput<'_>) -> Delete {
        Delete::new(Self::primary_key(key).into_key())
    }

    /// Prepares a condition check operation for the entity, for transactional writes
    #[inline]
    fn condition_check(key: Self::KeyInput<'_>, condition: expr::Condition) -> ConditionCheck {
        ConditionCheck::new(Self::primary_key(key).into_key(), condition)
    }
}

impl<T: Entity> EntityExt for T {}

/// A projection of an entity that may not contain all of the entity's attributes
///
/// This trait can be used when querying a subset of an entity's attributes. In this way
/// time won't be spent deserializing attributes that aren't needed.
///
/// Note that this type does not automatically impose a projection expression on the DynamoDB
/// operation, so network bandwidth will still be spent retrieving the full entity unless the
/// projected attributes are specified.
///
/// In addition, even if a projection expression is specified, the full size of an item will
/// still be counted when computing the DynamoDB read capacity unit consumption.
///
/// For easier implementation, use the [`derive@Projection`] derive macro to infer the projected
/// attributes automatically.
pub trait Projection: Sized {
    /// The set of attributes that are projected into the entity.
    ///
    /// By default, the set of projected attributes defined on the entity
    /// will be projected.
    ///
    /// Use of this attribute is optional, but recommended. If not
    /// specified here or on the entity, then any aggregate that uses
    /// this projection will return the entire item from DynamoDB, which
    /// can lead to unnecessary network and deserialization overhead.
    const PROJECTED_ATTRIBUTES: &'static [&'static str] =
        <Self::Entity as EntityDef>::PROJECTED_ATTRIBUTES;

    /// The entity type that this projection represents
    type Entity: Entity;
}

impl<T> Projection for T
where
    T: Entity,
{
    type Entity = Self;
}

/// Extension trait for [`Projection`] types
pub trait ProjectionExt: Projection {
    /// Deserialize a DynamoDB item into this projection
    fn from_item(item: Item) -> Result<Self, Error>;
}

impl<'a, P> ProjectionExt for P
where
    P: Projection + serde::Deserialize<'a>,
{
    fn from_item(item: Item) -> Result<Self, Error> {
        let parsed = crate::codec::from_item(item).map_err(|error| {
            crate::error::ItemDeserializationError::new(Self::Entity::ENTITY_TYPE, error)
        })?;

        Ok(parsed)
    }
}

/// A description of the set of entity types that constitute an [`Aggregate`]
///
/// This trait is not generally implemented directly, but rather is generated
/// by using the [`projections!`] macro.
pub trait ProjectionSet: Sized {
    /// Attempt to parse an known entity from a DynamoDB item
    ///
    /// On an unknown entity type, this method should return `Ok(None)`.
    ///
    /// # Errors
    ///
    /// This method will return an error if the item cannot be parsed
    /// based on the entity type that is present in the item or if the
    /// entity type attribute is missing from the item.
    fn try_from_item(item: Item) -> Result<Option<Self>, Error>;

    /// Generate a projection expression for the aggregate
    ///
    /// This expression will include all of the attributes that are
    /// projected by any of the entity types in the aggregate.
    fn projection_expression() -> Option<expr::StaticProjection>;
}

/// Utility macro for defining an [`ProjectionSet`] used when querying items
/// into an [`Aggregate`]
///
/// See the [module-level documentation][crate] for more details.
#[macro_export]
macro_rules! projections {
    ($(#[$meta:meta])* $v:vis enum $name:ident { $ty:ident }) => {
        $crate::projections!{
            ($(#[$meta])* $v:vis enum $name { $ty, })
        }
    };
    ($(#[$meta:meta])* $v:vis enum $name:ident { $ty:ident, $($tys:ident),* $(,)? }) => {
        $(#[$meta])*
        $v enum $name {
            $ty($ty),
            $($tys($tys),)*
        }

        impl $crate::ProjectionSet for $name {
            fn try_from_item(item: $crate::Item) -> ::std::result::Result<::std::option::Option<Self>, $crate::Error> {
                let entity_type = $crate::__private::get_entity_type::<$ty>(&item)?;

                let parsed =
                if entity_type == <<$ty as $crate::Projection>::Entity as $crate::EntityDef>::ENTITY_TYPE {
                    let parsed = <$ty as $crate::ProjectionExt>::from_item(item)
                        .map(Self::$ty)?;
                    ::std::option::Option::Some(parsed)
                } else
                $(
                    if entity_type == <<$tys as $crate::Projection>::Entity as $crate::EntityDef>::ENTITY_TYPE {
                        let parsed = <$tys as $crate::ProjectionExt>::from_item(item)
                            .map(Self::$tys)?;
                        ::std::option::Option::Some(parsed)
                    } else
                )*
                {
                    tracing::warn!(entity_type = entity_type.as_str(), "unknown entity type");
                    ::std::option::Option::None
                };

                ::std::result::Result::Ok(parsed)
            }

            fn projection_expression() -> ::std::option::Option<$crate::expr::StaticProjection> {
                $crate::once_projection_expression!($ty,$($tys),*)
            }
        }

        // Verifies that the Table types are all equal via the `once_projection_expression!` macro
    };
}

/// Generate a static projection expression that is computed exactly once in the lifetime
/// of the program
///
/// This may be used when overriding the implementations for the projection expression
/// in [`ScanInput`][ScanInput::projection_expression()] if desired.
///
/// # Example
///
/// ```
/// # struct Database;
/// # impl modyne::Table for Database {
/// #     type PrimaryKey = modyne::keys::Primary;
/// #     type IndexKeys = modyne::keys::Gsi1;
/// #     fn table_name(&self) -> &str {unimplemented!()}
/// #     fn client(&self) -> &aws_sdk_dynamodb::Client {unimplemented!()}
/// # }
/// #
/// # struct User {}
/// # impl modyne::EntityDef for User {
/// #     const ENTITY_TYPE: &'static modyne::EntityTypeNameRef = modyne::EntityTypeNameRef::from_static("user");
/// #     const PROJECTED_ATTRIBUTES: &'static [&'static str] = &["user_id"];
/// # }
/// # impl modyne::Entity for User {
/// #     type KeyInput<'a> = &'a str;
/// #     type Table = Database;
/// #     type IndexKeys = modyne::keys::Gsi1;
/// #     fn primary_key(input: Self::KeyInput<'_>) -> modyne::keys::Primary {unimplemented!()}
/// #     fn full_key(&self) -> modyne::keys::FullKey<modyne::keys::Primary, Self::IndexKeys> {unimplemented!()}
/// # }
/// use modyne::{expr, keys, once_projection_expression, ScanInput};
/// struct UserIndexScan;
///
/// impl ScanInput for UserIndexScan {
///     type Index = keys::Gsi1;
///
///     fn projection_expression() -> Option<expr::StaticProjection> {
///         once_projection_expression!(User)
///     }
/// }
/// ```
#[macro_export]
macro_rules! once_projection_expression {
    ($ty:path) => { $crate::once_projection_expression!($ty,) };
    ($ty:path, $($tys:path),* $(,)?) => {{
        $crate::ensure_table_types_are_same!($ty, $($tys),*);

        const PROJECTIONS: &'static [&'static [&'static str]] = &[
            <$ty as $crate::Projection>::PROJECTED_ATTRIBUTES,
            $(
                <$tys as $crate::Projection>::PROJECTED_ATTRIBUTES,
            )*
        ];

        static PROJECTION_ONCE: $crate::__private::OnceLock<
            ::std::option::Option<$crate::expr::StaticProjection>,
        > = $crate::__private::OnceLock::new();

        *PROJECTION_ONCE.get_or_init(|| {
            $crate::__private::generate_projection_expression::<<<$ty as $crate::Projection>::Entity as $crate::Entity>::Table>(
                PROJECTIONS,
            )
        })
    }};
}

/// Utility macro for reading an entity from a DynamoDB item
///
/// The projection set is inferred from the context in which this macro is used.
/// If an projection type is not present in the projection set, then the macro will
/// short-circuit to skip the item.
///
/// This macro is generally used in the implementation of [`Aggregate::merge`],
/// to ergonomically parse an entity from a DynamoDB item. Use outside of this
/// context is unlikely to compile.
#[macro_export]
macro_rules! read_projection {
    ($item:expr) => {{
        match <Self::Projections as $crate::ProjectionSet>::try_from_item($item) {
            Ok(Some(entity)) => Ok(entity),
            Ok(None) => return Ok(()),
            Err(error) => Err(error),
        }
    }};
}

/// Ensures that the table types will match for all variants in a projection set
#[macro_export]
#[doc(hidden)]
macro_rules! ensure_table_types_are_same {
    ($ty:path) => {};
    ($ty:path, $($tys:path),* $(,)?) => {
        const _: fn() = || { $({
            trait TypeEq {
                type This: ?Sized;
            }

            impl<T: ?Sized> TypeEq for T {
                type This = Self;
            }

            fn assert_table_types_match_for_all_projection_variants<T, U>()
            where
                T: ?Sized + TypeEq<This = U>,
                U: ?Sized,
            {}

            assert_table_types_match_for_all_projection_variants::<
                <<$ty as $crate::Projection>::Entity as $crate::Entity>::Table,
                <<$tys as $crate::Projection>::Entity as $crate::Entity>::Table,
            >();
        })* };
    };
}

/// An aggregate of multiple entity types, often used when querying multiple
/// items from a single partition key.
pub trait Aggregate: Default {
    /// The set of entity types that are expected to be returned from the aggregate
    ///
    /// This type is usually generated using the [`projections!`] macro.
    type Projections: ProjectionSet;

    /// Extends the aggregate with the entities represented by the given items
    fn reduce<I>(&mut self, items: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = Item>,
    {
        for item in items {
            self.merge(item)?;
        }

        Ok(())
    }

    /// Merges the entity represented by the given item into the aggregate
    ///
    /// When implementing this method, it is recommended to use the [`read_projection!`]
    /// macro, which will deserialize the item into the correct entity type,
    /// ignoring any unknown entity types.
    fn merge(&mut self, item: Item) -> Result<(), Error>;
}

impl<'a, P> ProjectionSet for P
where
    P: Projection + serde::Deserialize<'a> + 'static,
{
    fn try_from_item(item: Item) -> Result<Option<Self>, Error> {
        let entity_type = crate::__private::get_entity_type::<Self>(&item)?;
        if entity_type == <P::Entity as EntityDef>::ENTITY_TYPE {
            let parsed = P::from_item(item)?;
            Ok(Some(parsed))
        } else {
            tracing::warn!(entity_type = entity_type.as_str(), "unknown entity type");
            Ok(None)
        }
    }

    fn projection_expression() -> Option<expr::StaticProjection> {
        use std::{any::TypeId, collections::BTreeMap, sync::RwLock};

        static ENTITY_PROJECTION_EXPRESSION: RwLock<
            BTreeMap<TypeId, Option<expr::StaticProjection>>,
        > = RwLock::new(BTreeMap::new());

        // Optimistically take a read lock to see if we've already computed the projection
        {
            let projections = ENTITY_PROJECTION_EXPRESSION.read().unwrap();
            if let Some(&projection) = projections.get(&TypeId::of::<P>()) {
                return projection;
            }
        }

        // If we didn't find the projection, take a write lock and compute it
        let mut projections = ENTITY_PROJECTION_EXPRESSION.write().unwrap();
        *projections.entry(TypeId::of::<P>()).or_insert_with(|| {
            // If the entity type doesn't have any projected attributes, then we can't
            // generate a projection expression. This then means that _all_ attributes
            // will be returned.
            if !P::PROJECTED_ATTRIBUTES.iter().all(|a| !a.is_empty()) {
                return None;
            }

            let projection =
                expr::Projection::new(P::PROJECTED_ATTRIBUTES.iter().copied().chain([
                    <<P::Entity as crate::Entity>::Table as crate::Table>::ENTITY_TYPE_ATTRIBUTE,
                ]));

            // Leak the generated projection expression. This is safe since we're the
            // only ones with a lock that allows generating an expression. Thus no unnecessary
            // expressions will be generated (only one expression per projection; no
            // unbounded leaks). This expression will then be reused for the rest of the
            // process lifetime.
            Some(projection.leak())
        })
    }
}

impl<'a, P> Aggregate for Vec<P>
where
    P: Projection + serde::Deserialize<'a> + 'static,
{
    type Projections = P;

    fn reduce<I>(&mut self, items: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = Item>,
    {
        let items = items.into_iter();
        self.reserve(items.size_hint().0);
        for item in items {
            self.merge(item)?;
        }

        Ok(())
    }

    fn merge(&mut self, item: Item) -> Result<(), Error> {
        let entity = read_projection!(item)?;
        self.push(entity);
        Ok(())
    }
}

/// A value that can be used to query an aggregate
pub trait QueryInput {
    /// Whether to use consistent reads for the query
    const CONSISTENT_READ: bool = false;

    /// Whether to scan the index forward
    const SCAN_INDEX_FORWARD: bool = true;

    /// The index used to query the aggregate
    type Index: keys::Key;

    /// The aggregate that this query is for
    type Aggregate: Aggregate;

    /// The key condition to apply on this query
    fn key_condition(&self) -> expr::KeyCondition<Self::Index>;

    /// Specify which items should be returned by the query
    ///
    /// This is a filter expression that is applied to items after reading but
    /// before returning. Items scanned but not returned by the filter
    /// expression will still be counted towards any limit and read
    /// capacity quotas.
    ///
    /// Where possible, it is preferrable to rely on the key condition to
    /// filter the set of items returned, as that will be more efficient.
    #[inline]
    fn filter_expression(&self) -> Option<expr::Filter> {
        None
    }
}

/// Extensions to an aggregate query
pub trait QueryInputExt: QueryInput {
    /// Prepare a DynamoDB query
    ///
    /// This will prepare a query operation for the input, applying
    /// the key condition, filter expression, read consistency,
    /// and scan direction as defined by the input. Additional settings can
    /// be applied by chaining methods on the returned [`Query`] value.
    fn query(&self) -> Query<Self::Index>;
}

impl<Q> QueryInputExt for Q
where
    Q: QueryInput + ?Sized,
{
    fn query(&self) -> Query<Self::Index> {
        let mut query = Query::new(self.key_condition());

        if let Some(projection) =
            <<Self as QueryInput>::Aggregate as Aggregate>::Projections::projection_expression()
        {
            query = query.projection(projection);
        }

        if let Some(filter) = self.filter_expression() {
            query = query.filter(filter);
        }

        if Self::CONSISTENT_READ {
            query = query.consistent_read();
        }

        if !Self::SCAN_INDEX_FORWARD {
            query = query.scan_index_backward();
        }

        query
    }
}

/// A value that can be used to query an aggregate
pub trait ScanInput {
    /// Whether to use consistent reads for the scan
    const CONSISTENT_READ: bool = false;

    /// The index to be scanned
    type Index: keys::Key;

    /// Specify which items should be returned by the scan
    ///
    /// This is a filter expression that is applied to items after reading but
    /// before returning. Items scanned but not returned by the filter
    /// expression will still be counted towards any limit and read
    /// capacity quotas.
    #[inline]
    fn filter_expression(&self) -> Option<expr::Filter> {
        None
    }

    /// Specify which attributes should be returned by the scan
    ///
    /// This is a projection expression that is applied to items being
    /// returned. The full size of an item is counted toward read
    /// capacity usage, regardless of which attributes are returned.
    ///
    /// The [`once_projection_expression!`] macro can be used to automatically
    /// generate a projection expression from a known set of entities that
    /// the scan will return.
    #[inline]
    fn projection_expression() -> Option<expr::StaticProjection> {
        None
    }
}

/// Extensions to an aggregate scan
pub trait ScanInputExt: ScanInput {
    /// Prepare a DynamoDB scan
    ///
    /// This will prepare a scan operation for the input, applying
    /// filter expression and consistent read settings as defined by the input.
    /// Additional settings can be applied by chaining methods
    /// on the returned [`Scan`] value.
    fn scan(&self) -> Scan<Self::Index>;
}

impl<S> ScanInputExt for S
where
    S: ScanInput + ?Sized,
{
    fn scan(&self) -> Scan<Self::Index> {
        let mut scan = Scan::new();

        if let Some(filter) = self.filter_expression() {
            scan = scan.filter(filter);
        }

        if let Some(projection) = Self::projection_expression() {
            scan = scan.projection(projection)
        }

        if Self::CONSISTENT_READ {
            scan = scan.consistent_read();
        }

        scan
    }
}

#[derive(serde::Serialize)]
struct FullEntity<T: Entity> {
    #[serde(flatten)]
    keys: keys::FullKey<<T::Table as Table>::PrimaryKey, T::IndexKeys>,

    #[serde(flatten)]
    entity: T,
}

#[doc(hidden)]
pub mod __private {
    #[cfg(not(feature = "once_cell"))]
    pub type OnceLock<T> = std::sync::OnceLock<T>;

    #[cfg(feature = "once_cell")]
    pub type OnceLock<T> = once_cell::sync::OnceCell<T>;

    pub fn get_entity_type<P: crate::Projection>(
        item: &crate::Item,
    ) -> Result<&crate::EntityTypeNameRef, crate::Error> {
        let entity_type_attr = item
            .get(<<P::Entity as crate::Entity>::Table as crate::Table>::ENTITY_TYPE_ATTRIBUTE)
            .ok_or(crate::error::MissingEntityTypeError {})?;
        let entity_type =
            <<P::Entity as crate::Entity>::Table as crate::Table>::deserialize_entity_type(
                entity_type_attr,
            )?;
        Ok(entity_type)
    }

    /// Generate a projection expression for the given entity types
    pub fn generate_projection_expression<T: crate::Table>(
        attributes: &[&[&str]],
    ) -> Option<crate::expr::StaticProjection> {
        if !attributes.iter().all(|attrs| !attrs.is_empty()) {
            return None;
        }

        let expr = crate::expr::Projection::new(
            attributes
                .iter()
                .copied()
                .flatten()
                .copied()
                .chain([T::ENTITY_TYPE_ATTRIBUTE]),
        );
        Some(expr.leak())
    }
}

/// Extension trait for [`Table`] to provide convenience methods for testing operations
///
/// The methods within this trait are not recommended for use outside of testing contexts.
/// They are not intended for use in creating or managing production deployments, and
/// do not provide configurability generally required by those tools.
pub trait TestTableExt {
    /// Prepare a create table operation
    ///
    /// Table will be created with the primary key and index keys specified in _pay per request_
    /// mode.
    fn create_table(
        &self,
    ) -> aws_sdk_dynamodb::operation::create_table::builders::CreateTableFluentBuilder;

    /// Prepare a delete table operation
    fn delete_table(
        &self,
    ) -> aws_sdk_dynamodb::operation::delete_table::builders::DeleteTableFluentBuilder;
}

impl<T> TestTableExt for T
where
    T: Table,
{
    fn create_table(
        &self,
    ) -> aws_sdk_dynamodb::operation::create_table::builders::CreateTableFluentBuilder {
        let definitions: std::collections::BTreeSet<_> =
            <<Self as Table>::IndexKeys as keys::IndexKeys>::KEY_DEFINITIONS
                .iter()
                .copied()
                .collect();

        let mut builder = self
            .client()
            .create_table()
            .set_table_name(Some(self.table_name().into()));

        for definition in definitions {
            let hash = aws_sdk_dynamodb::types::AttributeDefinition::builder()
                .set_attribute_name(Some(definition.hash_key().into()))
                .set_attribute_type(Some(aws_sdk_dynamodb::types::ScalarAttributeType::S))
                .build()
                .expect("attribute name and attribute type are always provided");
            let mut key_schema = vec![aws_sdk_dynamodb::types::KeySchemaElement::builder()
                .set_attribute_name(Some(definition.hash_key().into()))
                .set_key_type(Some(aws_sdk_dynamodb::types::KeyType::Hash))
                .build()
                .expect("attribute name and key type are always provided")];
            builder = builder.attribute_definitions(hash);
            if let Some(range_key) = definition.range_key() {
                let range = aws_sdk_dynamodb::types::AttributeDefinition::builder()
                    .set_attribute_name(Some(range_key.into()))
                    .set_attribute_type(Some(aws_sdk_dynamodb::types::ScalarAttributeType::S))
                    .build()
                    .expect("attribute name and attribute type are always provided");
                key_schema.push(
                    aws_sdk_dynamodb::types::KeySchemaElement::builder()
                        .set_attribute_name(Some(range_key.into()))
                        .set_key_type(Some(aws_sdk_dynamodb::types::KeyType::Range))
                        .build()
                        .expect("attribute name and key type are always provided"),
                );
                builder = builder.attribute_definitions(range)
            }
            let gsi = aws_sdk_dynamodb::types::GlobalSecondaryIndex::builder()
                .set_index_name(Some(definition.index_name().into()))
                .set_projection(Some(
                    aws_sdk_dynamodb::types::Projection::builder()
                        .set_projection_type(Some(aws_sdk_dynamodb::types::ProjectionType::All))
                        .build(),
                ))
                .set_key_schema(Some(key_schema))
                .build()
                .expect("index name and key schema are always provided");
            builder = builder.global_secondary_indexes(gsi);
        }

        let primary_key_definition =
            <<Self as Table>::PrimaryKey as keys::PrimaryKey>::PRIMARY_KEY_DEFINITION;
        let hash = aws_sdk_dynamodb::types::AttributeDefinition::builder()
            .set_attribute_name(Some(primary_key_definition.hash_key.into()))
            .set_attribute_type(Some(aws_sdk_dynamodb::types::ScalarAttributeType::S))
            .build()
            .expect("attribute name and attribute type are always provided");
        let mut key_schema = vec![aws_sdk_dynamodb::types::KeySchemaElement::builder()
            .set_attribute_name(Some(primary_key_definition.hash_key.into()))
            .set_key_type(Some(aws_sdk_dynamodb::types::KeyType::Hash))
            .build()
            .expect("attribute name and key type are always provided")];
        builder = builder.attribute_definitions(hash);
        if let Some(range_key) = primary_key_definition.range_key {
            let range = aws_sdk_dynamodb::types::AttributeDefinition::builder()
                .set_attribute_name(Some(range_key.into()))
                .set_attribute_type(Some(aws_sdk_dynamodb::types::ScalarAttributeType::S))
                .build()
                .expect("attribute name and attribute type are always provided");
            key_schema.push(
                aws_sdk_dynamodb::types::KeySchemaElement::builder()
                    .set_attribute_name(Some(range_key.into()))
                    .set_key_type(Some(aws_sdk_dynamodb::types::KeyType::Range))
                    .build()
                    .expect("attribute name and key type are always provided"),
            );
            builder = builder.attribute_definitions(range)
        }

        builder
            .set_key_schema(Some(key_schema))
            .billing_mode(aws_sdk_dynamodb::types::BillingMode::PayPerRequest)
    }

    fn delete_table(
        &self,
    ) -> aws_sdk_dynamodb::operation::delete_table::builders::DeleteTableFluentBuilder {
        self.client()
            .delete_table()
            .set_table_name(Some(self.table_name().into()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod standard {
        use super::*;

        struct TestTable;
        impl Table for TestTable {
            type PrimaryKey = keys::Primary;
            type IndexKeys = keys::Gsi13;

            fn client(&self) -> &aws_sdk_dynamodb::Client {
                unimplemented!()
            }

            fn table_name(&self) -> &str {
                unimplemented!()
            }
        }

        #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct TestEntity {
            id: String,
            name: String,
            email: String,
        }

        impl EntityDef for TestEntity {
            const ENTITY_TYPE: &'static EntityTypeNameRef =
                EntityTypeNameRef::from_static("test_ent");
        }

        impl Entity for TestEntity {
            type KeyInput<'a> = (&'a str, &'a str);
            type Table = TestTable;
            type IndexKeys = keys::Gsi13;

            fn primary_key((id, email): Self::KeyInput<'_>) -> keys::Primary {
                keys::Primary {
                    hash: format!("PK#{id}"),
                    range: format!("NAME#{email}"),
                }
            }

            fn full_key(&self) -> keys::FullKey<keys::Primary, Self::IndexKeys> {
                keys::FullKey {
                    primary: Self::primary_key((&self.id, &self.email)),
                    indexes: keys::Gsi13 {
                        hash: format!("GSI13#{}", self.id),
                        range: format!("GSI13#NAME#{}", self.name),
                    },
                }
            }
        }

        #[test]
        fn test_entity_serializes_as_expected() {
            let entity = TestEntity {
                id: "test1".to_string(),
                name: "Test".to_string(),
                email: "my_email@not_real.com".to_string(),
            };

            let item = entity.into_item();
            assert_eq!(item.len(), 8);
            assert_eq!(item["entity_type"].as_s().unwrap(), "test_ent");
            assert_eq!(item["PK"].as_s().unwrap(), "PK#test1");
            assert_eq!(item["SK"].as_s().unwrap(), "NAME#my_email@not_real.com");
            assert_eq!(item["GSI13PK"].as_s().unwrap(), "GSI13#test1");
            assert_eq!(item["GSI13SK"].as_s().unwrap(), "GSI13#NAME#Test");
            assert_eq!(item["id"].as_s().unwrap(), "test1");
            assert_eq!(item["name"].as_s().unwrap(), "Test");
            assert_eq!(item["email"].as_s().unwrap(), "my_email@not_real.com");
        }

        #[test]
        fn test_entity_deserializes_as_expected() {
            let entity = TestEntity {
                id: "test1".to_string(),
                name: "Test".to_string(),
                email: "my_email@not_real.com".to_string(),
            };

            let item = entity.clone().into_item();
            let entity_type = TestTable::deserialize_entity_type(&item["entity_type"])
                .unwrap()
                .to_owned();
            let clone = TestEntity::from_item(item).unwrap();

            assert_eq!(entity, clone);
            assert_eq!(entity_type, TestEntity::ENTITY_TYPE);
        }
    }

    mod as_string_set {
        use super::*;

        struct TestTable;
        impl Table for TestTable {
            type PrimaryKey = keys::Primary;
            type IndexKeys = keys::Gsi13;

            fn client(&self) -> &aws_sdk_dynamodb::Client {
                unimplemented!()
            }

            fn table_name(&self) -> &str {
                unimplemented!()
            }

            fn deserialize_entity_type(
                attr: &AttributeValue,
            ) -> Result<&EntityTypeNameRef, MalformedEntityTypeError> {
                let values = attr.as_ss().map_err(|_| {
                    MalformedEntityTypeError::Custom("expected a string set".into())
                })?;
                let value = values
                    .first()
                    .expect("a DynamoDB string set always has at least one element");
                Ok(EntityTypeNameRef::from_str(value.as_str()))
            }

            fn serialize_entity_type(entity_type: &EntityTypeNameRef) -> AttributeValue {
                AttributeValue::Ss(vec![entity_type.to_string()])
            }
        }

        #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct TestEntity {
            id: String,
            name: String,
            email: String,
        }

        impl EntityDef for TestEntity {
            const ENTITY_TYPE: &'static EntityTypeNameRef =
                EntityTypeNameRef::from_static("test_ent");
        }

        impl Entity for TestEntity {
            type KeyInput<'a> = (&'a str, &'a str);
            type Table = TestTable;
            type IndexKeys = keys::Gsi13;

            fn primary_key((id, email): Self::KeyInput<'_>) -> keys::Primary {
                keys::Primary {
                    hash: format!("PK#{id}"),
                    range: format!("NAME#{email}"),
                }
            }

            fn full_key(&self) -> keys::FullKey<keys::Primary, Self::IndexKeys> {
                keys::FullKey {
                    primary: Self::primary_key((&self.id, &self.email)),
                    indexes: keys::Gsi13 {
                        hash: format!("GSI13#{}", self.id),
                        range: format!("GSI13#NAME#{}", self.name),
                    },
                }
            }
        }

        #[test]
        fn test_entity_serializes_as_expected() {
            let entity = TestEntity {
                id: "test1".to_string(),
                name: "Test".to_string(),
                email: "my_email@not_real.com".to_string(),
            };

            let item = entity.into_item();
            assert_eq!(item.len(), 8);
            assert_eq!(
                item["entity_type"].as_ss().unwrap(),
                &["test_ent".to_owned()]
            );
            assert_eq!(item["PK"].as_s().unwrap(), "PK#test1");
            assert_eq!(item["SK"].as_s().unwrap(), "NAME#my_email@not_real.com");
            assert_eq!(item["GSI13PK"].as_s().unwrap(), "GSI13#test1");
            assert_eq!(item["GSI13SK"].as_s().unwrap(), "GSI13#NAME#Test");
            assert_eq!(item["id"].as_s().unwrap(), "test1");
            assert_eq!(item["name"].as_s().unwrap(), "Test");
            assert_eq!(item["email"].as_s().unwrap(), "my_email@not_real.com");
        }

        #[test]
        fn test_entity_deserializes_as_expected() {
            let entity = TestEntity {
                id: "test1".to_string(),
                name: "Test".to_string(),
                email: "my_email@not_real.com".to_string(),
            };

            let item = entity.clone().into_item();
            let entity_type = TestTable::deserialize_entity_type(&item["entity_type"])
                .unwrap()
                .to_owned();
            let clone = TestEntity::from_item(item).unwrap();

            assert_eq!(entity, clone);
            assert_eq!(entity_type, TestEntity::ENTITY_TYPE);
        }
    }

    mod alternate_attribute {
        use super::*;

        struct TestTable;
        impl Table for TestTable {
            const ENTITY_TYPE_ATTRIBUTE: &'static str = "et";

            type PrimaryKey = keys::Primary;
            type IndexKeys = keys::Gsi13;

            fn client(&self) -> &aws_sdk_dynamodb::Client {
                unimplemented!()
            }

            fn table_name(&self) -> &str {
                unimplemented!()
            }
        }

        #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct TestEntity {
            id: String,
            name: String,
            email: String,
        }

        impl EntityDef for TestEntity {
            const ENTITY_TYPE: &'static EntityTypeNameRef =
                EntityTypeNameRef::from_static("test_ent");
        }

        impl Entity for TestEntity {
            type KeyInput<'a> = (&'a str, &'a str);
            type Table = TestTable;
            type IndexKeys = keys::Gsi13;

            fn primary_key((id, email): Self::KeyInput<'_>) -> keys::Primary {
                keys::Primary {
                    hash: format!("PK#{id}"),
                    range: format!("NAME#{email}"),
                }
            }

            fn full_key(&self) -> keys::FullKey<keys::Primary, Self::IndexKeys> {
                keys::FullKey {
                    primary: Self::primary_key((&self.id, &self.email)),
                    indexes: keys::Gsi13 {
                        hash: format!("GSI13#{}", self.id),
                        range: format!("GSI13#NAME#{}", self.name),
                    },
                }
            }
        }

        #[test]
        fn test_entity_serializes_as_expected() {
            let entity = TestEntity {
                id: "test1".to_string(),
                name: "Test".to_string(),
                email: "my_email@not_real.com".to_string(),
            };

            let item = entity.into_item();
            assert_eq!(item.len(), 8);
            assert_eq!(item["et"].as_s().unwrap(), "test_ent");
            assert_eq!(item["PK"].as_s().unwrap(), "PK#test1");
            assert_eq!(item["SK"].as_s().unwrap(), "NAME#my_email@not_real.com");
            assert_eq!(item["GSI13PK"].as_s().unwrap(), "GSI13#test1");
            assert_eq!(item["GSI13SK"].as_s().unwrap(), "GSI13#NAME#Test");
            assert_eq!(item["id"].as_s().unwrap(), "test1");
            assert_eq!(item["name"].as_s().unwrap(), "Test");
            assert_eq!(item["email"].as_s().unwrap(), "my_email@not_real.com");
        }

        #[test]
        fn test_entity_deserializes_as_expected() {
            let entity = TestEntity {
                id: "test1".to_string(),
                name: "Test".to_string(),
                email: "my_email@not_real.com".to_string(),
            };

            let item = entity.clone().into_item();
            let entity_type = TestTable::deserialize_entity_type(&item["et"])
                .unwrap()
                .to_owned();
            let clone = TestEntity::from_item(item).unwrap();

            assert_eq!(entity, clone);
            assert_eq!(entity_type, TestEntity::ENTITY_TYPE);
        }
    }
}