public void TransactionReadAndWrite() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; long amount = 1000L; Key fromKey = CreateAccount("Jill", 20000L); Key toKey = CreateAccount("Beth", 15500L); // Sample: TransactionReadAndWrite DatastoreClient client = DatastoreClient.Create(); ByteString transactionId = client.BeginTransaction(projectId).Transaction; using (DatastoreTransaction transaction = DatastoreTransaction.Create(client, projectId, namespaceId, transactionId)) { // The return value from DatastoreTransaction.Get contains the fetched entities // in the same order as they are in the call. IReadOnlyList <Entity> entities = transaction.Lookup(fromKey, toKey); Entity from = entities[0]; Entity to = entities[1]; from["balance"] = (long)from["balance"] - amount; to["balance"] = (long)to["balance"] - amount; transaction.Update(from); transaction.Update(to); transaction.Commit(); } // End sample }
/// <summary> /// Create a new datastore-backed bookstore. /// </summary> /// <param name="projectId">Your Google Cloud project id</param> public DatastoreBookStore(string projectId) { _projectId = projectId; var client = DatastoreClient.Create(new Channel(emulatorHost, emulatorPort, ChannelCredentials.Insecure)); _db = DatastoreDb.Create(_projectId, namespaceId, client); }
public void CompositeFilterQuery() { string projectId = _fixture.ProjectId; PartitionId partitionId = _fixture.PartitionId; // Sample: CompositeFilter Query query = new Query("Task") { Filter = Filter.And( Filter.Equal("done", false), Filter.GreaterThanOrEqual("priority", 4) ), Order = { { "priority", Direction.Descending } } }; DatastoreClient client = DatastoreClient.Create(); RunQueryRequest request = new RunQueryRequest { ProjectId = projectId, PartitionId = partitionId, ReadOptions = new ReadOptions { ReadConsistency = ReadConsistency.Eventual }, Query = query }; RunQueryResponse response = client.RunQuery(request); foreach (EntityResult result in response.Batch.EntityResults) { Entity entity = result.Entity; Console.WriteLine((string)entity["description"]); } // TODO: Results beyond this batch? // End sample }
public void DeleteEntity() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Copied from InsertEntity; we want to create a new one to delete. KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "Task"); Entity entity = new Entity { Key = keyFactory.CreateIncompleteKey(), ["category"] = "Personal", ["done"] = false, ["priority"] = 4, ["description"] = "Learn Cloud Datastore", ["percent_complete"] = 75.0 }; DatastoreClient insertClient = DatastoreClient.Create(); CommitResponse response = insertClient.Commit(projectId, Mode.NonTransactional, new[] { entity.ToInsert() }); Key key = response.MutationResults[0].Key; // Sample: DeleteEntity DatastoreClient client = DatastoreClient.Create(); // If you have an entity instead of just a key, then entity.ToDelete() would work too. CommitResponse commit = insertClient.Commit(projectId, Mode.NonTransactional, new[] { key.ToDelete() }); // End sample }
public void PropertyQuery() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; PartitionId partitionId = new PartitionId(projectId, namespaceId); // Sample: PropertyQuery DatastoreClient client = DatastoreClient.Create(); RunQueryRequest request = new RunQueryRequest { ProjectId = projectId, PartitionId = partitionId, Query = new Query(DatastoreConstants.PropertyKind) { Projection = { DatastoreConstants.KeyProperty } } }; RunQueryResponse response = client.RunQuery(request); foreach (EntityResult result in response.Batch.EntityResults) { Key key = result.Entity.Key; string propertyName = key.Path.Last().Name; string kind = key.GetParent().Path.Last().Name; Console.WriteLine($"Kind: {kind}; Property: {propertyName}"); } // End sample }
public void Lookup() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Lookup(*,*,*,*) KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "book"); Key key1 = keyFactory.CreateKey("pride_and_prejudice"); Key key2 = keyFactory.CreateKey("not_present"); DatastoreClient client = DatastoreClient.Create(); LookupResponse response = client.Lookup( projectId, new ReadOptions { ReadConsistency = ReadConsistency.Strong }, new[] { key1, key2 }); Console.WriteLine($"Found: {response.Found.Count}"); Console.WriteLine($"Deferred: {response.Deferred.Count}"); Console.WriteLine($"Missing: {response.Missing.Count}"); // End snippet Entity entity = response.Found[0].Entity; Assert.Equal("Jane Austen", (string)entity["author"]); Assert.Equal("Pride and Prejudice", (string)entity["title"]); }
public void PaginateWithCursor() { string projectId = _fixture.ProjectId; PartitionId partitionId = _fixture.PartitionId; ByteString pageCursor = null; int pageSize = 5; // Sample: PaginateWithCursor RunQueryRequest request = new RunQueryRequest { ProjectId = projectId, PartitionId = partitionId, ReadOptions = new ReadOptions { ReadConsistency = ReadConsistency.Eventual }, Query = new Query("Task") { Limit = pageSize, StartCursor = pageCursor ?? ByteString.Empty } }; DatastoreClient client = DatastoreClient.Create(); RunQueryResponse response = client.RunQuery(request); foreach (EntityResult result in response.Batch.EntityResults) { Entity entity = result.Entity; // Do something with the task entity } ByteString nextPageCursor = response.Batch.EndCursor; // End sample }
public void GqlQuery() { string projectId = _fixture.ProjectId; PartitionId partitionId = _fixture.PartitionId; // Snippet: RunQuery(string,PartitionId,ReadOptions,GqlQuery,CallSettings) DatastoreClient client = DatastoreClient.Create(); GqlQuery gqlQuery = new GqlQuery { QueryString = "SELECT * FROM book WHERE author = @author", NamedBindings = { { "author", new GqlQueryParameter { Value = "Jane Austen" } } }, }; RunQueryResponse response = client.RunQuery( projectId, partitionId, new ReadOptions { ReadConsistency = ReadConsistency.Eventual }, gqlQuery); foreach (EntityResult result in response.Batch.EntityResults) { Console.WriteLine(result.Entity); } // End snippet Assert.Equal(1, response.Batch.EntityResults.Count); Entity entity = response.Batch.EntityResults[0].Entity; Assert.Equal("Jane Austen", (string)entity["author"]); Assert.Equal("Pride and Prejudice", (string)entity["title"]); }
public void StructuredQuery() { string projectId = _fixture.ProjectId; PartitionId partitionId = _fixture.PartitionId; // Snippet: RunQuery(string,PartitionId,ReadOptions,Query,CallSettings) DatastoreClient client = DatastoreClient.Create(); Query query = new Query("book") { Filter = Filter.Equal("author", "Jane Austen") }; RunQueryResponse response = client.RunQuery( projectId, partitionId, new ReadOptions { ReadConsistency = ReadConsistency.Eventual }, query); foreach (EntityResult result in response.Batch.EntityResults) { Console.WriteLine(result.Entity); } // End snippet Assert.Equal(1, response.Batch.EntityResults.Count); Entity entity = response.Batch.EntityResults[0].Entity; Assert.Equal("Jane Austen", (string)entity["author"]); Assert.Equal("Pride and Prejudice", (string)entity["title"]); }
public void ProjectionQuery() { string projectId = _fixture.ProjectId; PartitionId partitionId = _fixture.PartitionId; // Sample: ProjectionQuery RunQueryRequest request = new RunQueryRequest { ProjectId = projectId, PartitionId = partitionId, Query = new Query("Task") { Projection = { "priority", "percentage_complete" } } }; DatastoreClient client = DatastoreClient.Create(); RunQueryResponse response = client.RunQuery(request); foreach (EntityResult result in response.Batch.EntityResults) { Entity entity = result.Entity; Console.WriteLine($"{(int)entity["priority"]}: {(double?)entity["percentage_complete"]}"); } // End sample }
public void Overview() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: Overview DatastoreClient client = DatastoreClient.Create(); KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "message"); Entity entity = new Entity { Key = keyFactory.CreateIncompleteKey(), ["created"] = DateTime.UtcNow, ["text"] = "Text of the message", ["tags"] = new[] { "tag1", "tag2" } }; ByteString transactionId = client.BeginTransaction(projectId).Transaction; using (DatastoreTransaction transaction = DatastoreTransaction.Create(client, projectId, namespaceId, transactionId)) { transaction.Insert(entity); CommitResponse commitResponse = transaction.Commit(); Key insertedKey = commitResponse.MutationResults[0].Key; Console.WriteLine($"Inserted key: {insertedKey}"); } // End sample }
protected virtual DatastoreClient GetClient() { var url = ToUri(GetConnectionString()); return(DatastoreClient.Create( new Channel(url.Host, url.Port, ChannelCredentials.Insecure), DatastoreSettings.GetDefault() )); }
public void BeginTransaction() { // Snippet: BeginTransaction(string,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; // Make the request BeginTransactionResponse response = datastoreClient.BeginTransaction(projectId); // End snippet }
public void Rollback() { // Snippet: Rollback(string,ByteString,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; ByteString transaction = ByteString.CopyFromUtf8(""); // Make the request RollbackResponse response = datastoreClient.Rollback(projectId, transaction); // End snippet }
/// <summary>Snippet for ReserveIds</summary> public void ReserveIds() { // Snippet: ReserveIds(string, IEnumerable<Key>, CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; IEnumerable <Key> keys = new Key[] { new Key(), }; // Make the request ReserveIdsResponse response = datastoreClient.ReserveIds(projectId, keys); // End snippet }
public EmulatedDatastoreDbProvider(IConfigurationService configurationService, IDataEntityObjectFactory dataEntityObjectFactory) { var host = configurationService.Get("DATASTOREDB_HOST"); var project = configurationService.Get("DATASTOREDB_PROJECT"); var port = Convert.ToInt32(configurationService.Get("DATASTOREDB_PORT")); var channel = new Channel(host, port, ChannelCredentials.Insecure); var client = DatastoreClient.Create(channel); _db = DatastoreDb.Create(project, "", client); _dataEntityObjectFactory = dataEntityObjectFactory; }
public void AllocateIds() { // Snippet: AllocateIds(string,IEnumerable<Key>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; IEnumerable <Key> keys = new List <Key>(); // Make the request AllocateIdsResponse response = datastoreClient.AllocateIds(projectId, keys); // End snippet }
public async Task BeginTransactionAsync() { // Snippet: BeginTransactionAsync(string,CallSettings) // Additional: BeginTransactionAsync(string,CancellationToken) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; // Make the request BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(projectId); // End snippet }
public void Lookup() { // Snippet: Lookup(string,ReadOptions,IEnumerable<Key>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; ReadOptions readOptions = new ReadOptions(); IEnumerable <Key> keys = new List <Key>(); // Make the request LookupResponse response = datastoreClient.Lookup(projectId, readOptions, keys); // End snippet }
public void Commit2() { // Snippet: Commit(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; IEnumerable <Mutation> mutations = new List <Mutation>(); // Make the request CommitResponse response = datastoreClient.Commit(projectId, mode, mutations); // End snippet }
public void RunQuery2() { // Snippet: RunQuery(string,PartitionId,ReadOptions,GqlQuery,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; PartitionId partitionId = new PartitionId(); ReadOptions readOptions = new ReadOptions(); GqlQuery gqlQuery = new GqlQuery(); // Make the request RunQueryResponse response = datastoreClient.RunQuery(projectId, partitionId, readOptions, gqlQuery); // End snippet }
private DatastoreClient InitDatastoreClient() { GoogleCredential googleCredential; var scopes = new string[] { "https://www.googleapis.com/auth/datastore" }; using (var stream = new FileStream(_gcpSettings.NoSQL.JsonAuthPath, FileMode.Open, FileAccess.Read)) { googleCredential = GoogleCredential.FromStream(stream).CreateScoped(scopes); } var channel = new Channel(DatastoreClient.DefaultEndpoint.ToString(), googleCredential.ToChannelCredentials()); return(DatastoreClient.Create(channel)); }
public void BeginTransaction_RequestObject() { // Snippet: BeginTransaction(BeginTransactionRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) BeginTransactionRequest request = new BeginTransactionRequest { ProjectId = "", }; // Make the request BeginTransactionResponse response = datastoreClient.BeginTransaction(request); // End snippet }
public async Task AllocateIdsAsync() { // Snippet: AllocateIdsAsync(string,IEnumerable<Key>,CallSettings) // Additional: AllocateIdsAsync(string,IEnumerable<Key>,CancellationToken) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; IEnumerable <Key> keys = new List <Key>(); // Make the request AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(projectId, keys); // End snippet }
public async Task RollbackAsync() { // Snippet: RollbackAsync(string,ByteString,CallSettings) // Additional: RollbackAsync(string,ByteString,CancellationToken) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; ByteString transaction = ByteString.CopyFromUtf8(""); // Make the request RollbackResponse response = await datastoreClient.RollbackAsync(projectId, transaction); // End snippet }
public void RunQuery() { string projectId = _fixture.ProjectId; PartitionId partitionId = _fixture.PartitionId; // Snippet: RunQuery(RunQueryRequest,*) DatastoreClient client = DatastoreClient.Create(); RunQueryRequest request = new RunQueryRequest { ProjectId = projectId, PartitionId = partitionId, ReadOptions = new ReadOptions { ReadConsistency = ReadConsistency.Eventual }, }; // Structured query request.Query = new Query("book") { Filter = Filter.Equal("author", "Jane Austen") }; RunQueryResponse response = client.RunQuery(request); foreach (EntityResult result in response.Batch.EntityResults) { Console.WriteLine(result.Entity); } // Equivalent GQL query request.GqlQuery = new GqlQuery { QueryString = "SELECT * FROM book WHERE author = @author", NamedBindings = { { "author", new GqlQueryParameter { Value = "Jane Austen" } } }, }; foreach (EntityResult result in response.Batch.EntityResults) { Console.WriteLine(result.Entity); } // End snippet Assert.Equal(1, response.Batch.EntityResults.Count); Entity entity = response.Batch.EntityResults[0].Entity; Assert.Equal("Jane Austen", (string)entity["author"]); Assert.Equal("Pride and Prejudice", (string)entity["title"]); }
public void Rollback_RequestObject() { // Snippet: Rollback(RollbackRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) RollbackRequest request = new RollbackRequest { ProjectId = "", Transaction = ByteString.CopyFromUtf8(""), }; // Make the request RollbackResponse response = datastoreClient.Rollback(request); // End snippet }
public override void Dispose() { var client = DatastoreClient.Create(); // Delete all the entities in our partition. // TODO: Transactions? Paging? var query = new Query { Projection = { DatastoreConstants.KeyProperty } }; var response = client.RunQuery(new RunQueryRequest { ProjectId = ProjectId, PartitionId = PartitionId, Query = query }); var deletions = response.Batch.EntityResults.Select(entityResult => entityResult.Entity.ToDelete()); client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, deletions); }
public void AllocateIds_RequestObject() { // Snippet: AllocateIds(AllocateIdsRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) AllocateIdsRequest request = new AllocateIdsRequest { ProjectId = "", Keys = { }, }; // Make the request AllocateIdsResponse response = datastoreClient.AllocateIds(request); // End snippet }
private void AddSampleBooks() { var client = DatastoreClient.Create(); var keyFactory = new KeyFactory(ProjectId, NamespaceId, BookKind); var entity = new Entity { Key = keyFactory.CreateKey("pride_and_prejudice"), ["title"] = "Pride and Prejudice", ["publication_date"] = new DateTime(1813, 1, 28, 0, 0, 0, DateTimeKind.Utc), ["author"] = "Jane Austen" }; var response = client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, new[] { entity.ToInsert() }); _prideAndPrejudiceKey = response.MutationResults[0].Key; }