Refine search
/** Example of putting a single entity. */ // [TARGET put(FullEntity)] // [VARIABLE "my_key_name"] public void putSingleEntity(String keyName) { Datastore datastore = transaction.getDatastore(); // [START putSingleEntity] Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); transaction.put(entity); transaction.commit(); // [END putSingleEntity] }
@Test public void testNewTransactionCommit() { Transaction transaction = datastore.newTransaction(); transaction.add(ENTITY3); Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla").build(); transaction.update(entity2); transaction.delete(KEY1); transaction.commit(); List<Entity> list = datastore.fetch(KEY1, KEY2, KEY3); assertNull(list.get(0)); assertEquals(entity2, list.get(1)); assertEquals(ENTITY3, list.get(2)); assertEquals(3, list.size()); try { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException ex) { // expected to fail } try { transaction.rollback(); fail("Expecting a failure"); } catch (DatastoreException ex) { // expected to fail } verifyNotUsable(transaction); }
/** * Inserts a new {@link PortabilityJob} keyed by {@code jobId} in Datastore. * * <p>To update an existing {@link PortabilityJob} instead, use {@link JobStore#update}. * * @throws IOException if a job already exists for {@code jobId}, or if there was a different * problem inserting the job. */ @Override public void createJob(UUID jobId, PortabilityJob job) throws IOException { Preconditions.checkNotNull(jobId); Transaction transaction = datastore.newTransaction(); Entity shouldNotExist = transaction.get(getKey(jobId)); if (shouldNotExist != null) { transaction.rollback(); throw new IOException( "Record already exists for jobID: " + jobId + ". Record: " + shouldNotExist); } Entity entity = createEntity(jobId, job.toMap()); try { transaction.put(entity); } catch (DatastoreException e) { transaction.rollback(); throw new IOException( "Could not create initial record for jobID: " + jobId + ". Record: " + entity, e); } transaction.commit(); }
/** Example of getting an entity for a given key. */ // [TARGET get(Key)] // [VARIABLE "my_key_name"] public Entity get(String keyName) { Datastore datastore = transaction.getDatastore(); // [START get] Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity entity = transaction.get(key); transaction.commit(); // Do something with the entity // [END get] return entity; }
/** Example of deleting multiple entities. */ // [TARGET delete(Key...)] // [VARIABLE "my_key_name1"] // [VARIABLE "my_key_name2"] public void multipleDeleteEntities(String keyName1, String keyName2) { Datastore datastore = transaction.getDatastore(); // [START multipleDeleteEntities] Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); transaction.delete(key1, key2); transaction.commit(); // [END multipleDeleteEntities] }
/** Example of adding a single entity. */ // [TARGET add(FullEntity)] // [VARIABLE "my_key_name"] public void addSingleEntity(String keyName) { Datastore datastore = transaction.getDatastore(); // [START addSingleEntity] Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); transaction.add(entity); transaction.commit(); // [END addSingleEntity] }
@Test public void testTransactionWithQuery() { Query<Entity> query = Query.newEntityQueryBuilder() .setKind(KIND2) .setFilter(PropertyFilter.hasAncestor(KEY2)) .build(); Transaction transaction = datastore.newTransaction(); QueryResults<Entity> results = transaction.run(query); assertEquals(ENTITY2, results.next()); assertFalse(results.hasNext()); transaction.add(ENTITY3); transaction.commit(); assertEquals(ENTITY3, datastore.get(KEY3)); transaction = datastore.newTransaction(); results = transaction.run(query); assertEquals(ENTITY2, results.next()); transaction.delete(ENTITY3.getKey()); // update entity2 during the transaction datastore.put(Entity.newBuilder(ENTITY2).clear().build()); try { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { assertEquals("ABORTED", expected.getReason()); } }
@Test public void testTransactionWithRead() { Transaction transaction = datastore.newTransaction(); assertNull(transaction.get(KEY3)); transaction.add(ENTITY3); transaction.commit(); assertEquals(ENTITY3, datastore.get(KEY3)); transaction = datastore.newTransaction(); assertEquals(ENTITY3, transaction.get(KEY3)); // update entity3 during the transaction datastore.put(Entity.newBuilder(ENTITY3).clear().build()); transaction.update(ENTITY2); try { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { assertEquals("ABORTED", expected.getReason()); } }
/** Example of updating multiple entities. */ // [TARGET update(Entity...)] // [VARIABLE "my_key_name1"] // [VARIABLE "my_key_name2"] public void multipleUpdateEntities(String keyName1, String keyName2) { Datastore datastore = transaction.getDatastore(); // [START multipleUpdateEntities] Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "value3"); Entity entity1 = entityBuilder1.build(); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "value4"); Entity entity2 = entityBuilder2.build(); transaction.update(entity1, entity2); transaction.commit(); // [END multipleUpdateEntities] }
String name = args.length > 1 ? args[1] : System.getProperty("user.getName"); Datastore datastore = options.getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind(USER_KIND); Key key = keyFactory.newKey(name); String actionName = args.length > 2 ? args[2].toLowerCase() : DEFAULT_ACTION; DatastoreAction action = ACTIONS.get(actionName); Transaction tx = datastore.newTransaction(); Object request; try { tx.commit(); } finally { if (tx.isActive()) { tx.rollback();
/** * Marks a task entity as done. * * @param id The ID of the task entity as given by {@link Key#id()} * @return true if the task was found, false if not * @throws DatastoreException if the transaction fails */ boolean markDone(long id) { Transaction transaction = datastore.newTransaction(); try { Entity task = transaction.get(keyFactory.newKey(id)); if (task != null) { transaction.put(Entity.newBuilder(task).set("done", true).build()); } transaction.commit(); return task != null; } finally { if (transaction.isActive()) { transaction.rollback(); } } } // [END datastore_update_entity]
/** Example of fetching a list of entities for several keys. */ // [TARGET fetch(Key...)] // [VARIABLE "my_first_key_name"] // [VARIABLE "my_second_key_name"] public List<Entity> fetchEntitiesWithKeys(String firstKeyName, String secondKeyName) { Datastore datastore = transaction.getDatastore(); // [START fetchEntitiesWithKeys] KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); List<Entity> entities = transaction.fetch(firstKey, secondKey); for (Entity entity : entities) { // do something with the entity } transaction.commit(); // [END fetchEntitiesWithKeys] return entities; }
/** Example of adding multiple entities with deferred id allocation. */ // [TARGET addWithDeferredIdAllocation(FullEntity...)] public List<Key> multipleAddEntitiesDeferredId() { Datastore datastore = transaction.getDatastore(); // [START multipleAddEntitiesDeferredId] IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); FullEntity entity1 = entityBuilder1.build(); IncompleteKey key2 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder2 = FullEntity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); FullEntity entity2 = entityBuilder2.build(); transaction.addWithDeferredIdAllocation(entity1, entity2); Response response = transaction.commit(); // [END multipleAddEntitiesDeferredId] return response.getGeneratedKeys(); }
/** Example of putting multiple entities with deferred id allocation. */ // [TARGET putWithDeferredIdAllocation(FullEntity...)] public List<Key> multiplePutEntitiesDeferredId() { Datastore datastore = transaction.getDatastore(); // [START multiplePutEntitiesDeferredId] IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); FullEntity entity1 = entityBuilder1.build(); IncompleteKey key2 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder2 = FullEntity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); FullEntity entity2 = entityBuilder2.build(); transaction.putWithDeferredIdAllocation(entity1, entity2); Response response = transaction.commit(); // [END multiplePutEntitiesDeferredId] return response.getGeneratedKeys(); }
/** Example of running a query to find all entities with an ancestor. */ // [TARGET run(Query)] // [VARIABLE "my_parent_key_name"] public List<Entity> run(String parentKeyName) { Datastore datastore = transaction.getDatastore(); // [START run] KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind"); Key parentKey = keyFactory.newKey(parentKeyName); // Build a query Query<Entity> query = Query.newEntityQueryBuilder() .setKind("MyKind") .setFilter(PropertyFilter.hasAncestor(parentKey)) .build(); QueryResults<Entity> results = transaction.run(query); List<Entity> entities = Lists.newArrayList(); while (results.hasNext()) { Entity result = results.next(); // do something with result entities.add(result); } transaction.commit(); // [END run] return entities; }
@Override public T call() throws DatastoreException { transaction = datastore.newTransaction(options); try { T value = callable.run(transaction); transaction.commit(); return value; } catch (Exception ex) { transaction.rollback(); throw DatastoreException.propagateUserException(ex); } finally { if (transaction.isActive()) { transaction.rollback(); } if (options != null && options.getModeCase().equals(TransactionOptions.ModeCase.READ_WRITE)) { setPrevTransactionId(transaction.getTransactionId()); } } } }
@Override public void run(Transaction tx, Key userKey, String content) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); user = Entity.newBuilder(userKey).set("count", 1).build(); tx.add(user); } else { user = Entity.newBuilder(user).set("count", user.getLong("count") + 1L).build(); tx.update(user); } IncompleteKey commentKey = IncompleteKey.newBuilder(userKey, COMMENT_KIND).build(); FullEntity<IncompleteKey> comment = FullEntity.newBuilder(commentKey) .set("content", content) .set("timestamp", Timestamp.now()) .build(); tx.addWithDeferredIdAllocation(comment); System.out.printf("Adding a comment to user '%s'.%n", userKey.getName()); }
entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity); Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE); transaction = datastore.newTransaction(); Entity storedNativeEntity = transaction.get(nativeEntity.getKey()); if (storedNativeEntity == null) { throw new OptimisticLockException( String.format("Entity does not exist: %s", nativeEntity.getKey())); long version = nativeEntity.getLong(versionPropertyName) - 1; long storedVersion = storedNativeEntity.getLong(versionPropertyName); if (version != storedVersion) { String.format("Expecting version %d, but found %d", version, storedVersion)); transaction.update(nativeEntity); transaction.commit(); E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass()); entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity);
@Override public void run(Transaction tx, Key userKey, Void arg) { Entity user = tx.get(userKey); if (user == null) { System.out.printf("User '%s' does not exist.%n", userKey.getName()); return; if (user.contains("contact")) { FullEntity<IncompleteKey> contact = user.getEntity("contact"); String email = contact.getString("email"); String phone = contact.getString("phone"); "User '%s' email is '%s', phone is '%s'.%n", userKey.getName(), email, phone); System.out.printf("User '%s' has %d comment[s].%n", userKey.getName(), user.getLong("count")); int limit = 200; Map<Timestamp, String> sortedComments = new TreeMap<>(); .build(); while (true) { QueryResults<Entity> results = tx.run(query); int resultCount = 0; while (results.hasNext()) {
nativeKeys[i] = nativeEntities[i].getKey(); transaction = datastore.newTransaction(); List<Entity> storedNativeEntities = transaction.fetch(nativeKeys); String versionPropertyName = versionMetadata.getMappedName(); long version = nativeEntities[i].getLong(versionPropertyName) - 1; Entity storedNativeEntity = storedNativeEntities.get(i); if (storedNativeEntity == null) { String.format("Entity does not exist: %s", nativeKeys[i])); long storedVersion = storedNativeEntities.get(i).getLong(versionPropertyName); if (version != storedVersion) { throw new OptimisticLockException( transaction.update(nativeEntities); transaction.commit(); List<E> updatedEntities = (List<E>) toEntities(entities.get(0).getClass(), nativeEntities); entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntities);