Skip to content

Commit e2f1c1a

Browse files
committed
Merging from main
2 parents def4df0 + 7eb9c90 commit e2f1c1a

File tree

5 files changed

+117
-14
lines changed

5 files changed

+117
-14
lines changed

Extensions/Cosmos/Cosmos.DataTransfer.CosmosExtension.UnitTests/CosmosDataSinkExtensionTests.cs

+78
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Cosmos.DataTransfer.Interfaces;
22
using System.Dynamic;
3+
using Microsoft.VisualStudio.TestTools.UnitTesting;
34

45
namespace Cosmos.DataTransfer.CosmosExtension.UnitTests
56
{
@@ -56,6 +57,83 @@ public void BuildDynamicObjectTree_WithNestedArrays_WorksCorrectly()
5657
Assert.AreEqual("sub2-1", secondSubArray[0].id);
5758
}
5859

60+
[TestMethod]
61+
public void BuildDynamicObjectTree_WithAnyCaseIds_UsesSourceIdValue()
62+
{
63+
var numeric = Random.Shared.Next();
64+
var lower = Guid.NewGuid().ToString();
65+
var upper = Guid.NewGuid().ToString();
66+
var mixed = Guid.NewGuid().ToString();
67+
var reversed = Guid.NewGuid().ToString();
68+
var item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
69+
{
70+
{ "id", numeric },
71+
});
72+
73+
dynamic obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: false)!;
74+
Assert.AreEqual(numeric.ToString(), obj.id);
75+
76+
item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
77+
{
78+
{ "id", lower },
79+
});
80+
81+
obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: false)!;
82+
Assert.AreEqual(lower, obj.id);
83+
84+
item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
85+
{
86+
{ "ID", upper },
87+
});
88+
obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: false)!;
89+
Assert.AreEqual(upper, obj.id);
90+
91+
item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
92+
{
93+
{ "Id", mixed },
94+
});
95+
obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: false)!;
96+
Assert.AreEqual(mixed, obj.id);
97+
98+
item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
99+
{
100+
{ "iD", reversed },
101+
});
102+
obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: false)!;
103+
Assert.AreEqual(reversed, obj.id);
104+
}
105+
106+
[TestMethod]
107+
public void BuildDynamicObjectTree_WithPreservedMixedCaseIds_PassesThroughSourceValues()
108+
{
109+
var id = Random.Shared.Next();
110+
var upper = Guid.NewGuid().ToString();
111+
var mixed = Guid.NewGuid().ToString();
112+
var item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
113+
{
114+
{ "id", id },
115+
{ "ID", upper },
116+
{ "Id", mixed }
117+
});
118+
119+
dynamic obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: true)!;
120+
Assert.AreEqual(id.ToString(), obj.id);
121+
Assert.AreEqual(upper, obj.ID);
122+
Assert.AreEqual(mixed, obj.Id);
123+
124+
item = new CosmosDictionaryDataItem(new Dictionary<string, object?>()
125+
{
126+
{ "ID", upper },
127+
{ "Id", mixed }
128+
});
129+
obj = item.BuildDynamicObjectTree(requireStringId: true, preserveMixedCaseIds: true)!;
130+
Assert.AreEqual(upper, obj.ID);
131+
Assert.AreEqual(mixed, obj.Id);
132+
string? cosmosId = obj.id;
133+
Assert.IsNotNull(cosmosId);
134+
Assert.IsFalse(string.IsNullOrWhiteSpace(cosmosId));
135+
}
136+
59137
[TestMethod]
60138
public void BuildDynamicObjectTree_WithIgnoredNulls_ExcludesNullFields()
61139
{

Extensions/Cosmos/Cosmos.DataTransfer.CosmosExtension/CosmosDataSinkExtension.cs

+6-3
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,14 @@ void ReportCount(int i)
8989
addedCount += i;
9090
if (addedCount % 500 == 0)
9191
{
92-
logger.LogInformation("{AddedCount} records added after {TotalSeconds}s", addedCount, $"{timer.ElapsedMilliseconds / 1000.0:F2}");
92+
logger.LogInformation("{AddedCount} records added after {TotalSeconds}s ({AddRate} records/s)", addedCount, $"{timer.ElapsedMilliseconds / 1000.0:F2}", $"{(int)(addedCount / (timer.ElapsedMilliseconds / 1000.0))}");
9393
}
9494
}
9595

96-
var convertedObjects = dataItems.Select(di => di.BuildDynamicObjectTree(requireStringId: true, ignoreNullValues: settings.IgnoreNullValues)).Where(o => o != null).OfType<ExpandoObject>();
96+
var convertedObjects = dataItems
97+
.Select(di => di.BuildDynamicObjectTree(requireStringId: true, ignoreNullValues: settings.IgnoreNullValues, preserveMixedCaseIds: settings.PreserveMixedCaseIds))
98+
.Where(o => o != null)
99+
.OfType<ExpandoObject>();
97100
var batches = convertedObjects.Buffer(settings.BatchSize);
98101
var retry = GetRetryPolicy(settings.MaxRetryCount, settings.InitialRetryDurationMs);
99102
await foreach (var batch in batches.WithCancellation(cancellationToken))
@@ -111,7 +114,7 @@ void ReportCount(int i)
111114
throw new Exception($"Only {addedCount} of {inputCount} records were added to Cosmos");
112115
}
113116

114-
logger.LogInformation("Added {AddedCount} total records in {TotalSeconds}s", addedCount, $"{timer.ElapsedMilliseconds / 1000.0:F2}");
117+
logger.LogInformation("Added {AddedCount} total records in {TotalSeconds}s ({AddRate} records/s)", addedCount, $"{timer.ElapsedMilliseconds / 1000.0:F2}", $"{(int)(addedCount / (timer.ElapsedMilliseconds / 1000.0))}");
115118
}
116119

117120
private static AsyncRetryPolicy GetRetryPolicy(int maxRetryCount, int initialRetryDuration)

Extensions/Cosmos/Cosmos.DataTransfer.CosmosExtension/CosmosSinkSettings.cs

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ public class CosmosSinkSettings : CosmosSettingsBase, IDataExtensionSettings
1414
public bool UseAutoscaleForCreatedContainer { get; set; } = true;
1515
public bool IsServerlessAccount { get; set; } = false;
1616
public bool UseSharedThroughput { get; set; } = false;
17+
public bool PreserveMixedCaseIds { get; set; } = false;
1718
public DataWriteMode WriteMode { get; set; } = DataWriteMode.Insert;
1819
public bool IgnoreNullValues { get; set; } = false;
1920
public List<string>? PartitionKeyPaths { get; set; }

Extensions/Cosmos/README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Or with RBAC:
4444
}
4545
```
4646

47-
Sink requires an additional `PartitionKeyPath` parameter which is used when creating the container if it does not exist. To use hierarchical partition keys, instead use the `PartitionKeyPaths` setting to supply an array of up to 3 paths. It also supports an optional `RecreateContainer` parameter (`false` by default) to delete and then recreate the container to ensure only newly imported data is present. The optional `BatchSize` parameter (100 by default) sets the number of items to accumulate before inserting. `ConnectionMode` can be set to either `Gateway` (default) or `Direct` to control how the client connects to the CosmosDB service. For situations where a container is created as part of the transfer operation `CreatedContainerMaxThroughput` (in RUs) and `UseAutoscaleForCreatedContainer` provide the initial throughput settings which will be in effect when executing the transfer. To instead use shared throughput that has been provisioned at the database level, set the `UseSharedThroughput` parameter to `true`. The optional `WriteMode` parameter specifies the type of data write to use: `InsertStream`, `Insert`, `UpsertStream`, or `Upsert`. The `IsServerlessAccount` parameter specifies whether the target account uses Serverless instead of Provisioned throughput, which affects the way containers are created. Additional parameters allow changing the behavior of the Cosmos client appropriate to your environment. The `IgnoreNullValues` parameter allows for excluding fields with null values when writing to Cosmos DB.
47+
Sink requires an additional `PartitionKeyPath` parameter which is used when creating the container if it does not exist. To use hierarchical partition keys, instead use the `PartitionKeyPaths` setting to supply an array of up to 3 paths. It also supports an optional `RecreateContainer` parameter (`false` by default) to delete and then recreate the container to ensure only newly imported data is present. The optional `BatchSize` parameter (100 by default) sets the number of items to accumulate before inserting. `ConnectionMode` can be set to either `Gateway` (default) or `Direct` to control how the client connects to the CosmosDB service. For situations where a container is created as part of the transfer operation `CreatedContainerMaxThroughput` (in RUs) and `UseAutoscaleForCreatedContainer` provide the initial throughput settings which will be in effect when executing the transfer. To instead use shared throughput that has been provisioned at the database level, set the `UseSharedThroughput` parameter to `true`. The optional `WriteMode` parameter specifies the type of data write to use: `InsertStream`, `Insert`, `UpsertStream`, or `Upsert`. The `IsServerlessAccount` parameter specifies whether the target account uses Serverless instead of Provisioned throughput, which affects the way containers are created. Additional parameters allow changing the behavior of the Cosmos client appropriate to your environment. The `PreserveMixedCaseIds` parameter (`false` by default) ignores differently cased `id` fields and writes them through without modification, while generating a separate lowercased `id` field as required by Cosmos. The `IgnoreNullValues` parameter allows for excluding fields with null values when writing to Cosmos DB.
4848

4949
### Sink
5050

@@ -62,6 +62,7 @@ Sink requires an additional `PartitionKeyPath` parameter which is used when crea
6262
"CreatedContainerMaxThroughput": 1000,
6363
"UseAutoscaleForCreatedContainer": true,
6464
"WriteMode": "InsertStream",
65+
"PreserveMixedCaseIds": false,
6566
"IgnoreNullValues": false,
6667
"IsServerlessAccount": false,
6768
"UseSharedThroughput": false

Interfaces/Cosmos.DataTransfer.Interfaces/DataItemExtensions.cs

+30-10
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ public static class DataItemExtensions
1010
/// <param name="source"></param>
1111
/// <param name="requireStringId">If true, adds a new GUID "id" field to any top level items where one is not already present.</param>
1212
/// <param name="ignoreNullValues">If true, excludes fields containing null values from output.</param>
13+
/// <param name="preserveMixedCaseIds">If true, disregards differently cased "id" fields for purposes of required "id" and passes them through.</param>
1314
/// <returns>A dynamic object containing the entire data structure.</returns>
1415
/// <remarks>The returned ExpandoObject can be used directly as an IDictionary.</remarks>
15-
public static ExpandoObject? BuildDynamicObjectTree(this IDataItem? source, bool requireStringId = false, bool ignoreNullValues = false)
16+
public static ExpandoObject? BuildDynamicObjectTree(this IDataItem? source, bool requireStringId = false, bool ignoreNullValues = false, bool preserveMixedCaseIds = false)
1617
{
1718
if (source == null)
1819
{
@@ -21,20 +22,25 @@ public static class DataItemExtensions
2122

2223
var fields = source.GetFieldNames().ToList();
2324
var item = new ExpandoObject();
24-
25+
2526
/*
2627
* If the item contains a lowercase id field, we can take it as is.
27-
* If we have an uppercase Id or ID field, but no lowercase id, we will rename it to id.
28+
* If we have an uppercase Id or ID field, but no lowercase id, we will rename it to id, unless `preserveMixedCaseIds` is set to true.
29+
* If `preserveMixedCaseIds` is set to true, any differently cased "id" fields will be passed through as normal properties with no casing change and a separate "id" will be generated.
2830
* Then it can be used i.e. as CosmosDB primary key, when `requireStringId` is set to true.
2931
*/
3032
var containsLowercaseIdField = fields.Contains("id", StringComparer.CurrentCulture);
3133
var containsAnyIdField = fields.Contains("id", StringComparer.CurrentCultureIgnoreCase);
32-
33-
if (requireStringId && !containsAnyIdField)
34+
35+
if (requireStringId)
3436
{
35-
item.TryAdd("id", Guid.NewGuid().ToString());
37+
bool mismatchedIdCasing = preserveMixedCaseIds && !containsLowercaseIdField;
38+
if (!containsAnyIdField || mismatchedIdCasing)
39+
{
40+
item.TryAdd("id", Guid.NewGuid().ToString());
41+
}
3642
}
37-
43+
3844
foreach (string field in fields)
3945
{
4046
object? value = source.GetValue(field);
@@ -44,10 +50,24 @@ public static class DataItemExtensions
4450
}
4551

4652
var fieldName = field;
47-
if (string.Equals(field, "id", StringComparison.CurrentCultureIgnoreCase) && requireStringId && !containsLowercaseIdField)
53+
if (requireStringId && string.Equals(field, "id", StringComparison.CurrentCultureIgnoreCase))
4854
{
49-
value = value?.ToString();
50-
fieldName = "id";
55+
if (preserveMixedCaseIds)
56+
{
57+
if (string.Equals(field, "id", StringComparison.CurrentCulture))
58+
{
59+
value = value?.ToString();
60+
}
61+
}
62+
else if (!containsLowercaseIdField)
63+
{
64+
value = value?.ToString();
65+
fieldName = "id";
66+
}
67+
else
68+
{
69+
value = value?.ToString();
70+
}
5171
}
5272
else if (value is IDataItem child)
5373
{

0 commit comments

Comments
 (0)