com.google.appengine.api.datastore.PreparedQuery Java Examples

The following examples show how to use com.google.appengine.api.datastore.PreparedQuery. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> getRootPipelinesDisplayName() {
  Query query = new Query(JobRecord.DATA_STORE_KIND);
  query.addProjection(
      new PropertyProjection(JobRecord.ROOT_JOB_DISPLAY_NAME, String.class));
  query.setDistinct(true);
  final PreparedQuery preparedQuery = dataStore.prepare(query);
  return tryFiveTimes(new Operation<Set<String>>("getRootPipelinesDisplayName") {
    @Override
    public Set<String> call() {
      Set<String> pipelines = new LinkedHashSet<>();
      for (Entity entity : preparedQuery.asIterable()) {
        pipelines.add((String) entity.getProperty(JobRecord.ROOT_JOB_DISPLAY_NAME));
      }
      return pipelines;
    }
  });
}
 
Example #2
Source File: DatastoreMultitenancyTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryConsidersCurrentNamespaceWhenCreatedNotWhenPreparedOrExecuted() {
    deleteNsKinds("one", "foo");
    deleteNsKinds("two", "foo");
    sync();

    NamespaceManager.set("one");
    Entity fooOne = new Entity("foo");
    service.put(fooOne);

    NamespaceManager.set("two");
    Entity fooTwo = new Entity("foo");
    service.put(fooTwo);
    sync();

    Query query = new Query("foo").setAncestor(fooTwo.getKey()); // query created in namespace "two"

    NamespaceManager.set("one");
    PreparedQuery preparedQuery = service.prepare(query);
    assertEquals(fooTwo, preparedQuery.asSingleEntity());

    service.delete(fooOne.getKey());
    service.delete(fooTwo.getKey());
}
 
Example #3
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeysOnly() throws Exception {
    Entity parent = createTestEntityWithUniqueMethodNameKey("Person", "testKeysOnly");
    Key key = parent.getKey();

    Entity john = createEntity("Person", key)
        .withProperty("name", "John")
        .withProperty("surname", "Doe")
        .store();

    Query query = new Query("Person")
        .setAncestor(key)
        .setKeysOnly();

    PreparedQuery preparedQuery = service.prepare(query);

    Entity entity = preparedQuery.asSingleEntity();
    assertEquals(john.getKey(), entity.getKey());
    assertNull(entity.getProperty("name"));
    assertNull(entity.getProperty("surname"));
}
 
Example #4
Source File: QueryFilteringByGAEPropertyTypesTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilterByEntityKey() {
    Entity parentEntity = createTestEntityWithUniqueMethodNameKey(TEST_ENTITY_KIND, "testFilterByEntityKey");
    Key parentKey = parentEntity.getKey();

    Key fooKey = KeyFactory.createKey(parentKey, "foo", 1);
    Entity fooEntity = new Entity(fooKey);
    service.put(fooEntity);

    Query query = new Query("foo")
        .setAncestor(parentKey)
        .setFilter(new Query.FilterPredicate(Entity.KEY_RESERVED_PROPERTY, EQUAL, fooKey));

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(FetchOptions.Builder.withDefaults());

    assertEquals(1, results.size());
    assertEquals(fooEntity, results.get(0));
}
 
Example #5
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testProjectionsWithoutType() throws Exception {
    String methodName = "testProjectionsWithoutType";
    Entity parent = createTestEntityWithUniqueMethodNameKey("Product", methodName);
    Key key = parent.getKey();

    Entity e = createEntity("Product", key)
        .withProperty("long", 123L)
        .store();

    Query query = new Query("Product")
        .setAncestor(key)
        .addProjection(new PropertyProjection("long", null));

    PreparedQuery preparedQuery = service.prepare(query);
    Entity result = preparedQuery.asSingleEntity();
    assertEquals(e.getKey(), result.getKey());

    RawValue rawValue = (RawValue) result.getProperty("long");
    assertEquals(Long.valueOf(123L), rawValue.asType(Long.class));
    assertEquals(Long.valueOf(123L), rawValue.asStrictType(Long.class));
}
 
Example #6
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private void assertRollbackSucceedsWhenResultFetchedWith(ResultFetcher resultFetcher) throws EntityNotFoundException {
    String methodName = "assertRollbackSucceedsWhenResultFetchedWith";
    Entity entity = createTestEntityWithUniqueMethodNameKey(TRANSACTION_TEST_ENTITY, methodName);
    Key parentKey = entity.getKey();
    entity.setProperty("name", "original");
    Key key = service.put(entity);
    try {
        Transaction tx = service.beginTransaction();
        PreparedQuery preparedQuery = service.prepare(new Query(TRANSACTION_TEST_ENTITY).setAncestor(parentKey));
        Entity entity2 = resultFetcher.fetchResult(preparedQuery);
        entity2.setProperty("name", "modified");
        service.put(tx, entity2);
        tx.rollback();

        Entity entity3 = service.get(key);
        assertEquals("original", entity3.getProperty("name"));
    } finally {
        service.delete(entity.getKey());
    }
}
 
Example #7
Source File: QueryResultTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexListFromList() throws Exception {
    Entity parent = createTestEntityWithUniqueMethodNameKey("Person", "testKeysOnly");
    Key key = parent.getKey();

    Entity joe = createEntity("Person", key)
        .withProperty("name", "Joe")
        .withProperty("surname", "Moe")
        .store();

    Query query = new Query("Person")
        .setAncestor(key)
        .setKeysOnly();

    PreparedQuery preparedQuery = service.prepare(query);
    QueryResultList<Entity> list = preparedQuery.asQueryResultList(FetchOptions.Builder.withDefaults());
    List<Index> indexes = list.getIndexList();
    if (indexes != null) {
        // TODO -- something useful
        System.out.println("indexes = " + indexes);
    }
}
 
Example #8
Source File: QueryResultTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexListFromIterator() throws Exception {
    Entity parent = createTestEntityWithUniqueMethodNameKey("Person", "testKeysOnly");
    Key key = parent.getKey();

    Entity tom = createEntity("Person", key)
        .withProperty("name", "Tom")
        .withProperty("surname", "Foe")
        .store();

    Query query = new Query("Person")
        .setAncestor(key)
        .setKeysOnly();

    PreparedQuery preparedQuery = service.prepare(query);
    QueryResultIterator<Entity> iter = preparedQuery.asQueryResultIterator();
    List<Index> indexes = iter.getIndexList();
    if (indexes != null) {
        // TODO -- something useful
        System.out.println("indexes = " + indexes);
    }
}
 
Example #9
Source File: QueryResultTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCursor() throws Exception {
    Entity parent = createTestEntityWithUniqueMethodNameKey("Person", "testKeysOnly");
    Key key = parent.getKey();

    Entity john = createEntity("Person", key)
        .withProperty("name", "John")
        .withProperty("surname", "Doe")
        .store();

    Query query = new Query("Person")
        .setAncestor(key)
        .setKeysOnly();

    PreparedQuery preparedQuery = service.prepare(query);
    QueryResultIterator<Entity> iter = preparedQuery.asQueryResultIterator();
    Assert.assertNotNull(iter.next());
    Cursor cursor = iter.getCursor();

    iter = service.prepare(query).asQueryResultIterator(FetchOptions.Builder.withStartCursor(cursor));
    Assert.assertFalse(iter.hasNext());
}
 
Example #10
Source File: TestReport.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the {@code TestReport} with the given build type id ordered by build id in the descendant order.
 *
 * @param buildTypeId      the build type id.
 * @param limit            the optional fetch limit, by default {@link com.google.appengine.tck.site.endpoints.TestReport#DEFAULT_FETCH_LIMIT}.
 * @param reports          the reports entry point
 * @return the matching test reports list or an empty one if none.
 */
@SuppressWarnings("unchecked")
public static List<TestReport> findByBuildTypeIdOrderByBuildIdDesc(String buildTypeId, Optional<Integer> limit, Reports reports) {
    final MemcacheService memcacheService = reports.getMemcacheService();
    List<TestReport> results = (List<TestReport>) memcacheService.get(buildTypeId);
    if (results == null) {
        final Filter buildTypeFilter = new Query.FilterPredicate("buildTypeId", FilterOperator.EQUAL, buildTypeId);
        final Query query = new Query(TEST_REPORT).setFilter(buildTypeFilter).addSort("buildId", DESCENDING);

        final DatastoreService datastoreService = reports.getDatastoreService();
        final PreparedQuery preparedQuery = datastoreService.prepare(query);
        final List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(limit.or(DEFAULT_FETCH_LIMIT)));

        results = new ArrayList<>();
        for (Entity oneEntity : entities) {
            final TestReport report = from(oneEntity);
            results.add(report);
        }

        memcacheService.put(buildTypeId, results);
    }
    return results;
}
 
Example #11
Source File: DatastoreSessionStore.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, SessionData> getAllSessions() {
  final String originalNamespace = NamespaceManager.get();
  NamespaceManager.set("");
  try {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery pq = ds.prepare(new Query(SESSION_ENTITY_TYPE));
    Map<String, SessionData> sessions = new HashMap<>();
    for (Entity entity : pq.asIterable()) {
      sessions.put(entity.getKey().getName(), createSessionFromEntity(entity));
    }
    return sessions;
  } finally {
    NamespaceManager.set(originalNamespace);
  }
}
 
Example #12
Source File: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 6 votes vote down vote up
private void deleteAll(final String kind, final Key rootJobKey) {
  logger.info("Deleting all " + kind + " with rootJobKey=" + rootJobKey);
  final int chunkSize = 100;
  final FetchOptions fetchOptions = FetchOptions.Builder.withChunkSize(chunkSize);
  final PreparedQuery preparedQuery = dataStore.prepare(new Query(kind).setKeysOnly().setFilter(
      new FilterPredicate(ROOT_JOB_KEY_PROPERTY, EQUAL, rootJobKey)));
  tryFiveTimes(new Operation<Void>("delete") {
    @Override
    public Void call() {
      Iterator<Entity> iter = preparedQuery.asIterator(fetchOptions);
      while (iter.hasNext()) {
        ArrayList<Key> keys = new ArrayList<>(chunkSize);
        for (int i = 0; i < chunkSize && iter.hasNext(); i++) {
          keys.add(iter.next().getKey());
        }
        logger.info("Deleting  " + keys.size() + " " + kind + "s with rootJobKey=" + rootJobKey);
        dataStore.delete(null, keys);
      }
      return null;
    }
  });
}
 
Example #13
Source File: QueryBasicsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithoutAnyConstraints() throws Exception {
    Key parentKey = createQueryBasicsTestParent("testQueryWithoutAnyConstraints");

    Entity person = new Entity("Person", parentKey);
    service.put(person);

    Entity address = new Entity("Address", parentKey);
    service.put(address);

    PreparedQuery preparedQuery = service.prepare(new Query().setAncestor(parentKey));
    assertTrue(preparedQuery.countEntities(withDefaults()) >= 2);

    List<Entity> results = preparedQuery.asList(withDefaults());
    assertTrue(results.containsAll(Arrays.asList(person, address)));
}
 
Example #14
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
public static <T extends TempData> T getLastTempData(Class<T> type) {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        String kind = getKind(type);
        PreparedQuery pq = ds.prepare(new Query(kind).addSort("timestamp", Query.SortDirection.DESCENDING));
        Iterator<Entity> iter = pq.asIterator();
        if (iter.hasNext()) {
            Entity entity = iter.next();
            return readTempData(type, entity, ds);
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #15
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example #16
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooksByUser(String userId, String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      // Only for this user
      .setFilter(new Query.FilterPredicate(
          Book.CREATED_BY_ID, Query.FilterOperator.EQUAL, userId))
      // a custom datastore index is required since you are filtering by one property
      // but ordering by another
      .addSort(Book.TITLE, SortDirection.ASCENDING);
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example #17
Source File: PersistingTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void putStoresEntity() throws Exception {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Entity client = new Entity("Client");
    client.setProperty("username", "alesj");
    client.setProperty("password", "password");
    final Key key = ds.put(client);
    try {
        Query query = new Query("Client");
        query.setFilter(new Query.FilterPredicate("username", Query.FilterOperator.EQUAL, "alesj"));
        PreparedQuery pq = ds.prepare(query);
        Entity result = pq.asSingleEntity();
        Assert.assertNotNull(result);
        Assert.assertEquals(key, result.getKey());
        Assert.assertEquals("alesj", result.getProperty("username"));
        Assert.assertEquals("password", result.getProperty("password"));
    } finally {
        ds.delete(key);
    }
}
 
Example #18
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example #19
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example #20
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      .addSort(Book.TITLE, SortDirection.ASCENDING); // Use default Index "title"
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example #21
Source File: QueryBasicsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void singleEntityThrowsTooManyResultsExceptionWhenMoreThanOneResult() throws Exception {
    String methodName = "singleEntityThrowsTooManyResultsExceptionWhenMoreThanOneResult";
    Key parentKey = createQueryBasicsTestParent(methodName);

    createEntity("Person", parentKey).store();
    createEntity("Person", parentKey).store();

    PreparedQuery preparedQuery = service.prepare(new Query("Person"));
    try {
        preparedQuery.asSingleEntity();
        fail("Expected PreparedQuery.TooManyResultsException");
    } catch (PreparedQuery.TooManyResultsException e) {
        // pass
    }
}
 
Example #22
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private static <T extends TempData> List<T> getAllTempData(Class<T> type, boolean unreadOnly) {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        String kind = getKind(type);
        Query query = new Query(kind);
        if (unreadOnly) {
            query.setFilter(new Query.FilterPredicate(TEMP_DATA_READ_PROPERTY, Query.FilterOperator.EQUAL, false));
        } else {
            query.addSort("timestamp", Query.SortDirection.ASCENDING);
        }
        PreparedQuery pq = ds.prepare(query);
        Iterator<Entity> iter = pq.asIterator();
        List<T> result = new ArrayList<>();
        while (iter.hasNext()) {
            Entity entity = iter.next();
            T data = readTempData(type, entity, ds);
            result.add(data);
        }
        return result;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #23
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooksByUser(String userId, String startCursorString) {
  FetchOptions fetchOptions = FetchOptions.Builder.withLimit(10); // Only show 10 at a time
  if (startCursorString != null && !startCursorString.equals("")) {
    fetchOptions.startCursor(Cursor.fromWebSafeString(startCursorString)); // Where we left off
  }
  Query query = new Query(BOOK_KIND) // We only care about Books
      // Only for this user
      .setFilter(new Query.FilterPredicate(
          Book.CREATED_BY_ID, Query.FilterOperator.EQUAL, userId))
      // a custom datastore index is required since you are filtering by one property
      // but ordering by another
      .addSort(Book.TITLE, SortDirection.ASCENDING);
  PreparedQuery preparedQuery = datastore.prepare(query);
  QueryResultIterator<Entity> results = preparedQuery.asQueryResultIterator(fetchOptions);

  List<Book> resultBooks = entitiesToBooks(results);     // Retrieve and convert Entities
  Cursor cursor = results.getCursor();              // Where to start next time
  if (cursor != null && resultBooks.size() == 10) {         // Are we paging? Save Cursor
    String cursorString = cursor.toWebSafeString();               // Cursors are WebSafe
    return new Result<>(resultBooks, cursorString);
  } else {
    return new Result<>(resultBooks);
  }
}
 
Example #24
Source File: Simple2ExampleTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
/**
 * This verifies the result on the server side of the invokeTimestampTest.
 *
 * @throws Exception
 */
@Test
@InSequence(2)
public void testTimestampWrittenTest() throws Exception {
    Query query = new Query("example");

    PreparedQuery preparedQuery = service.prepare(query);

    // A real test would assert on the result here.
    //
    // Assert.assertTrue("Should have a result.",
    //   preparedQuery.countEntities(FetchOptions.Builder.withDefaults()) > 0);
}
 
Example #25
Source File: DatastoreMultitenancyTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryOnSomePropertyWithKeyInDifferentNamespace() {
    NamespaceManager.set("one");
    Key keyInNamespaceOne = KeyFactory.createKey("kind", 1);

    NamespaceManager.set("two");
    Query query = new Query("kind").setFilter(new Query.FilterPredicate("someProperty", EQUAL, keyInNamespaceOne));
    PreparedQuery preparedQuery = service.prepare(query);
    preparedQuery.asSingleEntity();    // should not throw IllegalArgumentException as in previous test
    preparedQuery.asIterator().hasNext();    // should not throw IllegalArgumentException as in previous test
    preparedQuery.asList(withDefaults()).size();    // should not throw IllegalArgumentException as in previous test
}
 
Example #26
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjections() throws Exception {
    Entity parent = createTestEntityWithUniqueMethodNameKey("Product", "testProjections");
    Key key = parent.getKey();

    Entity e = createEntity("Product", key)
        .withProperty("price", 123L)
        .withProperty("percent", 0.123)
        .withProperty("x", -0.321)
        .withProperty("diff", -5L)
        .withProperty("weight", 10L)
        .store();

    Query query = new Query("Product")
        .setAncestor(key)
        .addProjection(new PropertyProjection("price", Long.class))
        .addProjection(new PropertyProjection("percent", Double.class))
        .addProjection(new PropertyProjection("x", Double.class))
        .addProjection(new PropertyProjection("diff", Long.class));

    PreparedQuery preparedQuery = service.prepare(query);
    Entity result = preparedQuery.asSingleEntity();
    assertEquals(e.getKey(), result.getKey());
    assertEquals(e.getProperty("price"), result.getProperty("price"));
    assertEquals(e.getProperty("percent"), result.getProperty("percent"));
    assertEquals(e.getProperty("x"), result.getProperty("x"));
    assertEquals(e.getProperty("diff"), result.getProperty("diff"));
    assertNull(result.getProperty("weight"));
}
 
Example #27
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectionOfCollectionProperties() throws Exception {
    String methodName = "testProjectionOfCollectionProperties";
    String entityKind = "test-proj";
    Entity parent = createTestEntityWithUniqueMethodNameKey(entityKind, methodName);
    Key key = parent.getKey();

    Entity e = createEntity(entityKind, key)
        .withProperty("prop", Arrays.asList("bbb", "ccc", "aaa"))
        .store();

    Query query = new Query(entityKind)
        .setAncestor(key)
        .addProjection(new PropertyProjection("prop", String.class))
        .addSort("prop");

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(3, results.size());

    Entity firstResult = results.get(0);
    Entity secondResult = results.get(1);
    Entity thirdResult = results.get(2);

    assertEquals(e.getKey(), firstResult.getKey());
    assertEquals(e.getKey(), secondResult.getKey());
    assertEquals(e.getKey(), thirdResult.getKey());
    assertEquals("aaa", firstResult.getProperty("prop"));
    assertEquals("bbb", secondResult.getProperty("prop"));
    assertEquals("ccc", thirdResult.getProperty("prop"));
}
 
Example #28
Source File: QueryOptimizationsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectionOfCollectionPropertyWithFilterOnCollectionProperty() throws Exception {
    String methodName = "testProjectionOfCollectionPropertyWithFilterOnCollectionProperty";
    Entity parent = createTestEntityWithUniqueMethodNameKey("Product", methodName);
    Key key = parent.getKey();

    Entity e = createEntity("Product", key)
        .withProperty("name", Arrays.asList("aaa", "bbb"))
        .withProperty("price", Arrays.asList(10L, 20L))
        .store();

    Query query = new Query("Product")
        .setAncestor(key)
        .addProjection(new PropertyProjection("name", String.class))
        .setFilter(new Query.FilterPredicate("price", GREATER_THAN, 0L))
        .addSort("price")
        .addSort("name");

    PreparedQuery preparedQuery = service.prepare(query);
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(4, results.size());

    assertEquals(e.getKey(), results.get(0).getKey());
    assertEquals(e.getKey(), results.get(1).getKey());
    assertEquals(e.getKey(), results.get(2).getKey());
    assertEquals(e.getKey(), results.get(3).getKey());

    assertEquals("aaa", results.get(0).getProperty("name"));
    assertEquals("bbb", results.get(1).getProperty("name"));
    assertEquals("aaa", results.get(2).getProperty("name"));
    assertEquals("bbb", results.get(3).getProperty("name"));
}
 
Example #29
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private void assertIAEWhenAccessingList(PreparedQuery preparedQuery) {
    List<Entity> list = preparedQuery.asList(withDefaults());
    try {
        list.size();
        fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException ex) {
        // pass
    }
}
 
Example #30
Source File: QueryBasicsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilteringByKind() throws Exception {
    Key parentKey = createQueryBasicsTestParent("testFilteringByKind");
    Entity foo = createEntity("foo", parentKey).store();
    Entity bar = createEntity("bar", parentKey).store();

    PreparedQuery preparedQuery = service.prepare(new Query("foo").setAncestor(parentKey));
    List<Entity> results = preparedQuery.asList(withDefaults());
    assertEquals(1, results.size());
    assertEquals(foo, results.get(0));
}