/// <summary> /// <para>Check if a database exists, and if it doesn't, create it. /// Only the database id is used to verify if there is an existing database. Other database properties /// such as throughput are not validated and can be different then the passed properties.</para> /// /// <para>A database manages users, permissions and a set of containers. /// Each Azure Cosmos DB Database Account is able to support multiple independent named databases, /// with the database being the logical container for data.</para> /// /// <para>Each Database consists of one or more containers, each of which in turn contain one or more /// documents. Since databases are an administrative resource, the Service Master Key will be /// required in order to access and successfully complete any action using the User APIs.</para> /// </summary> /// <param name="id">The database id.</param> /// <param name="throughput">(Optional) The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.</param> /// <param name="requestOptions">(Optional) A set of additional options that can be set.</param> /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param> /// <returns>A <see cref="Task"/> containing a <see cref="DatabaseResponse"/> which wraps a <see cref="DatabaseProperties"/> containing the resource record. /// <list type="table"> /// <listheader> /// <term>StatusCode</term><description>Common success StatusCodes for the CreateDatabaseIfNotExistsAsync operation</description> /// </listheader> /// <item> /// <term>201</term><description>Created - New database is created.</description> /// </item> /// <item> /// <term>200</term><description>Accepted - This means the database already exists.</description> /// </item> /// </list> /// </returns> /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/request-units">Request Units</seealso> public virtual async Task <DatabaseResponse> CreateDatabaseIfNotExistsAsync( string id, int?throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException(nameof(id)); } // Doing a Read before Create will give us better latency for existing databases DatabaseProperties databaseProperties = this.PrepareDatabaseProperties(id); Database database = this.GetDatabase(id); ResponseMessage response = await database.ReadStreamAsync(requestOptions : requestOptions, cancellationToken : cancellationToken); if (response.StatusCode != HttpStatusCode.NotFound) { return(await this.ClientContext.ResponseFactory.CreateDatabaseResponseAsync(database, Task.FromResult(response))); } response = await this.CreateDatabaseStreamAsync(databaseProperties, throughput, requestOptions, cancellationToken); if (response.StatusCode != HttpStatusCode.Conflict) { return(await this.ClientContext.ResponseFactory.CreateDatabaseResponseAsync(this.GetDatabase(databaseProperties.Id), Task.FromResult(response))); } // This second Read is to handle the race condition when 2 or more threads have Read the database and only one succeeds with Create // so for the remaining ones we should do a Read instead of throwing Conflict exception return(await database.ReadAsync(cancellationToken : cancellationToken)); }
/// <summary> /// <para>Check if a database exists, and if it doesn't, create it. /// Only the database id is used to verify if there is an existing database. Other database properties /// such as throughput are not validated and can be different then the passed properties.</para> /// /// <para>A database manages users, permissions and a set of containers. /// Each Azure Cosmos DB Database Account is able to support multiple independent named databases, /// with the database being the logical container for data.</para> /// /// <para>Each Database consists of one or more containers, each of which in turn contain one or more /// documents. Since databases are an administrative resource, the Service Master Key will be /// required in order to access and successfully complete any action using the User APIs.</para> /// </summary> /// <param name="id">The database id.</param> /// <param name="throughput">(Optional) The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.</param> /// <param name="requestOptions">(Optional) A set of additional options that can be set.</param> /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param> /// <returns>A <see cref="Task"/> containing a <see cref="DatabaseResponse"/> which wraps a <see cref="DatabaseProperties"/> containing the resource record. /// <list type="table"> /// <listheader> /// <term>StatusCode</term><description>Common success StatusCodes for the CreateDatabaseIfNotExistsAsync operation</description> /// </listheader> /// <item> /// <term>201</term><description>Created - New database is created.</description> /// </item> /// <item> /// <term>200</term><description>Accepted - This means the database already exists.</description> /// </item> /// </list> /// </returns> /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/request-units">Request Units</seealso> public virtual Task <DatabaseResponse> CreateDatabaseIfNotExistsAsync( string id, int?throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { this.ThrowIfDisposed(); if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException(nameof(id)); } return(TaskHelper.RunInlineIfNeededAsync(async() => { // Doing a Read before Create will give us better latency for existing databases DatabaseProperties databaseProperties = this.PrepareDatabaseProperties(id); Database database = this.GetDatabase(id); ResponseMessage readResponse = await database.ReadStreamAsync( requestOptions: requestOptions, cancellationToken: cancellationToken); if (readResponse.StatusCode != HttpStatusCode.NotFound) { return await this.ClientContext.ResponseFactory.CreateDatabaseResponseAsync(database, Task.FromResult(readResponse)); } ResponseMessage createResponse = await this.CreateDatabaseStreamAsync(databaseProperties, throughput, requestOptions, cancellationToken); // Merge the diagnostics with the first read request. createResponse.DiagnosticsContext.AddDiagnosticsInternal(readResponse.DiagnosticsContext); if (createResponse.StatusCode != HttpStatusCode.Conflict) { return await this.ClientContext.ResponseFactory.CreateDatabaseResponseAsync(this.GetDatabase(databaseProperties.Id), Task.FromResult(createResponse)); } // This second Read is to handle the race condition when 2 or more threads have Read the database and only one succeeds with Create // so for the remaining ones we should do a Read instead of throwing Conflict exception ResponseMessage readResponseAfterConflict = await database.ReadStreamAsync( requestOptions: requestOptions, cancellationToken: cancellationToken); readResponseAfterConflict.DiagnosticsContext.AddDiagnosticsInternal(readResponse.DiagnosticsContext); return await this.ClientContext.ResponseFactory.CreateDatabaseResponseAsync(this.GetDatabase(databaseProperties.Id), Task.FromResult(readResponseAfterConflict)); })); }