Java Code Examples for com.google.cloud.datastore.GqlQuery#Builder

The following examples show how to use com.google.cloud.datastore.GqlQuery#Builder . 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: DefaultDatastoreMetadata.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getKinds(boolean excludeSystemKinds) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_KINDS + " ORDER BY __key__";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    gqlQueryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    QueryResults<Key> results = entityManager.getDatastore().run(gqlQuery);
    List<String> kinds = new ArrayList<>(50);
    while (results.hasNext()) {
      Key key = results.next();
      String kind = key.getName();
      if (excludeSystemKinds && kind.startsWith("__")) {
        continue;
      }
      kinds.add(key.getName());
    }
    return kinds;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 2
Source File: DefaultDatastoreMetadata.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public QueryResponse<String> getNamespaces(DatastoreCursor fromCursor, int limit) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__";
    if (limit > 0) {
      query += " LIMIT @Limit";
    }
    query += " OFFSET @Offset";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    if (limit > 0) {
      gqlQueryBuilder.setBinding("Limit", limit);
    }
    gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded()));
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    Datastore datastore = entityManager.getDatastore();
    QueryResults<Key> results = datastore.run(gqlQuery);
    DefaultQueryResponse<String> response = new DefaultQueryResponse<>();
    List<String> namespaces = new ArrayList<>(Math.max(limit, 50));
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Key key = results.next();
      String name = key.getName();
      namespaces.add(name == null ? "" : name);
    }
    response.setResults(namespaces);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 3
Source File: QueryUtils.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given positional bindings to the given query builder.
 * 
 * @param queryBuilder
 *          the query builder
 * @param positionalBindings
 *          the positional bindings.
 */
static void applyPositionalBindings(GqlQuery.Builder<?> queryBuilder,
    Object... positionalBindings) {
  if (positionalBindings != null) {
    for (Object binding : positionalBindings) {
      addPositionalBinding(queryBuilder, binding);
    }
  }
}
 
Example 4
Source File: QueryUtils.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given positional bindings to the given query builder.
 * 
 * @param queryBuilder
 *          the query builder
 * @param positionalBindings
 *          the positional bindings.
 */
static void applyPositionalBindings(GqlQuery.Builder<?> queryBuilder,
    List<Object> positionalBindings) {
  if (positionalBindings != null) {
    for (Object binding : positionalBindings) {
      addPositionalBinding(queryBuilder, binding);
    }
  }
}
 
Example 5
Source File: DefaultDatastoreReader.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link EntityQueryRequest} and returns the response.
 * 
 * @param expectedResultType
 *          the expected type of results.
 * @param request
 *          the entity query request
 * @return the query response
 */
public <E> QueryResponse<E> executeEntityQueryRequest(Class<E> expectedResultType,
    EntityQueryRequest request) {
  try {
    GqlQuery.Builder<Entity> queryBuilder = Query.newGqlQueryBuilder(ResultType.ENTITY,
        request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<Entity> gqlQuery = queryBuilder.build();
    QueryResults<Entity> results = nativeReader.run(gqlQuery);
    List<E> entities = new ArrayList<>();
    DefaultQueryResponse<E> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Entity result = results.next();
      E entity = Unmarshaller.unmarshal(result, expectedResultType);
      entities.add(entity);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities);
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 6
Source File: DefaultDatastoreReader.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link ProjectionQueryRequest} and returns the response.
 * 
 * @param expectedResultType
 *          the expected type of results.
 * @param request
 *          the projection query request
 * @return the query response
 */
public <E> QueryResponse<E> executeProjectionQueryRequest(Class<E> expectedResultType,
    ProjectionQueryRequest request) {
  try {
    GqlQuery.Builder<ProjectionEntity> queryBuilder = Query
        .newGqlQueryBuilder(ResultType.PROJECTION_ENTITY, request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<ProjectionEntity> gqlQuery = queryBuilder.build();
    QueryResults<ProjectionEntity> results = nativeReader.run(gqlQuery);
    List<E> entities = new ArrayList<>();
    DefaultQueryResponse<E> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      ProjectionEntity result = results.next();
      E entity = Unmarshaller.unmarshal(result, expectedResultType);
      entities.add(entity);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    // TODO should we invoke PostLoad callback for projected entities?
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 7
Source File: DefaultDatastoreReader.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link KeyQueryRequest} and returns the response.
 * 
 * @param request
 *          the key query request
 * @return the query response
 */
public QueryResponse<DatastoreKey> executeKeyQueryRequest(KeyQueryRequest request) {
  try {
    GqlQuery.Builder<Key> queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY,
        request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<Key> gqlQuery = queryBuilder.build();
    QueryResults<Key> results = nativeReader.run(gqlQuery);
    List<DatastoreKey> entities = new ArrayList<>();
    DefaultQueryResponse<DatastoreKey> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Key result = results.next();
      DatastoreKey datastoreKey = new DefaultDatastoreKey(result);
      entities.add(datastoreKey);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 8
Source File: QueryUtils.java    From catatumbo with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the given binding to the given query builder's to the list of positional bindings.
 * 
 * @param queryBuilder
 *          the query builder
 * @param binding
 *          the positional binding to add
 */
static void addPositionalBinding(GqlQuery.Builder<?> queryBuilder, Object binding) {
  if (binding == null) {
    throw new IllegalArgumentException("binding cannot be null. Use IS NULL in your query");
  }
  if (binding instanceof Short) {
    queryBuilder.addBinding((short) binding);
  } else if (binding instanceof Integer) {
    queryBuilder.addBinding((int) binding);
  } else if (binding instanceof Long) {
    queryBuilder.addBinding((long) binding);
  } else if (binding instanceof Float) {
    queryBuilder.addBinding((float) binding);
  } else if (binding instanceof Double) {
    queryBuilder.addBinding((double) binding);
  } else if (binding instanceof Boolean) {
    queryBuilder.addBinding((boolean) binding);
  } else if (binding instanceof Character) {
    queryBuilder.addBinding(String.valueOf((char) binding));
  } else if (binding instanceof String) {
    queryBuilder.addBinding((String) binding);
  } else if (binding instanceof Calendar) {
    queryBuilder.addBinding(toTimestamp((Calendar) binding));
  } else if (binding instanceof Date) {
    queryBuilder.addBinding(toTimestamp((Date) binding));
  } else if (binding instanceof LocalDate) {
    queryBuilder.addBinding(((LocalDate) binding).toString());
  } else if (binding instanceof LocalTime) {
    queryBuilder.addBinding(((LocalTime) binding).format(LocalTimeMapper.FORMATTER));
  } else if (binding instanceof LocalDateTime) {
    queryBuilder.addBinding(((LocalDateTime) binding).format(LocalDateTimeMapper.FORMATTER));
  } else if (binding instanceof OffsetDateTime) {
    queryBuilder.addBinding(toTimestamp((OffsetDateTime) binding));
  } else if (binding instanceof ZonedDateTime) {
    queryBuilder.addBinding(toTimestamp((ZonedDateTime) binding));
  } else if (binding instanceof byte[]) {
    queryBuilder.addBinding(Blob.copyFrom((byte[]) binding));
  } else if (binding instanceof DatastoreKey) {
    queryBuilder.addBinding(((DatastoreKey) binding).nativeKey());
  } else if (binding instanceof DatastoreCursor) {
    queryBuilder.addBinding(Cursor.fromUrlSafe(((DatastoreCursor) binding).getEncoded()));
  } else if (binding instanceof GeoLocation) {
    // TODO no support for GeoLocation in the gcloud API
  }
}
 
Example 9
Source File: QueryUtils.java    From catatumbo with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the given positional bindings to the given query builder.
 * 
 * @param queryBuilder
 *          the query builder
 * @param namedBindings
 *          the named bindings to apply
 */
static void applyNamedBindings(GqlQuery.Builder<?> queryBuilder,
    Map<String, Object> namedBindings) {
  if (namedBindings != null) {
    for (Map.Entry<String, Object> entry : namedBindings.entrySet()) {
      String bindingName = entry.getKey();
      Object bindingValue = entry.getValue();
      if (bindingValue instanceof Short) {
        queryBuilder.setBinding(bindingName, (short) bindingValue);
      } else if (bindingValue instanceof Integer) {
        queryBuilder.setBinding(bindingName, (int) bindingValue);
      } else if (bindingValue instanceof Long) {
        queryBuilder.setBinding(bindingName, (long) bindingValue);
      } else if (bindingValue instanceof Float) {
        queryBuilder.setBinding(bindingName, (float) bindingValue);
      } else if (bindingValue instanceof Double) {
        queryBuilder.setBinding(bindingName, (double) bindingValue);
      } else if (bindingValue instanceof Boolean) {
        queryBuilder.setBinding(bindingName, (boolean) bindingValue);
      } else if (bindingValue instanceof String) {
        queryBuilder.setBinding(bindingName, (String) bindingValue);
      } else if (bindingValue instanceof Calendar) {
        queryBuilder.setBinding(bindingName, toTimestamp((Calendar) bindingValue));
      } else if (bindingValue instanceof Date) {
        queryBuilder.setBinding(bindingName, toTimestamp((Date) bindingValue));
      } else if (bindingValue instanceof LocalDate) {
        queryBuilder.setBinding(bindingName, ((LocalDate) bindingValue).toString());
      } else if (bindingValue instanceof LocalTime) {
        queryBuilder.setBinding(bindingName,
            ((LocalTime) bindingValue).format(LocalTimeMapper.FORMATTER));
      } else if (bindingValue instanceof LocalDateTime) {
        queryBuilder.setBinding(bindingName,
            ((LocalDateTime) bindingValue).format(LocalDateTimeMapper.FORMATTER));
      } else if (bindingValue instanceof OffsetDateTime) {
        queryBuilder.setBinding(bindingName, toTimestamp((OffsetDateTime) bindingValue));
      } else if (bindingValue instanceof ZonedDateTime) {
        queryBuilder.setBinding(bindingName, toTimestamp((ZonedDateTime) bindingValue));
      } else if (bindingValue instanceof byte[]) {
        queryBuilder.setBinding(bindingName, Blob.copyFrom((byte[]) bindingValue));
      } else if (bindingValue instanceof DatastoreKey) {
        queryBuilder.setBinding(bindingName, ((DatastoreKey) bindingValue).nativeKey());
      } else if (bindingValue instanceof DatastoreCursor) {
        queryBuilder.setBinding(bindingName,
            Cursor.fromUrlSafe(((DatastoreCursor) bindingValue).getEncoded()));
      } else if (bindingValue instanceof GeoLocation) {
        // TODO no support for GeoLocation in the gcloud API
      }
    }
  }
}