Skip to content

Implement DynamoDbFlatten annotation #3833

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions sdk/src/Services/DynamoDBv2/Custom/DataModel/Attributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,35 @@ public DynamoDBPolymorphicTypeAttribute(string typeDiscriminator,
}
}

/// <summary>
/// Indicates that the properties of the decorated field or property type should be "flattened"
/// into the top-level attributes of the DynamoDB item. When applied, all public properties
/// of the referenced type are serialized as individual top-level attributes in the DynamoDB record,
/// rather than as a nested object.
/// <para>
/// Example:
/// <code>
/// public class Address
/// {
/// public string Street { get; set; }
/// public string City { get; set; }
/// }
///
/// public class Person
/// {
/// public string Name { get; set; }
/// [DynamoDBFlatten]
/// public Address Address { get; set; }
/// }
/// </code>
/// In this example, the <c>Person</c> table will have top-level attributes for <c>Name</c>, <c>Street</c>, and <c>City</c>.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class DynamoDBFlattenAttribute : DynamoDBAttribute
{
}

/// <summary>
/// DynamoDB attribute that directs the specified attribute not to
/// be included when saving or loading objects.
Expand Down
100 changes: 71 additions & 29 deletions sdk/src/Services/DynamoDBv2/Custom/DataModel/ContextInternal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -390,29 +390,53 @@ private void PopulateInstance(ItemStorage storage, object instance, DynamoDBFlat

using (flatConfig.State.Track(document))
{
foreach (PropertyStorage propertyStorage in storageConfig.AllPropertyStorage)
foreach (PropertyStorage propertyStorage in storageConfig.Properties)
{
string propertyName = propertyStorage.PropertyName;
string attributeName = propertyStorage.AttributeName;

DynamoDBEntry entry;
if (document.TryGetValue(attributeName, out entry))
if (propertyStorage.FlattenProperty)
{
if (ShouldSave(entry, true))
//create instance of the flatten property
var targetType = propertyStorage.MemberType;
object flattenedPropertyInstance = Utils.InstantiateConverter(targetType, this);

//populate the flatten properties
foreach (var propertyStorageFlattenProperty in propertyStorage.FlattenProperties)
{
object value = FromDynamoDBEntry(propertyStorage, entry, flatConfig);
string flattenedAttributeName = propertyStorageFlattenProperty.AttributeName;

if (!TrySetValue(instance, propertyStorage.Member, value))
{
throw new InvalidOperationException("Unable to retrieve value from " + attributeName);
}
PopulateProperty(storage, flatConfig, document, flattenedAttributeName, propertyStorageFlattenProperty, flattenedPropertyInstance);
}
if (!TrySetValue(instance, propertyStorage.Member, flattenedPropertyInstance))
{
throw new InvalidOperationException("Unable to retrieve value from " + attributeName);
}

if (propertyStorage.IsVersion)
storage.CurrentVersion = entry as Primitive;
}
else
{
PopulateProperty(storage, flatConfig, document, attributeName, propertyStorage, instance);
}
}
}
}

private void PopulateProperty(ItemStorage storage, DynamoDBFlatConfig flatConfig, Document document,
string attributeName, PropertyStorage propertyStorageFlattenProperty, object instance)
{
DynamoDBEntry entry;
if (!document.TryGetValue(attributeName, out entry)) return;

if (ShouldSave(entry, true))
{
object value = FromDynamoDBEntry(propertyStorageFlattenProperty, entry, flatConfig);

if (!TrySetValue(instance, propertyStorageFlattenProperty.Member, value))
{
throw new InvalidOperationException("Unable to retrieve value from " + attributeName);
}
}

if (propertyStorageFlattenProperty.IsVersion)
storage.CurrentVersion = entry as Primitive;
}

/// <summary>
Expand Down Expand Up @@ -469,29 +493,46 @@ private void PopulateItemStorage(object toStore, ItemStorage storage, DynamoDBFl
if (keysOnly && !propertyStorage.IsHashKey && !propertyStorage.IsRangeKey &&
!propertyStorage.IsVersion) continue;

if (propertyStorage.IsFlattened) continue;

string propertyName = propertyStorage.PropertyName;
string attributeName = propertyStorage.AttributeName;

object value;
if (TryGetValue(toStore, propertyStorage.Member, out value))
{
DynamoDBEntry dbe = ToDynamoDBEntry(propertyStorage, value, flatConfig);
DynamoDBEntry dbe = ToDynamoDBEntry(propertyStorage, value, flatConfig, propertyStorage.FlattenProperty);

if (ShouldSave(dbe, ignoreNullValues))
{
Primitive dbePrimitive = dbe as Primitive;
if (propertyStorage.IsHashKey || propertyStorage.IsRangeKey ||
propertyStorage.IsVersion || propertyStorage.IsLSIRangeKey)

if (propertyStorage.FlattenProperty)
{
if (dbe != null && dbePrimitive == null)
throw new InvalidOperationException("Property " + propertyName +
" is a hash key, range key or version property and must be Primitive");
}
if (dbe == null) continue;

document[attributeName] = dbe;
if (dbe is not Document innerDocument) continue;

if (propertyStorage.IsVersion)
storage.CurrentVersion = dbePrimitive;
foreach (var pair in innerDocument)
{
document[pair.Key] = pair.Value;
}
}
else
{
Primitive dbePrimitive = dbe as Primitive;
if (propertyStorage.IsHashKey || propertyStorage.IsRangeKey ||
propertyStorage.IsVersion || propertyStorage.IsLSIRangeKey)
{
if (dbe != null && dbePrimitive == null)
throw new InvalidOperationException("Property " + propertyName +
" is a hash key, range key or version property and must be Primitive");
}

document[attributeName] = dbe;

if (propertyStorage.IsVersion)
storage.CurrentVersion = dbePrimitive;
}
}
}
else
Expand Down Expand Up @@ -671,7 +712,8 @@ internal DynamoDBEntry ToDynamoDBEntry(SimplePropertyStorage propertyStorage, ob

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072",
Justification = "The user's type has been annotated with InternalConstants.DataModelModeledType with the public API into the library. At this point the type will not be trimmed.")]
private DynamoDBEntry ToDynamoDBEntry(SimplePropertyStorage propertyStorage, object value, DynamoDBFlatConfig flatConfig, bool canReturnScalarInsteadOfList)
private DynamoDBEntry ToDynamoDBEntry(SimplePropertyStorage propertyStorage, object value,
DynamoDBFlatConfig flatConfig, bool canReturnScalarInsteadOfList)
{
if (value == null)
return null;
Expand Down Expand Up @@ -750,7 +792,7 @@ private bool TryToMap(object value, [DynamicallyAccessedMembers(InternalConstant
if (item == null)
entry = DynamoDBNull.Null;
else
entry = ToDynamoDBEntry(propertyStorage, item, flatConfig);
entry = ToDynamoDBEntry(propertyStorage, item, flatConfig, false);

output[key] = entry;
}
Expand Down Expand Up @@ -786,7 +828,7 @@ private bool TryToList(object value, [DynamicallyAccessedMembers(DynamicallyAcce
entry = DynamoDBNull.Null;
else
{
entry = ToDynamoDBEntry(propertyStorage, item, flatConfig);
entry = ToDynamoDBEntry(propertyStorage, item, flatConfig, false);
}

output.Add(entry);
Expand Down Expand Up @@ -1134,7 +1176,7 @@ private static List<QueryCondition> CreateQueryConditions(DynamoDBFlatConfig fla
// Key creation
private DynamoDBEntry ValueToDynamoDBEntry(PropertyStorage propertyStorage, object value, DynamoDBFlatConfig flatConfig)
{
var entry = ToDynamoDBEntry(propertyStorage, value, flatConfig);
var entry = ToDynamoDBEntry(propertyStorage, value, flatConfig, false);
return entry;
}
private static void ValidateKey(Key key, ItemStorageConfig storageConfig)
Expand Down
124 changes: 78 additions & 46 deletions sdk/src/Services/DynamoDBv2/Custom/DataModel/InternalModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,17 @@ internal class PropertyStorage : SimplePropertyStorage
// whether to store Type Discriminator for polymorphic serialization
public bool PolymorphicProperty { get; set; }

// whether to store child properties at the same level as the parent property
public bool FlattenProperty { get; set; }

// whether to store property at parent level
public bool IsFlattened { get; set; }

// corresponding IndexNames, if applicable
public List<string> IndexNames { get; set; }

public List<PropertyStorage> FlattenProperties { get; set; }

public void AddIndex(DynamoDBGlobalSecondaryIndexHashKeyAttribute gsiHashKey)
{
AddIndex(new GSI(true, gsiHashKey.AttributeName, gsiHashKey.IndexNames));
Expand Down Expand Up @@ -219,6 +227,9 @@ public void Validate(DynamoDBContext context)
if (PolymorphicProperty)
throw new InvalidOperationException("Converter for " + PropertyName + " must not be set at the same time as derived types.");

if (FlattenProperty)
throw new InvalidOperationException("Converter for " + PropertyName + " must not be set at the same time as flatten types.");

if (StoreAsEpoch || StoreAsEpochLong)
throw new InvalidOperationException("Converter for " + PropertyName + " must not be set at the same time as StoreAsEpoch or StoreAsEpochLong is set to true");

Expand Down Expand Up @@ -248,6 +259,7 @@ internal PropertyStorage(MemberInfo member)
{
IndexNames = new List<string>();
Indexes = new List<Index>();
FlattenProperties = new List<PropertyStorage>();
}

}
Expand Down Expand Up @@ -531,20 +543,58 @@ public PropertyStorage VersionPropertyStorage

public void Denormalize(DynamoDBContext context, string derivedTypeAttributeName)
{
// analyze all PropertyStorage configs and denormalize data into other properties
// all data must exist in PropertyStorage objects prior to denormalization

foreach (var property in this.BaseTypeStorageConfig.Properties)
{
ProcessProperty(property, this.BaseTypeStorageConfig, true);
}

foreach (var polymorphicTypesProperty in this.PolymorphicTypesStorageConfig)
{
foreach (var polymorphicProperty in polymorphicTypesProperty.Value.Properties)
{
ProcessProperty(polymorphicProperty, polymorphicTypesProperty.Value, false);
}
}

if (StorePolymorphicTypes)
{
AttributesToGet.Add(derivedTypeAttributeName);
}

if (this.BaseTypeStorageConfig.Properties.Count == 0)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Type {0} is unsupported, it has no supported members", this.BaseTypeStorageConfig.TargetType.FullName));
return;

void ProcessProperty(PropertyStorage property, StorageConfig storageConfig, bool setKeyProperties)
{
// only add non-ignored properties
if (property.IsIgnored) continue;
if (property.IsIgnored)
return;

property.Validate(context);
AddPropertyStorage(property, this.BaseTypeStorageConfig);

SetPropertyConfig(property, storageConfig, setKeyProperties);

if (!property.FlattenProperty) return;

// flatten properties
foreach (var flattenProperty in property.FlattenProperties)
{
ProcessProperty(flattenProperty, storageConfig, setKeyProperties);
}
}

void SetPropertyConfig(PropertyStorage property, StorageConfig storageConfig, bool setKeyProperties)
{
AddPropertyStorage(property, storageConfig);

string propertyName = property.PropertyName;

AddKeyPropertyNames(property, propertyName);
if (setKeyProperties)
{
AddKeyPropertyNames(property, propertyName);
}

foreach (var index in property.Indexes)
{
Expand All @@ -557,47 +607,8 @@ public void Denormalize(DynamoDBContext context, string derivedTypeAttributeName
AddLSIConfigs(lsi.IndexNames, propertyName);
}
}

foreach (var polymorphicTypesProperty in this.PolymorphicTypesStorageConfig)
{
foreach (var polymorphicProperty in polymorphicTypesProperty.Value.Properties)
{
// only add non-ignored properties
if (polymorphicProperty.IsIgnored) continue;

polymorphicProperty.Validate(context);

string propertyName = polymorphicProperty.PropertyName;

AddPropertyStorage(polymorphicProperty, polymorphicTypesProperty.Value);

foreach (var index in polymorphicProperty.Indexes)
{
var gsi = index as PropertyStorage.GSI;
if (gsi != null)
AddGSIConfigs(gsi.IndexNames, propertyName, gsi.IsHashKey);

var lsi = index as PropertyStorage.LSI;
if (lsi != null)
AddLSIConfigs(lsi.IndexNames, propertyName);
}
}
}

if (PolymorphicTypesStorageConfig.Any())
{
AttributesToGet.Add(derivedTypeAttributeName);
}

//if (this.HashKeyPropertyNames.Count == 0)
// throw new InvalidOperationException("No hash key configured for type " + TargetTypeInfo.FullName);

if (this.BaseTypeStorageConfig.Properties.Count == 0)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Type {0} is unsupported, it has no supported members", this.BaseTypeStorageConfig.TargetType.FullName));
}


public void AddPolymorphicPropertyStorageConfiguration(string typeDiscriminator, Type derivedType, StorageConfig polymorphicStorageConfig)
{
this.PolymorphicTypesStorageConfig.Add(typeDiscriminator, polymorphicStorageConfig);
Expand Down Expand Up @@ -941,6 +952,8 @@ private static void PopulateConfigFromType(ItemStorageConfig config, [Dynamicall
}
}

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072",
Justification = "The user's type has been annotated with DynamicallyAccessedMemberTypes.All with the public API into the library. At this point the type will not be trimmed.")]
private static PropertyStorage MemberInfoToPropertyStorage(ItemStorageConfig config, MemberInfo member)
{
// prepare basic info
Expand All @@ -953,7 +966,26 @@ private static PropertyStorage MemberInfoToPropertyStorage(ItemStorageConfig con
{
// filter out ignored properties
if (attribute is DynamoDBIgnoreAttribute)
{
propertyStorage.IsIgnored = true;
continue;
}

// flatten properties
if (attribute is DynamoDBFlattenAttribute)
{
propertyStorage.FlattenProperty = true;

var type = Utils.GetType(member);
var members = Utils.GetMembersFromType(type);

foreach (var memberInfo in members)
{
var flattenPropertyStorage = MemberInfoToPropertyStorage(config, memberInfo);
flattenPropertyStorage.IsFlattened = true;
propertyStorage.FlattenProperties.Add(flattenPropertyStorage);
}
}

if (attribute is DynamoDBVersionAttribute)
propertyStorage.IsVersion = true;
Expand Down Expand Up @@ -1014,7 +1046,7 @@ private static PropertyStorage MemberInfoToPropertyStorage(ItemStorageConfig con
}
}

return propertyStorage;
return propertyStorage;
}

private static void PopulateConfigFromTable(ItemStorageConfig config, Table table)
Expand Down
Loading