public static LeanAccount findAccountByEmail(String email, String provider) { if (email == null) { log.severe("Empty email. Can not find account without email."); return null; } Query query = new Query(accountsKind); query.addFilter("email", Query.FilterOperator.EQUAL, email); query.addFilter("_provider", Query.FilterOperator.EQUAL, provider); PreparedQuery pq = datastore.prepare(query); Entity accountEntity = pq.asSingleEntity(); return (accountEntity == null) ? null : toLeanAccount(accountEntity); }
public static LeanAccount findAccountByProvider(String providerID, String provider) { if (providerID == null) { log.severe("Empty providerID. Can not find account without providerID."); return null; } Query query = new Query(accountsKind); query.addFilter("_provider_id", Query.FilterOperator.EQUAL, providerID); query.addFilter("_provider", Query.FilterOperator.EQUAL, provider); PreparedQuery pq = datastore.prepare(query); Entity accountEntity = pq.asSingleEntity(); return (accountEntity == null) ? null : toLeanAccount(accountEntity); }
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query gaeQuery = new Query(entityName); gaeQuery.setKeysOnly(); gaeQuery.addFilter("__key__", FilterOperator.EQUAL, key); PreparedQuery pq = datastore.prepare(gaeQuery); List<Entity> results = pq.asList(FetchOptions.Builder.withLimit(1)); Key elementKey = null; if (results.size() == 1) { elementKey = results.get(0).getKey(); }
/** */ public QueryImpl(ObjectifyFactory fact, Objectify objectify, Class<T> clazz) { this.factory = fact; this.ofy = objectify; this.actual = new com.google.appengine.api.datastore.Query(Key.getKind(clazz)); // If this is a polymorphic subclass, add an extra filter Subclass sub = clazz.getAnnotation(Subclass.class); if (sub != null) { String discriminator = sub.name().length() > 0 ? sub.name() : clazz.getSimpleName(); this.actual.addFilter(PolymorphicEntityMetadata.DISCRIMINATOR_INDEX_PROPERTY, FilterOperator.EQUAL, discriminator); } this.classRestriction = clazz; }
qd.primaryDatastoreQuery.addFilter(entry.getKey(), Query.FilterOperator.IN, entry.getValue());
public static List<Entity> getPrivateEntities(String kind) throws LeanException { if (!pattern.matcher(kind).matches()) { throw new LeanException(LeanException.Error.IllegalEntityName); } LeanAccount account = AuthService.getCurrentAccount(); // this should not happen, but we check anyway if (account == null) throw new LeanException(LeanException.Error.NotAuthorized); Query query = new Query(kind); query.addFilter("_account", Query.FilterOperator.EQUAL, account.id); PreparedQuery pq = datastore.prepare(query); return pq.asList(FetchOptions.Builder.withDefaults()); }
private void handleValueComparisonCondition(ValueComparisonCondition<Entity, Object> ccc, Query query, List<ColumnCondition<Entity, Object>> locals, TableMetadata kindStats) { String property = ccc.getColumn(); if (kindStats != null) { ColumnMetadata propertyStats = kindStats.getColumnMetadata(property); if (propertyStats != null && propertyStats.isIndexed()) { query.addFilter(property, convertRelation(ccc.getRelation()), ccc.getValue()); return; } } locals.add(ccc); }
this.actual.addFilter(prop, op, value);
/** * Method to add a filter to restrict any multitenancy discriminator to a valid value. * @param qd QueryData */ private void addMultitenancyDiscriminator(QueryData qd) { if (getStoreManager().getStringProperty(PropertyNames.PROPERTY_TENANT_ID) != null) { if ("true".equalsIgnoreCase(qd.acmd.getValueForExtension("multitenancy-disable"))) { } else { // Restrict to the current tenant String multitenantPropName = getStoreManager().getNamingFactory().getColumnName(qd.acmd, ColumnType.MULTITENANCY_COLUMN); qd.primaryDatastoreQuery.addFilter(multitenantPropName, Query.FilterOperator.EQUAL, getStoreManager().getStringProperty(PropertyNames.PROPERTY_TENANT_ID)); } } }
if (propertyStats != null && propertyStats.isIndexed()) query.addFilter(property, Query.FilterOperator.EQUAL, columnValues.first()); if (propertyStats != null && propertyStats.isIndexed()) query.addFilter(property, Query.FilterOperator.GREATER_THAN_OR_EQUAL, columnValues.first()); query.addFilter(property, Query.FilterOperator.LESS_THAN_OR_EQUAL, columnValues.last());
/** * Method to add a filter to restrict any discriminator property to valid values. * @param qd QueryData * @param clr ClassLoader resolver */ private void addDiscriminator(QueryData qd, ClassLoaderResolver clr) { if (qd.acmd.hasDiscriminatorStrategy()) { String className = qd.acmd.getFullClassName(); boolean includeSubclasses = query.isSubclasses(); DatastoreManager storeMgr = getStoreManager(); String discriminatorPropertyName = EntityUtils.getDiscriminatorPropertyName(storeMgr.getIdentifierFactory(), qd.acmd.getDiscriminatorMetaDataRoot()); // Note : we always restrict the discriminator since the user may at some later point add other classes // to be persisted here, or have others that have data but aren't currently active in the persistence process List<Object> discriminatorValues = new ArrayList<Object>(); discriminatorValues.add(qd.acmd.getDiscriminatorValue()); if (includeSubclasses) { for (String subClassName : storeMgr.getSubClassesForClass(className, true, clr)) { AbstractClassMetaData subCmd = storeMgr.getMetaDataManager().getMetaDataForClass(subClassName, clr); discriminatorValues.add(subCmd.getDiscriminatorValue()); } } qd.primaryDatastoreQuery.addFilter(discriminatorPropertyName, Query.FilterOperator.IN, discriminatorValues); } }
protected int[] internalShift(ObjectProvider op, boolean batched, int oldIndex, int amount) throws MappedDatastoreException { if (orderMapping == null) { return null; } DatastoreServiceConfig config = storeMgr.getDefaultDatastoreServiceConfigForReads(); DatastoreService service = DatastoreServiceFactoryInternal.getDatastoreService(config); AbstractClassMetaData acmd = elementCmd; String kind = storeMgr.getIdentifierFactory().newDatastoreContainerIdentifier(acmd).getIdentifierName(); Query q = new Query(kind); ExecutionContext ec = op.getExecutionContext(); Object id = ec.getApiAdapter().getTargetKeyForSingleFieldIdentity(op.getInternalObjectId()); Key key = id instanceof Key ? (Key) id : KeyFactory.stringToKey((String) id); q.setAncestor(key); // create an entity just to capture the name of the index property Entity entity = new Entity(kind); orderMapping.setObject(ec, entity, new int[] {1}, oldIndex); String indexProp = entity.getProperties().keySet().iterator().next(); q.addFilter(indexProp, Query.FilterOperator.GREATER_THAN_OR_EQUAL, oldIndex); for (Entity shiftMe : service.prepare(service.getCurrentTransaction(null), q).asIterable()) { Long pos = (Long) shiftMe.getProperty(indexProp); shiftMe.setProperty(indexProp, pos + amount); EntityUtils.putEntityIntoDatastore(ec, shiftMe); } return null; }
/** * Make a new Query object that is exactly like the old. Too bad Query isn't Cloneable. */ protected com.google.appengine.api.datastore.Query cloneRawQuery(com.google.appengine.api.datastore.Query orig) { com.google.appengine.api.datastore.Query copy = new com.google.appengine.api.datastore.Query(orig.getKind(), orig.getAncestor()); for (FilterPredicate filter: orig.getFilterPredicates()) copy.addFilter(filter.getPropertyName(), filter.getOperator(), filter.getValue()); for (SortPredicate sort: orig.getSortPredicates()) copy.addSort(sort.getPropertyName(), sort.getDirection()); // This should be impossible but who knows what might happen in the future if (orig.isKeysOnly()) copy.setKeysOnly(); return copy; }
orderMapping.setObject(ec, entity, new int[] {1}, index); String indexProp = entity.getProperties().keySet().iterator().next(); q.addFilter(indexProp, Query.FilterOperator.GREATER_THAN, index); for (Entity shiftMe : service.prepare(service.getCurrentTransaction(null), q).asIterable()) { Long pos = (Long) shiftMe.getProperty(indexProp);
ListIterator<?> getChildrenByKeys(List<Key> childKeys, final ExecutionContext ec) { String kindName = elementTable.getIdentifier().getIdentifierName(); Query q = new Query(kindName); NucleusLogger.PERSISTENCE.debug("Preparing to query for " + childKeys); q.addFilter(Entity.KEY_RESERVED_PROPERTY, Query.FilterOperator.IN, childKeys); for (Query.SortPredicate sp : getSortPredicates()) { q.addSort(sp.getPropertyName(), sp.getDirection()); } DatastoreServiceConfig config = storeMgr.getDefaultDatastoreServiceConfigForReads(); DatastoreService ds = DatastoreServiceFactoryInternal.getDatastoreService(config); Utils.Function<Entity, Object> func = new Utils.Function<Entity, java.lang.Object>() { @Override public Object apply(Entity from) { return EntityUtils.entityToPojo(from, elementCmd, clr, ec, false, ec.getFetchPlan()); } }; return new LazyResult(ds.prepare(q).asIterable(), func, true).listIterator(); }
public static QueryResult queryEntityPrivate(LeanQuery leanQuery) throws LeanException { LeanAccount account = findCurrentAccount(); Query query = new Query(leanQuery.getKind()); query.addFilter("_account", Query.FilterOperator.EQUAL, account.id); for (QueryFilter queryFilter : leanQuery.getFilters()) { query.addFilter( queryFilter.getProperty(), queryFilter.getOperator().getFilterOperator(), queryFilter.getValue()); } for (QuerySort querySort : leanQuery.getSorts()) { query.addSort(querySort.getProperty(), querySort.getDirection().getSortDirection()); } FetchOptions fetchOptions = FetchOptions.Builder.withDefaults(); if(leanQuery.getCursor() != null ) fetchOptions.startCursor(leanQuery.getCursor()); if(leanQuery.getOffset() != null) fetchOptions.offset(leanQuery.getOffset()); if(leanQuery.getLimit() != null) fetchOptions.limit(leanQuery.getLimit()); try { PreparedQuery pq = datastore.prepare(query); QueryResultList<Entity> result; result = pq.asQueryResultList(fetchOptions); return new QueryResult(result, result.getCursor()); } catch (DatastoreNeedIndexException dnie) { throw new LeanException(LeanException.Error.AppEngineMissingIndex); } }
@SuppressWarnings("deprecation") @Test public void testDeprecatedFiltersAreSupported() throws Exception { Key parentKey = createQueryBasicsTestParent("testDeprecatedFiltersAreSupported"); Entity johnDoe = createEntity("Person", parentKey) .withProperty("name", "John") .withProperty("lastName", "Doe") .store(); Entity johnBooks = createEntity("Person", parentKey) .withProperty("name", "John") .withProperty("lastName", "Books") .store(); Entity janeDoe = createEntity("Person", parentKey) .withProperty("name", "Jane") .withProperty("lastName", "Doe") .store(); Query query = new Query("Person") .setAncestor(parentKey) .addFilter("name", EQUAL, "John") .addFilter("lastName", EQUAL, "Doe"); assertSingleResult(johnDoe, query); }
/** * Method to create a PreparedQuery, for the specified filter and ordering, to get the child objects of a parent. * @param parentKey Key of the parent * @param filterPredicates Filtering required * @param sortPredicates Ordering required * @param keysOnly Whether to just returns the keys of the children * @param kindName Name of the kind that we are querying * @return The PreparedQuery */ PreparedQuery prepareChildrenQuery(Key parentKey, Iterable<FilterPredicate> filterPredicates, Iterable<SortPredicate> sortPredicates, boolean keysOnly, String kindName) { Query q = new Query(kindName, parentKey); if (keysOnly) { q.setKeysOnly(); } NucleusLogger.PERSISTENCE.debug("Preparing to query for all children of " + parentKey + " of kind " + kindName); for (FilterPredicate fp : filterPredicates) { q.addFilter(fp.getPropertyName(), fp.getOperator(), fp.getValue()); NucleusLogger.PERSISTENCE.debug(" Added filter: " + fp.getPropertyName() + " " + fp.getOperator() + " " + fp.getValue()); } for (SortPredicate sp : sortPredicates) { q.addSort(sp.getPropertyName(), sp.getDirection()); NucleusLogger.PERSISTENCE.debug(" Added sort: " + sp.getPropertyName() + " " + sp.getDirection()); } DatastoreServiceConfig config = storeMgr.getDefaultDatastoreServiceConfigForReads(); DatastoreService ds = DatastoreServiceFactoryInternal.getDatastoreService(config); return ds.prepare(q); }