/// <inheritdoc/> public async Task <bool> AddManyAsync(IReadOnlyList <T> items) { var uri = UriFactory.CreateStoredProcedureUri(_databaseName, _collectionName, "bulkImport"); var count = await _client.ExecuteStoredProcedureAsync <int>(uri, items); return(count == items.Count); }
public async Task Document_AddManyCallsSP() { var model = new Test(); var models = new[] { model }; var uri = UriFactory.CreateStoredProcedureUri("DB", "DOC", "bulkImport"); var doc = new DocumentClientService.Document <Test>(_documentClient, "DB", "DOC"); _documentClient.ExecuteStoredProcedureAsync <int>(uri).ReturnsForAnyArgs(new StoredProcedureResponse <int>()); await doc.AddManyAsync(models); _documentClient.Received().ExecuteStoredProcedureAsync <int>(uri, Arg.Is(CheckModel(model))); }
public async Task GivenAStoredProcedureRequestWithLink_WithSessionConsistency_ThenTheResponseHeadersContainTheSessionToken() { _innerClient .ExecuteStoredProcedureAsync <int>("link", Arg.Is <RequestOptions>(o => o.ConsistencyLevel == ConsistencyLevel.Session)) .Returns(CosmosDbMockingHelper.CreateStoredProcedureResponse(42, HttpStatusCode.OK, new NameValueCollection { { CosmosDbHeaders.SessionToken, "2" } })); _requestHeaders.Add(CosmosDbHeaders.ConsistencyLevel, "Session"); _requestHeaders.Add(CosmosDbHeaders.SessionToken, "1"); await _fhirClient.ExecuteStoredProcedureAsync <int>("link"); await _cosmosResponseProcessor.Received(1).ProcessResponse(Arg.Any <StoredProcedureResponse <int> >()); }
public async Task GivenAStoredProcedureRequestWithLink_WithSessionConsistency_ThenTheResponseHeadersContainTheSessionToken() { _innerClient .ExecuteStoredProcedureAsync <int>("link", Arg.Is <RequestOptions>(o => o.ConsistencyLevel == ConsistencyLevel.Session)) .Returns(CreateStoredProcedureResponse(42, HttpStatusCode.OK, new NameValueCollection { { CosmosDbHeaders.SessionToken, "2" } })); _requestHeaders.Add(CosmosDbHeaders.ConsistencyLevel, "Session"); _requestHeaders.Add(CosmosDbHeaders.SessionToken, "1"); await _fhirClient.ExecuteStoredProcedureAsync <int>("link"); Assert.True(_responseHeaders.TryGetValue(CosmosDbHeaders.SessionToken, out var values)); Assert.Equal("2", values.ToString()); }
public async Task <TResult> ExecuteStoredProcedureAsync <TResult>(Domain.RequestOptions options, params dynamic[] procedureParams) where TResult : class { if (_databaseName == null) { throw new DataStoreException("Connect must be called to query CosmosDB"); } try { var response = await _client.ExecuteStoredProcedureAsync <TResult>( UriFactory.CreateStoredProcedureUri(_databaseName, _collectionName, _storedProcedureName), options.ToRequestOptions(), procedureParams); //Console.WriteLine("RU Charge " + response.RequestCharge); if (response.StatusCode != HttpStatusCode.OK) { return(null); } return(response.Response); } catch (DocumentClientException e) { if (e.StatusCode == HttpStatusCode.NotFound) { return(null); } throw; } }
public static async Task <StoredProcedureResponse <string> > HandleEntityMergeAsync(string tableName, TableOperationType operationType, string partitionKey, string ifMatch, IDocumentClient client, Document document, RequestOptions requestOptions, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Uri uri = UriFactory.CreateStoredProcedureUri("TablesDB", tableName, "__.sys.tablesBatchOperation"); List <Document> list = new List <Document>(); list.Add(document); List <TableOperationType> list2 = new List <TableOperationType>(); list2.Add(operationType); List <string> list3 = new List <string>(); list3.Add(ifMatch); AccessCondition accessCondition = null; if (operationType == TableOperationType.Merge) { accessCondition = new AccessCondition { Type = AccessConditionType.IfMatch, Condition = ifMatch }; } requestOptions = SetPartitionKey(requestOptions, partitionKey); requestOptions.AccessCondition = accessCondition; return(await client.ExecuteStoredProcedureAsync <string>(uri.ToString(), requestOptions, new object[3] { list.ToArray(), list2.ToArray(), list3.ToArray() })); }
private static async Task Execute_spHelloWorld(IDocumentClient client) { Console.WriteLine(); Console.WriteLine("Execute spHelloWorld stored procedure"); Uri uri = UriFactory.CreateStoredProcedureUri("mydb", "mystore", "spHelloWorld"); RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey(string.Empty) }; StoredProcedureResponse <string> result = await client.ExecuteStoredProcedureAsync <string>(uri, options); string message = result.Response; Console.WriteLine($"Result: {message}"); }
protected async Task <StoredProcedureResponse <T> > ExecuteStoredProc <T>(IDocumentClient client, Uri collection, string partitionId, params object[] parameters) { EnsureArg.IsNotNull(client, nameof(client)); EnsureArg.IsNotNull(collection, nameof(collection)); EnsureArg.IsNotNull(partitionId, nameof(partitionId)); var partitionKey = new RequestOptions { PartitionKey = new PartitionKey(partitionId), }; var results = await client.ExecuteStoredProcedureAsync <T>( GetUri(collection), partitionKey, parameters); return(results); }
private static async Task Execute_spBulkInsert(IDocumentClient client) { Console.WriteLine(); Console.WriteLine("Execute spBulkInsert"); List <dynamic> docs = new List <dynamic>(); const int total = 5000; for (int i = 1; i <= total; i++) { dynamic doc = new { name = $"Bulk inserted doc {i}", address = new { postalCode = "12345" } }; docs.Add(doc); } Uri uri = UriFactory.CreateStoredProcedureUri("mydb", "mystore", "spBulkInsert"); RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey("12345") }; int totalInserted = 0; while (totalInserted < total) { StoredProcedureResponse <int> result = await client.ExecuteStoredProcedureAsync <int>(uri, options, docs); int inserted = result.Response; totalInserted += inserted; int remaining = total - totalInserted; Console.WriteLine($"Inserted {inserted} documents ({totalInserted} total, {remaining} remaining)"); docs = docs.GetRange(inserted, docs.Count - inserted); } }
private static async Task <int> Execute_spBulkDelete(IDocumentClient client, string sql) { Uri uri = UriFactory.CreateStoredProcedureUri("mydb", "mystore", "spBulkDelete"); RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey("12345") }; bool continuationFlag = true; int totalDeleted = 0; while (continuationFlag) { StoredProcedureResponse <BulkDeleteResponse> result = await client.ExecuteStoredProcedureAsync <BulkDeleteResponse>(uri, options, sql); BulkDeleteResponse response = result.Response; continuationFlag = response.ContinuationFlag; int deleted = response.Count; totalDeleted += deleted; Console.WriteLine($"Deleted {deleted} documents ({totalDeleted} total, more: {continuationFlag})"); } return(totalDeleted); }
public async Task <string> ExecuteStoredProcedureAsync(string storedProcedureName, params dynamic[] parameters) { var sproc = _client.CreateStoredProcedureQuery(_collection.SelfLink).Where(sp => sp.Id == storedProcedureName).AsEnumerable().First(); return(await _client.ExecuteStoredProcedureAsync <string>(sproc.SelfLink, parameters)); }
//public async Task<ResourceResponse<Document>> Load( // IAmDocument doc) //{ // var r = await this.client.CreateDocumentAsync( // UriFactory.CreateDocumentUri( // databaseId, // collectionId, // doc.Id), // doc); // // return r; //} /// <summary> /// Loads multple IAmDocuments, split by partitionKey, using /// the bulkImport stored procedure. The stored procedure is /// not generated so must be created. Function fails if stored /// procedure is not found /// </summary> /// <remarks>Assumed name of stored procedure is "bulkImport"</remarks> /// <param name="docs"></param> /// <returns></returns> public async Task <StoredProcedureResponse <bool>[]> LoadBulk( IEnumerable <IAmDocument> docs) { // TODO: Replace with BulkExecutor once it's netstandard2 complient //List<Task<StoredProcedureResponse<bool>>> tasks = // new List<Task<StoredProcedureResponse<bool>>>(); var groupedDocs = docs.GroupBy(d => d.PartitionKey); List <StoredProcedureResponse <bool> > results = new List <StoredProcedureResponse <bool> >(); foreach (var groupedDoc in groupedDocs) { try { //tasks.Add(client.ExecuteStoredProcedureAsync<bool>( // $"/dbs/{databaseId}/colls/{collectionId}/sprocs/bulkImport/", // new RequestOptions // { // PartitionKey = // new PartitionKey( // groupedDoc.Key.ToString()) // }, // groupedDoc)); results.Add(await client.ExecuteStoredProcedureAsync <bool>( $"/dbs/{databaseId}/colls/{collectionId}/sprocs/bulkImport/", new RequestOptions { PartitionKey = new PartitionKey( groupedDoc.Key.ToString()) }, groupedDoc)); } catch (Exception e) { throw new Exception( $"Error initializing tasks for bulk import on groupedDoc {groupedDoc.Key.ToString()} with {groupedDoc.Count().ToString()} measurements.", e); } } //StoredProcedureResponse<bool>[] result; //try //{ // result = await Task.WhenAll(tasks); //} //catch(Exception e) //{ // IEnumerable<Exception> exceptions = tasks // .Where(t => t.Exception != null) // .Select(t => t.Exception); // Exception exampleException = exceptions.FirstOrDefault(); // string exceptionMessage = // exampleException.InnerException != null // ? exampleException.InnerException.Message // : exampleException.Message; // // throw new Exception( // $"{exceptions.Count().ToString()} stored procedures failed out of a total of {tasks.Count()} sprocs for {docs.Count()} measurements. Example exception message from first exception: {exceptionMessage}", // e); //} return(results.ToArray()); }
public async Task <dynamic> ExecuteStoredProcedureAsync(string collectionId, string storedProcName, params dynamic[] procedureParams) { return(await documentClient.ExecuteStoredProcedureAsync <dynamic>(UriFactory.CreateStoredProcedureUri(cosmosDbSettings.DatabaseId, collectionId, storedProcName), procedureParams)); }