public void EagerGqlQuery() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: RunQuery(GqlQuery,*) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("player"); // Prepare the data: a player with two game child entities Entity player = new Entity { Key = keyFactory.CreateIncompleteKey(), ["name"] = "Sophie" }; Key playerKey = db.Insert(player); Entity game1 = new Entity { Key = playerKey.WithElement(new PathElement { Kind = "game" }), ["score"] = 10, ["timestamp"] = new DateTime(2017, 2, 16, 8, 35, 0, DateTimeKind.Utc) }; Entity game2 = new Entity { Key = playerKey.WithElement(new PathElement { Kind = "game" }), ["score"] = 25, ["timestamp"] = new DateTime(2017, 3, 15, 10, 35, 0, DateTimeKind.Utc) }; db.Insert(game1, game2); // Perform a query within a transaction using (DatastoreTransaction transaction = db.BeginTransaction()) { // Any query executed in a transaction must at least have an ancestor filter. GqlQuery query = new GqlQuery { QueryString = "SELECT * FROM game WHERE __key__ HAS ANCESTOR @player LIMIT @limit", NamedBindings = { { "player", playerKey }, { "limit", 10 } } }; DatastoreQueryResults results = db.RunQuery(query); // RunQuery fetches all the results into memory in a single call. // Constrast this with RunQueryLazily, which merely prepares an enumerable // query. Always specify a limit when you use RunQuery, to avoid running // out of memory. foreach (Entity entity in results.Entities) { Console.WriteLine(entity); } } // End snippet }
public void LazyGqlQuery() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: RunQueryLazily(GqlQuery,*) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("player"); // Prepare the data: a player with two game child entities Entity player = new Entity { Key = keyFactory.CreateIncompleteKey(), ["name"] = "Sophie" }; Key playerKey = db.Insert(player); Entity game1 = new Entity { Key = playerKey.WithElement(new PathElement { Kind = "game" }), ["score"] = 10, ["timestamp"] = new DateTime(2017, 2, 16, 8, 35, 0, DateTimeKind.Utc) }; Entity game2 = new Entity { Key = playerKey.WithElement(new PathElement { Kind = "game" }), ["score"] = 25, ["timestamp"] = new DateTime(2017, 3, 15, 10, 35, 0, DateTimeKind.Utc) }; db.Insert(game1, game2); // Perform a query within a transaction using (DatastoreTransaction transaction = db.BeginTransaction()) { // Any query executed in a transaction must at least have an ancestor filter. GqlQuery query = new GqlQuery { QueryString = "SELECT * FROM game WHERE __key__ HAS ANCESTOR @player", NamedBindings = { { "player", playerKey } } }; LazyDatastoreQuery results = db.RunQueryLazily(query); // LazyDatastoreQuery implements IEnumerable<Entity>, but you can // call AsResponses() to see the raw RPC responses, or // GetAllResults() to get all the results into memory, complete with // the end cursor and the reason for the query finishing. foreach (Entity entity in results) { Console.WriteLine(entity); } } // End snippet }
static void Main(string[] args) { string projectId = "YOUR-PROJECT-ID-HERE"; DatastoreDb client = DatastoreDb.Create(projectId); Entity shelf = new Entity { Key = client.CreateKeyFactory("shelf").CreateIncompleteKey(), ["genre"] = "fiction" }; Key shelfKey = client.Insert(shelf); // Insert a book specifying a complete key Entity book1 = new Entity { Key = shelfKey.WithElement("book", "potter1"), ["title"] = "Harry Potter and the Philosopher's Stone" }; Key book1Key = client.Insert(book1); // Insert a book by creating an incomplete key with the extension method Entity book2 = new Entity { Key = shelfKey.WithIncompleteElement("book"), ["title"] = "Harry Potter and the Chamber of Secrets" }; Key book2Key = client.Insert(book2); Console.WriteLine($"Inserted key: {book2Key}"); // Insert a book by creating an incomplete key with a KeyFactory KeyFactory keyFactory = new KeyFactory(shelf, "book"); Entity book3 = new Entity { Key = keyFactory.CreateIncompleteKey(), ["title"] = "Harry Potter and the Prisoner of Azkaban" }; Key book3Key = client.Insert(book3); Console.WriteLine($"Inserted key: {book3Key}"); Console.WriteLine(); // List all the books var books = client.RunQuery(new Query { Kind = { new KindExpression { Name = "book" } } }); Console.WriteLine("All books:"); foreach (var book in books.Entities) { Console.WriteLine($"{(string) book["title"]}: Key={book.Key}"); } }
public TKey InsertOne(TEntity dsEntity) { var entity = BuildEntity(dsEntity); var keys = _database.Insert(new[] { entity }); if (keys.Any() && keys[0] == null) { return(GetId(dsEntity)); } // Auto-generated key - set the key property under the entity var id = GetId(keys.FirstOrDefault()); SetId(dsEntity, id); return(id); }
public void TestInsert() { // [START insert] Entity task = new Entity() { Key = _keyFactory.CreateIncompleteKey() }; task.Key = _db.Insert(task); // [END insert] Assert.Equal(task, _db.Lookup(task.Key)); // Make sure a second insert throws an exception. Grpc.Core.RpcException e = Assert.Throws <Grpc.Core.RpcException>(() => _db.Insert(task)); }
public Key AddUser(User user) { DateTime dateTime = DateTime.SpecifyKind(DateTime.ParseExact(user.Dob, "dd/MM/yyyy", CultureInfo.InvariantCulture), DateTimeKind.Utc); Entity entity = new Entity() { Key = _keyFactory.CreateIncompleteKey(), ["name"] = new Value() { StringValue = user.Name }, ["surname"] = new Value() { StringValue = user.Surname }, ["gender"] = new Value() { StringValue = user.Gender }, ["dob"] = new Value() { StringValue = user.Dob }, ["dob_timestamp"] = new Value() { TimestampValue = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(dateTime) } }; return(_db.Insert(entity)); }
public void AddEntity_NonTransactional() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Insert(Entity[]) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("book"); Entity book1 = new Entity { Key = keyFactory.CreateIncompleteKey(), ["author"] = "Harper Lee", ["title"] = "To Kill a Mockingbird", ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc), ["genres"] = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" } }; Entity book2 = new Entity { Key = keyFactory.CreateIncompleteKey(), ["author"] = "Charlotte Brontë", ["title"] = "Jane Eyre", ["publication_date"] = new DateTime(1847, 10, 16, 0, 0, 0, DateTimeKind.Utc), ["genres"] = new[] { "Gothic", "Romance", "Bildungsroman" } }; IReadOnlyList <Key> insertedKeys = db.Insert(book1, book2); Console.WriteLine($"Inserted keys: {string.Join(",", insertedKeys)}"); // End snippet }
public void DeleteKey() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Delete(Key, *) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); Entity message = new Entity { Key = keyFactory.CreateIncompleteKey(), ["text"] = "Hello", }; Key key = db.Insert(message); Entity fetchedBeforeDeletion = db.Lookup(key); // Only the key is required to determine what to delete. // If you have an entity with the right key, you can use Delete(Entity, CallSettings) // or a similar overload for convenience. db.Delete(key); Entity fetchedAfterDeletion = db.Lookup(key); Console.WriteLine($"Entity exists before deletion? {fetchedBeforeDeletion != null}"); Console.WriteLine($"Entity exists after deletion? {fetchedAfterDeletion != null}"); // End snippet Assert.NotNull(fetchedBeforeDeletion); Assert.Null(fetchedAfterDeletion); }
public void DeleteEntity() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: DeleteEntity // Additional: Delete(Entity, *) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); Entity message = new Entity { Key = keyFactory.CreateIncompleteKey(), ["text"] = "Hello", }; db.Insert(message); Entity fetchedBeforeDeletion = db.Lookup(message.Key); // Only the key from the entity is used to determine what to delete. // If you already have the key but not the entity, use Delete(Key, CallSettings) or // a similar overload. db.Delete(message); Entity fetchedAfterDeletion = db.Lookup(message.Key); Console.WriteLine($"Entity exists before deletion? {fetchedBeforeDeletion != null}"); Console.WriteLine($"Entity exists after deletion? {fetchedAfterDeletion != null}"); // End snippet Assert.NotNull(fetchedBeforeDeletion); Assert.Null(fetchedAfterDeletion); }
public void Update() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Update(Entity, CallSettings) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("book"); Entity book = new Entity { Key = keyFactory.CreateIncompleteKey(), ["author"] = "Harper Lee", ["title"] = "Tequila Mockingbird", ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc), ["genres"] = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" } }; db.Insert(book); // Correct the typo in memory book["title"] = "To Kill a Mockingbird"; // Then update the entity in Datastore db.Update(book); // End snippet var fetched = db.Lookup(book.Key); Assert.Equal("To Kill a Mockingbird", (string)fetched["title"]); }
public void DeleteEntity() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Copied from InsertEntity; we want to create a new one to delete. DatastoreDb insertClient = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = insertClient.CreateKeyFactory("Task"); Entity entity = new Entity { Key = keyFactory.CreateIncompleteKey(), ["category"] = "Personal", ["done"] = false, ["priority"] = 4, ["description"] = "Learn Cloud Datastore", ["percent_complete"] = 75.0 }; Key insertedKey = insertClient.Insert(entity); // Sample: DeleteEntity DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); // If you have an entity instead of just a key, then entity.ToDelete() would work too. db.Delete(insertedKey); // End sample }
public void Lookup() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Lookup(Key[]) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); Entity message = new Entity { Key = keyFactory.CreateIncompleteKey(), ["text"] = "Original" }; db.Insert(message); using (DatastoreTransaction transaction = db.BeginTransaction()) { // Look the message up at the start of the transaction Entity fetched1 = transaction.Lookup(message.Key); Console.WriteLine((string)fetched1["text"]); // "Original" // Update the message outside the transaction message["text"] = "Updated"; db.Update(message); // Look up the message up again. We are guaranteed not to see the // update because it occurred after the start of the transaction. Entity fetched2 = transaction.Lookup(message.Key); Console.WriteLine((string)fetched2["text"]); // Still "Original" } // End snippet }
// [START create] public void Create(Movie movie) { var entity = movie.ToEntity(); entity.Key = _db.CreateKeyFactory("Movie").CreateIncompleteKey(); var keys = _db.Insert(new[] { entity }); movie.Id = keys.First().Path.First().Id; }
public void Create(Item item) { var entity = item.ToEntity(); entity.Key = _db.CreateKeyFactory(kind).CreateIncompleteKey(); var keys = _db.Insert(new[] { entity }); item.Id = keys.First().Path.First().Id; }
// [START create] public void Create(Team team) { var entity = team.ToEntity(); entity.Key = _db.CreateKeyFactory("Team").CreateIncompleteKey(); var keys = _db.Insert(new[] { entity }); team.TeamId = keys.First().Path.First().Id; }
// [START create] public void Create(Book book) { var entity = book.ToEntity(); entity.Key = _db.CreateKeyFactory("Book").CreateIncompleteKey(); var keys = _db.Insert(new[] { entity }); book.Id = keys.First().Path.First().Id; }
// [START create] public void Create(Place place) { var entity = place.ToEntity(); entity.Key = _db.CreateKeyFactory("Place").CreateIncompleteKey(); var keys = _db.Insert(new[] { entity }); place.Id = keys.First().Path.First().Id; }
private Key PrepareQueryTest(DatastoreDb db) { var keyFactory = db.CreateKeyFactory("parent"); var parent = new Entity { Key = keyFactory.CreateIncompleteKey() }; var parentKey = db.Insert(parent); var child = new Entity { Key = parentKey.WithElement(new PathElement { Kind = "childKind" }) }; db.Insert(child); return(parentKey); }
public bool InsertDatastore(Entity aEntity, string aKind) { aEntity.Key = datastore.CreateKeyFactory(aKind).CreateIncompleteKey(); var keys = datastore.Insert(new[] { aEntity }); if (keys != null) { return(true); } return(false); }
// [START create] public long Create(T item) { KeyFactory factory = _db.CreateKeyFactory(_kind); var entity = item.ToEntity(factory); entity.Key = factory.CreateIncompleteKey(); var keys = _db.Insert(new[] { entity }); item.Id = keys.First().Path.First().Id; return(item.Id); }
public void Insert <T>(T poco) { var entity = new Entity(); entity.Key = _db.CreateKeyFactory(typeof(T).Name).CreateIncompleteKey(); foreach (var prop in typeof(T).GetProperties()) { var test = prop; var y = poco.GetType().GetProperty(test.Name).GetValue(poco, null); entity[test.Name] = y.ToString(); } var keys = _db.Insert(new[] { entity }); }
void CreateKeyFactory() { DatastoreDb datastoreDb = DatastoreDb.Create(ProjectId, Namespace); KeyFactory keyFactory = datastoreDb.CreateKeyFactory(Kind); Key key = keyFactory.CreateKey("sampletask"); var task = new Entity { Key = key, ["description"] = "Buy milk" }; datastoreDb.Insert(task); }
// [START create] public void Create(ImageMetaDeta image) { try { var entity = image.ToEntity(); entity.Key = _db.CreateKeyFactory("Image").CreateIncompleteKey(); var keys = _db.Insert(entity); image.imageId = keys.Path.First().Id; } catch (Exception e) { ExceptionLogging.SendExcepToDB(e); } }
// Used by TransactionReadAndWrite. Could promote to the fixture. private Key CreateAccount(string name, long balance) { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory factory = db.CreateKeyFactory("Account"); Entity entity = new Entity { Key = factory.CreateIncompleteKey(), ["name"] = name, ["balance"] = balance }; return(db.Insert(entity)); }
// [START add_entity] /// <summary> /// Adds a task entity to the Datastore /// </summary> /// <param name="description">The task description.</param> /// <returns>The key of the entity.</returns> Key AddTask(string description) { Entity task = new Entity() { Key = _keyFactory.CreateIncompleteKey(), ["description"] = new Value() { StringValue = description, ExcludeFromIndexes = true }, ["created"] = DateTime.UtcNow, ["done"] = false }; return(_db.Insert(task)); }
public ActionResult Create() { DatastoreDb db = DatastoreDb.Create("Jurgen-Cloud-Project"); Entity log = new Entity() { Key = db.CreateKeyFactory("users").CreateIncompleteKey(), //incompletekey : auto generated id ["email"] = User.Identity.Name, ["lastloggedin"] = DateTime.UtcNow, ["active"] = true }; db.Insert(log); return(Content("Operation done!")); }
public void Upsert() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Upsert(Entity[]) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("book"); Entity book1 = new Entity { Key = keyFactory.CreateIncompleteKey(), ["author"] = "Harper Lee", ["title"] = "Tequila Mockingbird", ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc), ["genres"] = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" } }; db.Insert(book1); using (DatastoreTransaction transaction = db.BeginTransaction()) { // Correct the typo in memory book1["title"] = "To Kill a Mockingbird"; Entity book2 = new Entity { Key = keyFactory.CreateIncompleteKey(), ["author"] = "Charlotte Brontë", ["title"] = "Jane Eyre", ["publication_date"] = new DateTime(1847, 10, 16, 0, 0, 0, DateTimeKind.Utc), ["genres"] = new[] { "Gothic", "Romance", "Bildungsroman" } }; // This adds the entities to a collection of mutations in memory: nothing // is sent to the server. transaction.Upsert(book1, book2); // Without the Commit call, the transaction will automatically // be rolled back. The Commit call performs all the mutations // within the transaction. transaction.Commit(); } // End snippet }
public void InsertEntity() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: InsertEntity DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("Task"); Entity entity = new Entity { Key = keyFactory.CreateIncompleteKey(), ["category"] = "Personal", ["done"] = false, ["priority"] = 4, ["description"] = "Learn Cloud Datastore", ["percent_complete"] = 75.0 }; Key insertedKey = db.Insert(entity); // End sample }
public async Task RollbackAsync() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: RollbackAsync(*) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); // Dispose automatically rolls back an uncommitted transaction synchronously. // To roll back asynchronously, bool committed = false; DatastoreTransaction transaction = await db.BeginTransactionAsync(); try { Entity message = new Entity { Key = keyFactory.CreateIncompleteKey(), ["text"] = "Hello", }; // This adds the entity to a collection in memory: nothing // is sent to the server. db.Insert(message); // Attempt to commit the transaction asynchronously. await transaction.CommitAsync(); committed = true; } finally { if (!committed) { // Roll back asynchronously if anything failed. await transaction.RollbackAsync(); } } // End snippet }
public void DeleteEntity() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: Delete(Entity[]) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); Entity message = new Entity { Key = keyFactory.CreateIncompleteKey(), ["text"] = "Hello", }; db.Insert(message); Entity fetchedBeforeDeletion = db.Lookup(message.Key); using (DatastoreTransaction transaction = db.BeginTransaction()) { // This adds the entity key to a collection of mutations in memory: nothing // is sent to the server. Only the key from the entity is used to determine what to delete. // If you already have the key but not the entity, use Delete(Key[]) or // a similar overload. transaction.Delete(message); // Without the Commit call, the transaction will automatically // be rolled back. The Commit call performs all the mutations // within the transaction. transaction.Commit(); } Entity fetchedAfterDeletion = db.Lookup(message.Key); Console.WriteLine($"Entity exists before deletion? {fetchedBeforeDeletion != null}"); Console.WriteLine($"Entity exists after deletion? {fetchedAfterDeletion != null}"); // End snippet Assert.NotNull(fetchedBeforeDeletion); Assert.Null(fetchedAfterDeletion); }