diff --git a/CosmosDBShell.Tests/CommandTests/CreateCommandTests.cs b/CosmosDBShell.Tests/CommandTests/CreateCommandTests.cs index 443d7a38..bfb06a25 100644 --- a/CosmosDBShell.Tests/CommandTests/CreateCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/CreateCommandTests.cs @@ -12,6 +12,32 @@ namespace CosmosShell.Tests.CommandTests; public class CreateCommandTests { + private const string UniqueKeyPolicy = """{"uniqueKeys":[{"paths":["/sku"]}]}"""; + + [Theory] + [InlineData("item", """{"id":"product"}""", UniqueKeyPolicy)] + [InlineData("item", """{"id":"product"}""", "")] + [InlineData("i", """{"id":"product"}""", UniqueKeyPolicy)] + [InlineData("i", """{"id":"product"}""", "")] + [InlineData("database", "ExampleShop", UniqueKeyPolicy)] + [InlineData("database", "ExampleShop", "")] + [InlineData("db", "ExampleShop", UniqueKeyPolicy)] + [InlineData("db", "ExampleShop", "")] + public async Task Create_NonContainerWithUniqueKeyPolicy_ThrowsUsageErrorBeforeConnecting( + string target, string name, string policy) + { + using var shell = ShellInterpreter.CreateInstance(); + var parser = new StatementParser($"create {target} '{name}' --unique_key_policy='{policy}'"); + var statement = Assert.Single(parser.ParseStatements()); + + var exception = await Assert.ThrowsAsync( + () => statement.RunAsync(shell, new CommandState(), TestContext.Current.CancellationToken)); + + Assert.True(exception.IsUsageError); + Assert.Equal("create", exception.Command); + Assert.Contains("The --unique_key_policy option is only valid for `create container`", exception.Message); + } + [Fact] public async Task MkCon_PositionalPartitionKeyMissing_UsesCustomErrorMessage() { diff --git a/CosmosDBShell.Tests/CommandTests/ServerlessCreationThroughputTests.cs b/CosmosDBShell.Tests/CommandTests/ServerlessCreationThroughputTests.cs index 345c6bf7..85dd13c3 100644 --- a/CosmosDBShell.Tests/CommandTests/ServerlessCreationThroughputTests.cs +++ b/CosmosDBShell.Tests/CommandTests/ServerlessCreationThroughputTests.cs @@ -22,6 +22,108 @@ namespace CosmosShell.Tests.CommandTests; public class ServerlessCreationThroughputTests { private const string ServerlessMessage = "Setting offer throughput or autopilot on container is not supported for serverless accounts."; + private const string UniqueKeysJson = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplier","/externalCode"]}]}"""; + + [Theory] + [InlineData("mkcon")] + [InlineData("create container")] + public async Task ContainerCommand_BindsUniquePolicyAndPreservesConstraintsOnDataPlane(string command) + { + using var shell = ShellInterpreter.CreateInstance(); + var (client, database) = CreateDataPlaneClient(); + shell.State = new DatabaseState("db", client); + ContainerProperties? sent = null; + var created = Substitute.For(); + created.StatusCode.Returns(HttpStatusCode.Created); + created.Container.Id.Returns("Items"); + database.CreateContainerIfNotExistsAsync( + Arg.Do(properties => sent = properties), + Arg.Any(), Arg.Any(), Arg.Any()).Returns(created); + + var result = await shell.ExecuteCommandAsync( + $"{command} Items /tenantId --unique_key_policy='{UniqueKeysJson}'", TestContext.Current.CancellationToken); + + Assert.False(result.IsError); + Assert.NotNull(sent); + Assert.Collection(sent.UniqueKeyPolicy.UniqueKeys, + key => Assert.Equal(["/sku"], key.Paths), + key => Assert.Equal(["/supplier", "/externalCode"], key.Paths)); + } + + [Fact] + public async Task DataPlaneCreateContainer_WithUniqueKeys_RejectsExistingContainer() + { + using var shell = ShellInterpreter.CreateInstance(); + var (client, database) = CreateDataPlaneClient(); + shell.State = new DatabaseState("db", client); + var existing = Substitute.For(); + existing.StatusCode.Returns(HttpStatusCode.OK); + database.CreateContainerIfNotExistsAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(existing); + + var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", UniqueKeyPolicy = UniqueKeysJson }; + var error = await Assert.ThrowsAsync( + () => command.ExecuteAsync(shell, new CommandState(), "mkcon", TestContext.Current.CancellationToken)); + + Assert.Contains("already exists", error.Message); + Assert.IsType(error.InnerException); + } + + [Theory] + [InlineData("", null)] + [InlineData("null", null)] + [InlineData("""{"uniqueKeys":[]}""", null)] + [InlineData("""{"uniqueKeys":[{"paths":[]}]}""", null)] + [InlineData("""{"uniqueKeys":[{"paths":["sku"]}]}""", null)] + [InlineData("""{"uniqueKeys":[{"paths":[12]}]}""", null)] + [InlineData("""{"uniqueKeys":[{"paths":["/\uD800"]}]}""", null)] + [InlineData("""{"uniqueKeys":[{"paths":["/\uDC00"]}]}""", null)] + [InlineData("""{"uniqueKeys":[{"paths":["/sku","/sku"]}]}""", null)] + [InlineData(UniqueKeysJson, "/id")] + public async Task Mkcon_InvalidUniqueKeyPolicy_IsRejectedBeforeBackendAccess(string json, string? legacy) + { + using var shell = ShellInterpreter.CreateInstance(); + var client = Substitute.For(); + shell.State = new DatabaseState("db", client); + var command = new MakeContainerCommand { Name = "Items", PartitionKey = "/pk", UniqueKeyPolicy = json, UniqueKey = legacy }; + + await Assert.ThrowsAsync( + () => command.ExecuteAsync(shell, new CommandState(), "mkcon", TestContext.Current.CancellationToken)); + + client.DidNotReceiveWithAnyArgs().GetDatabase(default!); + } + + [Fact] + public void UniqueKeyPolicy_DecodesValidSurrogatePairInPath() + { + var keys = ContainerUniqueKeyPolicy.Parse(null, """{"uniqueKeys":[{"paths":["/\uD83D\uDE80"]}]}"""); + + Assert.Equal("/\U0001F680", Assert.Single(Assert.Single(keys))); + } + + [Theory] + [InlineData(10, 8, false)] + [InlineData(10, 7, true)] + [InlineData(11, 1, false)] + public void UniqueKeyPolicy_EnforcesServiceLimits(int constraints, int firstPathCount, bool valid) + { + var json = System.Text.Json.JsonSerializer.Serialize(new + { + uniqueKeys = Enumerable.Range(0, constraints).Select(i => new + { + paths = Enumerable.Range(0, i == 0 ? firstPathCount : 1).Select(j => $"/p{i}_{j}"), + }), + }); + + if (valid) + { + Assert.Equal(constraints, ContainerUniqueKeyPolicy.Parse(null, json).Count); + } + else + { + Assert.Throws(() => ContainerUniqueKeyPolicy.Parse(null, json)); + } + } [Fact] public void CreateUpdateConfig_ServerlessWithoutOptions_OmitsThroughput() @@ -141,14 +243,33 @@ public async Task ArmCreateContainer_Serverless_SendsPayloadWithoutThroughput() .Returns(Substitute.For>()); await CosmosArmResourceProvider.CreateContainerAsync( - context, "db", "Items", ["/tenantId", "/userId"], "/email", null, null, null, TestContext.Current.CancellationToken); + context, "db", "Items", ["/tenantId", "/userId"], [["/email"], ["/supplier", "/externalCode"]], null, null, null, TestContext.Current.CancellationToken); var json = CosmosArmResourceProvider.WriteArmModel(Assert.IsType(sent)); Assert.DoesNotContain("throughput", json, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("autoscaleSettings", json, StringComparison.OrdinalIgnoreCase); Assert.Contains("/tenantId", json); Assert.Contains("/userId", json); - Assert.Contains("/email", json); + using var document = System.Text.Json.JsonDocument.Parse(json); + var keys = document.RootElement.GetProperty("properties").GetProperty("resource").GetProperty("uniqueKeyPolicy").GetProperty("uniqueKeys"); + Assert.Equal(2, keys.GetArrayLength()); + Assert.Equal("/email", Assert.Single(keys[0].GetProperty("paths").EnumerateArray()).GetString()); + Assert.Equal(new[] { "/supplier", "/externalCode" }, keys[1].GetProperty("paths").EnumerateArray().Select(p => p.GetString())); + } + + [Fact] + public async Task ArmCreateContainer_WithUniqueKeys_RejectsExistingContainerBeforePut() + { + var (context, containers) = CreateArmContainerContext(Provisioned()); + var existing = Substitute.For(); + containers.GetIfExistsAsync("Items", Arg.Any()) + .Returns(Task.FromResult>(Response.FromValue(existing, Substitute.For()))); + var token = TestContext.Current.CancellationToken; + + await Assert.ThrowsAsync(() => CosmosArmResourceProvider.CreateContainerAsync( + context, "db", "Items", ["/pk"], [["/sku"], ["/externalCode"]], null, null, null, token)); + + await containers.DidNotReceiveWithAnyArgs().CreateOrUpdateAsync(default, default!, default!, token); } [Fact] @@ -466,6 +587,7 @@ private static (DataPlaneCosmosResourceOperations Operations, Database Database, private static (CosmosClient Client, Database Database) CreateDataPlaneClient() { var client = Substitute.For(); + client.Endpoint.Returns(new Uri("https://example.documents.azure.com")); var database = Substitute.For(); var existing = Substitute.For(); existing.StatusCode.Returns(HttpStatusCode.OK); @@ -492,6 +614,8 @@ private static (ArmCosmosContext Context, CosmosDBSqlContainerCollection Contain .Returns(Task.FromResult>( Response.FromValue(database, Substitute.For()))); var containers = Substitute.For(); + containers.GetIfExistsAsync("Items", Arg.Any()) + .Returns(Task.FromResult(Substitute.For>())); database.GetCosmosDBSqlContainers().Returns(containers); return (context, containers); } diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 58ec4e97..deede2e2 100644 --- a/CosmosDBShell.Tests/McpConfirmationTests.cs +++ b/CosmosDBShell.Tests/McpConfirmationTests.cs @@ -23,6 +23,65 @@ namespace CosmosShell.Tests; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class McpConfirmationTests { + [Theory] + [InlineData("mkcon")] + [InlineData("create")] + public async Task ContainerCreation_OverMcp_BindsUniqueKeyPolicy(string toolName) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + using var host = McpServer.CreateHost(new Program.CosmosShellOptions { McpPort = 0 }); + await host.StartAsync(timeout.Token); + var shell = ShellInterpreter.Instance; + var originalState = shell.State; + using var cosmos = Substitute.For(); + try + { + cosmos.Endpoint.Returns(new Uri("https://example.documents.azure.com")); + var database = Substitute.For(); + cosmos.GetDatabase("db").Returns(database); + var databaseResponse = Substitute.For(); + databaseResponse.StatusCode.Returns(HttpStatusCode.OK); + database.ReadAsync(Arg.Any(), Arg.Any()).Returns(databaseResponse); + var created = Substitute.For(); + created.StatusCode.Returns(HttpStatusCode.Created); + created.Container.Id.Returns("Items"); + ContainerProperties? sent = null; + database.CreateContainerIfNotExistsAsync( + Arg.Do(properties => sent = properties), + Arg.Any(), Arg.Any(), Arg.Any()).Returns(created); + shell.State = new DatabaseState("db", cosmos); + + var address = host.Services.GetRequiredService().Features.Get()!.Addresses.Single(); + var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri(address.TrimEnd('/') + "/") }); + await using var client = await McpClient.CreateAsync(transport, cancellationToken: timeout.Token); + var args = new Dictionary + { + ["name"] = "Items", + ["partition_key"] = "/tenant", + ["unique_key_policy"] = """{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplier","/externalCode"]}]}""", + }; + if (toolName == "create") + { + args["item"] = "container"; + } + + var result = await client.CallToolAsync(toolName, args, cancellationToken: timeout.Token); + + Assert.False(result.IsError); + Assert.NotNull(sent); + Assert.Collection( + sent.UniqueKeyPolicy.UniqueKeys, + key => Assert.Equal(["/sku"], key.Paths), + key => Assert.Equal(["/supplier", "/externalCode"], key.Paths)); + } + finally + { + shell.State = originalState; + await host.StopAsync(TestContext.Current.CancellationToken); + } + } + [Theory] [InlineData("rmcon", "accept", null)] [InlineData("rmdb", "accept", null)] @@ -130,7 +189,7 @@ public async Task ResourceDeletion_OverHttp_RequiresOnlyMcpApproval(string comma finally { await host.StopAsync(TestContext.Current.CancellationToken); - shell.State = originalState; + shell.State = originalState; } } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ContainerUniqueKeyPolicy.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ContainerUniqueKeyPolicy.cs new file mode 100644 index 00000000..b70367c0 --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ContainerUniqueKeyPolicy.cs @@ -0,0 +1,92 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Commands; + +using System.Text.Json; +using Azure.Data.Cosmos.Shell.Core; +using Azure.Data.Cosmos.Shell.Util; + +internal static class ContainerUniqueKeyPolicy +{ + public static IReadOnlyList> Parse(string? legacy, string? json) + { + var constraints = new List>(); + if (json is null) + { + if (string.IsNullOrWhiteSpace(legacy)) + { + return constraints; + } + + constraints.Add(legacy.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)); + } + else + { + if (legacy is not null) + { + throw CommandException.Usage("mkcon", MessageService.GetString("command-mkcon-error_unique_key_policy_conflict")); + } + + try + { + using var document = JsonDocument.Parse(json); + var keys = ReadArrayProperty(document.RootElement, "uniqueKeys"); + constraints.AddRange(keys.EnumerateArray().Select(key => + ReadArrayProperty(key, "paths").EnumerateArray().Select(ReadPath).ToArray())); + } + catch (JsonException ex) + { + throw InvalidPolicy(ex); + } + } + + if (constraints.Count is < 1 or > 10 + || constraints.Sum(paths => paths.Count) > 16 + || constraints.Any(paths => paths.Count == 0 + || paths.Any(path => path.Length < 2 || path[0] != '/' || string.IsNullOrWhiteSpace(path[1..])) + || paths.Distinct(StringComparer.Ordinal).Count() != paths.Count)) + { + throw InvalidPolicy(); + } + + return constraints; + } + + private static string ReadPath(JsonElement path) + { + if (path.ValueKind != JsonValueKind.String) + { + throw InvalidPolicy(); + } + + try + { + return path.GetString()!; + } + catch (InvalidOperationException ex) + { + // JsonDocument defers decoding escaped surrogate pairs until the string is read. + throw InvalidPolicy(ex); + } + } + + private static JsonElement ReadArrayProperty(JsonElement element, string name) + { + if (element.ValueKind != JsonValueKind.Object + || element.EnumerateObject().Count() != 1 + || !element.TryGetProperty(name, out var array) + || array.ValueKind != JsonValueKind.Array) + { + throw InvalidPolicy(); + } + + return array; + } + + private static CommandException InvalidPolicy(Exception? inner = null) + { + return CommandException.Usage("mkcon", MessageService.GetString("command-mkcon-error_invalid_unique_key_policy"), inner); + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CreateCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CreateCommand.cs index 1329a89b..b6db7e11 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CreateCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CreateCommand.cs @@ -31,6 +31,9 @@ internal class CreateCommand : CosmosCommand [CosmosParameter("unique_key", IsRequired = false)] public string? UniqueKey { get; init; } + [CosmosOption("unique_key_policy")] + public string? UniqueKeyPolicy { get; init; } + [CosmosOption("scale", "s")] public string? Scale { get; init; } @@ -52,6 +55,11 @@ internal class CreateCommand : CosmosCommand public async override Task ExecuteAsync(ShellInterpreter shell, CommandState commandState, string commandText, CancellationToken token) { var item = (this.Item ?? string.Empty).ToUpper(); + if (this.UniqueKeyPolicy is not null && !IsContainer(item)) + { + throw CommandException.Usage("create", MessageService.GetString("command-create-error_unique_key_policy_only_for_containers")); + } + if (IsItem(item)) { var mkItemCmd = new MakeItemCommand() @@ -89,6 +97,7 @@ public async override Task ExecuteAsync(ShellInterpreter shell, Co Name = this.Name, PartitionKey = this.PartitionKey, UniqueKey = this.UniqueKey, + UniqueKeyPolicy = this.UniqueKeyPolicy, Scale = this.Scale, MaxRU = this.MaxRU, Database = this.Database, diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/MakeContainerCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/MakeContainerCommand.cs index 75099806..436bf843 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/MakeContainerCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/MakeContainerCommand.cs @@ -41,6 +41,9 @@ internal class MakeContainerCommand : CosmosCommand, IStateVisitor 1) - { - var hpkProperties = new ContainerProperties(this.Name, keys); - if (this.UniqueKey != null) - { - AddUniqueKeyPolicy(hpkProperties, this.UniqueKey); - } - - return hpkProperties; - } - - var cp = new ContainerProperties(this.Name, keys[0]); - if (this.UniqueKey != null) - { - AddUniqueKeyPolicy(cp, this.UniqueKey); - } - - return cp; - } - - private static void AddUniqueKeyPolicy(ContainerProperties properties, string uniqueKey) - { - var key = new UniqueKey(); - foreach (var uk in uniqueKey.Split(",", StringSplitOptions.TrimEntries).Where(static path => !string.IsNullOrWhiteSpace(path))) - { - key.Paths.Add(uk); - } - - properties.UniqueKeyPolicy.UniqueKeys.Add(key); + return DataPlaneCosmosResourceOperations.BuildContainerProperties( + this.Name ?? string.Empty, keys, ContainerUniqueKeyPolicy.Parse(this.UniqueKey, this.UniqueKeyPolicy)); } private static List ParsePartitionKeyPaths(string? partitionKey) @@ -146,10 +122,9 @@ Task IStateVisitor.VisitContainerS private async Task CreateContainerInDatabaseAsync(ConnectedState state, ShellInterpreter shell, string databaseName, CancellationToken token) { - // Validate database exists - await ValidateDatabaseExistsAsync(state, databaseName, "mkcon", token); - var partitionKeyPaths = this.GetPartitionKeyPaths(); + var uniqueKeys = ContainerUniqueKeyPolicy.Parse(this.UniqueKey, this.UniqueKeyPolicy); + await ValidateDatabaseExistsAsync(state, databaseName, "mkcon", token); ResourceCreationResult creation; try { @@ -158,7 +133,7 @@ private async Task CreateContainerInDatabaseAsync(ConnectedState s databaseName, this.Name ?? string.Empty, partitionKeyPaths, - this.UniqueKey, + uniqueKeys, this.IndexPolicy, this.Scale, this.MaxRU, @@ -168,6 +143,13 @@ private async Task CreateContainerInDatabaseAsync(ConnectedState s { throw CommandException.Usage("mkcon", MessageService.GetString("command-mkcon-error_invalid_index_policy"), ex); } + catch (ExistingContainerUniqueKeyPolicyException ex) + { + throw new CommandException( + "mkcon", + MessageService.GetArgsString("command-mkcon-error_existing_unique_key_policy", "container", this.Name ?? string.Empty), + ex); + } catch (ServerlessThroughputNotSupportedException ex) { throw new CommandException("mkcon", MessageService.GetString("error-serverless_throughput_not_supported"), ex); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs index 988125cf..1045ffd1 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs @@ -66,7 +66,7 @@ public async Task CreateContainerAsync( string databaseName, string containerName, IReadOnlyList partitionKeyPaths, - string? uniqueKey, + IReadOnlyList>? uniqueKeys, string? indexPolicyJson, string? scale, int? maxRu, @@ -85,7 +85,7 @@ public async Task CreateContainerAsync( } } - var resource = await CosmosArmResourceProvider.CreateContainerAsync(context, databaseName, containerName, partitionKeyPaths, uniqueKey, parsedIndex, scale, maxRu, token); + var resource = await CosmosArmResourceProvider.CreateContainerAsync(context, databaseName, containerName, partitionKeyPaths, uniqueKeys, parsedIndex, scale, maxRu, token); return new ResourceCreationResult(resource.Data.Resource.ContainerName, ResourceCreationOutcome.CreatedOrUpdated); } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosArmResourceProvider.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosArmResourceProvider.cs index e1309046..adc3c4c4 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosArmResourceProvider.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosArmResourceProvider.cs @@ -236,7 +236,7 @@ public static async Task CreateContainerAsync( string databaseName, string containerName, IReadOnlyList partitionKeyPaths, - string? uniqueKey, + IReadOnlyList>? uniqueKeys, CosmosDBIndexingPolicy? indexingPolicy, string? scale, int? maxRu, @@ -257,10 +257,10 @@ public static async Task CreateContainerAsync( resource.PartitionKey.Paths.Add(path); } - if (!string.IsNullOrWhiteSpace(uniqueKey)) + foreach (var constraint in uniqueKeys ?? []) { var armUniqueKey = new CosmosDBUniqueKey(); - foreach (var path in uniqueKey.Split(",", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + foreach (var path in constraint) { armUniqueKey.Paths.Add(path); } @@ -278,7 +278,15 @@ public static async Task CreateContainerAsync( Options = CreateUpdateConfig(context.Account.Data, scale, maxRu), }; - var operation = await database.GetCosmosDBSqlContainers().CreateOrUpdateAsync(WaitUntil.Completed, containerName, content, token); + var containers = database.GetCosmosDBSqlContainers(); + + // ARM exposes only create-or-update. This preflight cannot exclude concurrent creators. + if (uniqueKeys is { Count: > 0 } && (await containers.GetIfExistsAsync(containerName, token)).HasValue) + { + throw new ExistingContainerUniqueKeyPolicyException(); + } + + var operation = await containers.CreateOrUpdateAsync(WaitUntil.Completed, containerName, content, token); return operation.Value; } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosResourceFacade.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosResourceFacade.cs index 14a5d4eb..c3ed3d87 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosResourceFacade.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CosmosResourceFacade.cs @@ -43,13 +43,13 @@ public static Task CreateContainerAsync( string databaseName, string containerName, IReadOnlyList partitionKeyPaths, - string? uniqueKey, + IReadOnlyList>? uniqueKeys, string? indexPolicyJson, string? scale, int? maxRu, CancellationToken token) { - return For(state).CreateContainerAsync(databaseName, containerName, partitionKeyPaths, uniqueKey, indexPolicyJson, scale, maxRu, token); + return For(state).CreateContainerAsync(databaseName, containerName, partitionKeyPaths, uniqueKeys, indexPolicyJson, scale, maxRu, token); } public static Task DeleteDatabaseAsync(ConnectedState state, string databaseName, CancellationToken token) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs index cf7aa04a..316d9bd5 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/DataPlaneCosmosResourceOperations.cs @@ -93,26 +93,13 @@ public async Task CreateContainerAsync( string databaseName, string containerName, IReadOnlyList partitionKeyPaths, - string? uniqueKey, + IReadOnlyList>? uniqueKeys, string? indexPolicyJson, string? scale, int? maxRu, CancellationToken token) { - var props = partitionKeyPaths.Count > 1 - ? new ContainerProperties(containerName, partitionKeyPaths.ToList()) - : new ContainerProperties(containerName, partitionKeyPaths[0]); - - if (!string.IsNullOrWhiteSpace(uniqueKey)) - { - var key = new UniqueKey(); - foreach (var path in uniqueKey.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) - { - key.Paths.Add(path); - } - - props.UniqueKeyPolicy.UniqueKeys.Add(key); - } + var props = BuildContainerProperties(containerName, partitionKeyPaths, uniqueKeys); if (!string.IsNullOrWhiteSpace(indexPolicyJson)) { @@ -125,6 +112,11 @@ public async Task CreateContainerAsync( maxRu, throughput => database.CreateContainerIfNotExistsAsync(props, throughput, cancellationToken: token)); RequestChargeContext.Record(response.RequestCharge); + if (response.StatusCode == HttpStatusCode.OK && uniqueKeys is { Count: > 0 }) + { + throw new ExistingContainerUniqueKeyPolicyException(); + } + if (response.StatusCode == HttpStatusCode.OK && CreationThroughput.IsSpecified(scale, maxRu)) { await ValidateExistingResourceThroughputAsync( @@ -134,6 +126,29 @@ await ValidateExistingResourceThroughputAsync( return new ResourceCreationResult(response.Container.Id, ToCreationOutcome(response.StatusCode)); } + internal static ContainerProperties BuildContainerProperties( + string containerName, + IReadOnlyList partitionKeyPaths, + IReadOnlyList>? uniqueKeys) + { + var properties = partitionKeyPaths.Count > 1 + ? new ContainerProperties(containerName, partitionKeyPaths.ToList()) + : new ContainerProperties(containerName, partitionKeyPaths[0]); + + foreach (var constraint in uniqueKeys ?? []) + { + var key = new UniqueKey(); + foreach (var path in constraint) + { + key.Paths.Add(path); + } + + properties.UniqueKeyPolicy.UniqueKeys.Add(key); + } + + return properties; + } + public async Task DeleteDatabaseAsync(string databaseName, CancellationToken token) { var response = await client.GetDatabase(databaseName).DeleteAsync(cancellationToken: token); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ExistingContainerUniqueKeyPolicyException.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ExistingContainerUniqueKeyPolicyException.cs new file mode 100644 index 00000000..5079c426 --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ExistingContainerUniqueKeyPolicyException.cs @@ -0,0 +1,7 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Core; + +internal sealed class ExistingContainerUniqueKeyPolicyException : Exception; diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ICosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ICosmosResourceOperations.cs index bd632d28..dda69034 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ICosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ICosmosResourceOperations.cs @@ -20,7 +20,7 @@ Task CreateContainerAsync( string databaseName, string containerName, IReadOnlyList partitionKeyPaths, - string? uniqueKey, + IReadOnlyList>? uniqueKeys, string? indexPolicyJson, string? scale, int? maxRu, diff --git a/CosmosDBShell/lang/en.ftl b/CosmosDBShell/lang/en.ftl index 14d87380..6fc26f08 100644 --- a/CosmosDBShell/lang/en.ftl +++ b/CosmosDBShell/lang/en.ftl @@ -668,7 +668,11 @@ command-mkdb-error-only_auto_or_manual_allowed = Only manual or autoscale are al command-mkcon-description = Creates a new container in the current database. command-mkcon-description-name = The container to create. command-mkcon-description-partition_key = The partition key path(s) for the container. Use a single path (e.g. /categoryId) or comma-separated paths for hierarchical partition keys (e.g. /tenantId,/userId or /tenantId,/userId,/sessionId). -command-mkcon-description-unique_key = The unique keys for the container to create. +command-mkcon-description-unique_key = Comma-separated paths for one composite unique-key constraint. Do not combine with --unique_key_policy. +command-mkcon-description-unique_key_policy = JSON policy with a uniqueKeys array. Each entry has a paths array and defines a separate constraint on a new container. Do not combine with unique_key. +command-mkcon-error_unique_key_policy_conflict = Specify either unique_key or --unique_key_policy, not both. +command-mkcon-error_invalid_unique_key_policy = Invalid unique-key policy. Supply a JSON object with 1 to 10 uniqueKeys entries, each with a nonempty paths array, and at most 16 paths in total. Paths within a constraint must be distinct and start with /. +command-mkcon-error_existing_unique_key_policy = Container '{ $container }' already exists. Unique-key policies can only be set when creating a new container. command-mkcon-description-scale = Container throughput mode (manual or auto). Not supported on serverless accounts. command-mkcon-description-ru = Container max RU/s (default: 1000; omitted on serverless accounts) command-mkcon-description-database = The database where the container should be created @@ -1006,6 +1010,8 @@ command-create-description-item = The object to create item, container or databa command-create-description-name = The container or database name to create. command-create-description-partition_key = { command-mkcon-description-partition_key } command-create-description-unique_key = { command-mkcon-description-unique_key } +command-create-description-unique_key_policy = { command-mkcon-description-unique_key_policy } +command-create-error_unique_key_policy_only_for_containers = The --unique_key_policy option is only valid for `create container`. command-create-description-scale = Throughput mode: manual (m) or auto. Databases default to no shared throughput; specify --scale or --ru to provision it. Containers default to auto. Not supported on serverless accounts. command-create-description-ru = Database or container RU/s (autoscale maximum in auto mode; default: 1000 when throughput is provisioned). Databases omit shared throughput unless --scale or --ru is specified. Not supported on serverless accounts. command-create-description-data = JSON data for the item to create diff --git a/docs/commands.md b/docs/commands.md index 9790187c..dde38615 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1096,11 +1096,12 @@ Usage: mkcon name partition_key [unique_key] [options] Arguments: name The container to create partition_key The partition key path. For hierarchical partition keys, use comma-separated paths such as /tenantId,/userId,/sessionId - [unique_key] Unique key paths (Optional) + [unique_key] Comma-separated paths for one composite unique-key constraint (optional) Options: --scale Throughput mode: manual (m) or auto (default) --ru Max RU/s (default: 1000) + --unique_key_policy JSON string defining independent and composite unique-key constraints Examples: mkcon Products /categoryId @@ -1111,6 +1112,27 @@ Unlike `mkdb`, container creation on provisioned accounts still defaults to dedi `create database` follows the `mkdb` defaults; `create container` follows the `mkcon` defaults. +Use `--unique_key_policy` on either container creation command to define more than +one unique-key constraint. Each `uniqueKeys` entry is independent; multiple paths +in a single entry constrain the combination. For example, this makes `/sku` +unique independently of the `/supplier` and `/externalCode` combination within +each logical partition: + +```text +mkcon Products /tenantId --database=ExampleShop --unique_key_policy='{"uniqueKeys":[{"paths":["/sku"]},{"paths":["/supplier","/externalCode"]}]}' +``` + +In MCP, pass the same JSON **as a string** in the `unique_key_policy` tool +argument. Do not combine it with the legacy `unique_key` positional argument, +whose comma-separated paths still define one composite constraint. A policy +can contain up to 10 constraints and 16 paths in total. + +Unique-key policies are creation-only. If you supply a policy and the container +already exists, the command reports an error instead of updating or recreating +it. ARM checks for an existing container before sending its create-or-update +request; avoid concurrent creation attempts for the same name because this +check is not atomic. + ### rmdb Remove database. diff --git a/l10n/CosmosDBShell.json b/l10n/CosmosDBShell.json index c482cf51..0bdd6a3b 100644 --- a/l10n/CosmosDBShell.json +++ b/l10n/CosmosDBShell.json @@ -301,11 +301,13 @@ "command-create-description-ru": "Database or container RU/s (autoscale maximum in auto mode; default: 1000 when throughput is provisioned). Databases omit shared throughput unless --scale or --ru is specified. Not supported on serverless accounts.", "command-create-description-scale": "Throughput mode: manual (m) or auto. Databases default to no shared throughput; specify --scale or --ru to provision it. Containers default to auto. Not supported on serverless accounts.", "command-create-description-unique_key": "{0}", + "command-create-description-unique_key_policy": "{0}", "command-create-error-container_name_required": "Create container requires a container name.", "command-create-error-database_name_required": "Create database requires a database name.", "command-create-error-force_only_for_items": "The --force/--upsert option is only valid for \u0060create item\u0060.", "command-create-error-invalid_item_type": "{0}", "command-create-error-partition_key_required": "Create container requires a partition key path that starts with \u0027/\u0027, for example: create container name /pk. Learn more: https://github.com/Azure/CosmosDBShell/blob/main/docs/commands.md#create", + "command-create-error_unique_key_policy_only_for_containers": "The --unique_key_policy option is only valid for \u0060create container\u0060.", "command-create-example-1": "Create a new container with partition key", "command-create-example-2": "Create database with autoscale throughput", "command-delete-description": "Delete items/container or databases.", @@ -626,10 +628,14 @@ "command-mkcon-description-partition_key": "The partition key path(s) for the container. Use a single path (e.g. /categoryId) or comma-separated paths for hierarchical partition keys (e.g. /tenantId,/userId or /tenantId,/userId,/sessionId).", "command-mkcon-description-ru": "Container max RU/s (default: 1000; omitted on serverless accounts)", "command-mkcon-description-scale": "Container throughput mode (manual or auto). Not supported on serverless accounts.", - "command-mkcon-description-unique_key": "The unique keys for the container to create.", + "command-mkcon-description-unique_key": "Comma-separated paths for one composite unique-key constraint. Do not combine with --unique_key_policy.", + "command-mkcon-description-unique_key_policy": "JSON policy with a uniqueKeys array. Each entry has a paths array and defines a separate constraint on a new container. Do not combine with unique_key.", + "command-mkcon-error_existing_unique_key_policy": "Container \u0027{0}\u0027 already exists. Unique-key policies can only be set when creating a new container.", "command-mkcon-error_invalid_index_policy": "Invalid indexing policy JSON. Please provide a valid Cosmos DB indexing policy.", + "command-mkcon-error_invalid_unique_key_policy": "Invalid unique-key policy. Supply a JSON object with 1 to 10 uniqueKeys entries, each with a nonempty paths array, and at most 16 paths in total. Paths within a constraint must be distinct and start with /.", "command-mkcon-error_partition_key_empty": "Partition key path cannot be empty. Provide a path that starts with \u0027/\u0027, for example: mkcon name /pk.", "command-mkcon-error_partition_key_slash": "Partition key path must start with a forward slash (/), for example: mkcon name /pk.", + "command-mkcon-error_unique_key_policy_conflict": "Specify either unique_key or --unique_key_policy, not both.", "command-mkcon-example-1": "Create container with single partition key", "command-mkcon-example-2": "Create container with hierarchical partition keys", "command-mkcon-example-3": "Create container with unique key constraint and autoscale throughput",