/// <summary> /// Filters a query based upon the predicate provided. /// </summary> /// <typeparam name="TSource">The type of ParseObject being queried for.</typeparam> /// <param name="source">The base <see cref="ParseQuery{TSource}"/> to which /// the predicate will be added.</param> /// <param name="predicate">A function to test each ParseObject for a condition. /// The predicate must be able to be represented by one of the standard Where /// functions on ParseQuery</param> /// <returns>A new ParseQuery whose results will match the given predicate as /// well as the source's filters.</returns> public static ParseQuery <TSource> Where <TSource>( this ParseQuery <TSource> source, Expression <Func <TSource, bool> > predicate) where TSource : ParseObject { // Handle top-level logic operators && and || var binaryExpression = predicate.Body as BinaryExpression; if (binaryExpression != null) { if (binaryExpression.NodeType == ExpressionType.AndAlso) { return(source .Where(Expression.Lambda <Func <TSource, bool> >( binaryExpression.Left, predicate.Parameters)) .Where(Expression.Lambda <Func <TSource, bool> >( binaryExpression.Right, predicate.Parameters))); } if (binaryExpression.NodeType == ExpressionType.OrElse) { var left = source.Where(Expression.Lambda <Func <TSource, bool> >( binaryExpression.Left, predicate.Parameters)); var right = source.Where(Expression.Lambda <Func <TSource, bool> >( binaryExpression.Right, predicate.Parameters)); return(left.Or(right)); } } var normalized = new WhereNormalizer().Visit(predicate.Body); var methodCallExpr = normalized as MethodCallExpression; if (methodCallExpr != null) { return(source.WhereMethodCall(predicate, methodCallExpr)); } var binaryExpr = normalized as BinaryExpression; if (binaryExpr != null) { return(source.WhereBinaryExpression(predicate, binaryExpr)); } if (!(normalized is UnaryExpression unaryExpr) || unaryExpr.NodeType != ExpressionType.Not) { throw new InvalidOperationException( "Encountered an unsupported expression for ParseQueries."); } if (unaryExpr.Operand is MethodCallExpression node && (IsParseObjectGet(node) && (node.Type == typeof(bool) || node.Type == typeof(bool?)))) { // This is a raw boolean field access like 'where !obj.Get<bool>("foo")' return(source.WhereNotEqualTo(GetValue(node.Arguments[0]) as string, true)); } throw new InvalidOperationException( "Encountered an unsupported expression for ParseQueries."); }
/// <summary> /// Adds a constraint to the query that requires that a particular key's value /// matches another ParseQuery. This only works on keys whose values are /// ParseObjects or lists of ParseObjects. /// </summary> /// <param name="key">The key to check.</param> /// <param name="query">The query that the value should match.</param> /// <returns>A new query with the additional constraint.</returns> public ParseQuery <T> WhereMatchesQuery <TOther>(string key, ParseQuery <TOther> query) where TOther : ParseObject { return(new ParseQuery <T>(this, @where: new Dictionary <string, object> { { key, new Dictionary <string, object> { { "$inQuery", query.BuildParameters(true) } } } })); }
/// <summary> /// Converts a normalized binary expression into the appropriate ParseQuery clause. /// </summary> private static ParseQuery <T> WhereBinaryExpression <T>( this ParseQuery <T> source, Expression <Func <T, bool> > expression, BinaryExpression node) where T : ParseObject { var leftTransformed = new ObjectNormalizer().Visit(node.Left) as MethodCallExpression; if (leftTransformed != null && !(IsParseObjectGet(leftTransformed) && leftTransformed.Object == expression.Parameters[0])) { throw new InvalidOperationException( "Where expressions must have one side be a field operation on a ParseObject."); } if (leftTransformed != null) { var fieldPath = GetValue(leftTransformed.Arguments[0]) as string; var filterValue = GetValue(node.Right); if (filterValue != null && !ParseEncoder.IsValidType(filterValue)) { throw new InvalidOperationException( "Where clauses must use types compatible with ParseObjects."); } switch (node.NodeType) { case ExpressionType.GreaterThan: return(source.WhereGreaterThan(fieldPath, filterValue)); case ExpressionType.GreaterThanOrEqual: return(source.WhereGreaterThanOrEqualTo(fieldPath, filterValue)); case ExpressionType.LessThan: return(source.WhereLessThan(fieldPath, filterValue)); case ExpressionType.LessThanOrEqual: return(source.WhereLessThanOrEqualTo(fieldPath, filterValue)); case ExpressionType.Equal: return(source.WhereEqualTo(fieldPath, filterValue)); case ExpressionType.NotEqual: return(source.WhereNotEqualTo(fieldPath, filterValue)); default: throw new InvalidOperationException( "Where expressions do not support this operator."); } } return(null); }
/// <summary> /// Adds a constraint to the query that requires a particular key's value /// does not match any value for a key in the results of another ParseQuery. /// </summary> /// <param name="key">The key whose value is being checked.</param> /// <param name="keyInQuery">The key in the objects from the subquery to look in.</param> /// <param name="query">The subquery to run</param> /// <returns>A new query with the additional constraint.</returns> public ParseQuery <T> WhereDoesNotMatchesKeyInQuery <TOther>(string key, string keyInQuery, ParseQuery <TOther> query) where TOther : ParseObject { var parameters = new Dictionary <string, object> { { "query", query.BuildParameters(true) }, { "key", keyInQuery } }; return(new ParseQuery <T>(this, @where: new Dictionary <string, object> { { key, new Dictionary <string, object> { { "$dontSelect", parameters } } } })); }
/// <summary> /// Constructs a ParseObject whose id is already known by fetching data /// from the server. /// </summary> /// <param name="objectId">ObjectId of the ParseObject to fetch.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The ParseObject for the given objectId.</returns> public Task <T> GetAsync(string objectId, CancellationToken cancellationToken) { ParseQuery <T> singleItemQuery = new ParseQuery <T>(ClassName).WhereEqualTo("objectId", objectId); singleItemQuery = new ParseQuery <T>(singleItemQuery, includes: _includes, selectedKeys: _selectedKeys, limit: 1); return(singleItemQuery.FindAsync(cancellationToken).OnSuccess(t => { var result = t.Result.FirstOrDefault(); if (result == null) { throw new ParseException(ParseException.ErrorCode.ObjectNotFound, "Object with the given objectId not found."); } return result; })); }
/// <summary> /// Constructs a query that is the or of the given queries. /// </summary> /// <typeparam name="T">The type of ParseObject being queried.</typeparam> /// <param name="source">An initial query to 'or' with additional queries.</param> /// <param name="queries">The list of ParseQueries to 'or' together.</param> /// <returns>A query that is the or of the given queries.</returns> public static ParseQuery <T> Or <T>(this ParseQuery <T> source, params ParseQuery <T>[] queries) where T : ParseObject { return(ParseQuery <T> .Or(queries.Concat(new[] { source }))); }
/// <summary> /// Private constructor for composition of queries. A source query is required, /// but the remaining values can be null if they won't be changed in this /// composition. /// </summary> private ParseQuery(ParseQuery <T> source, IDictionary <string, object> where = null, IEnumerable <string> replacementOrderBy = null, IEnumerable <string> thenBy = null, int?skip = null, int?limit = null, IEnumerable <string> includes = null, IEnumerable <string> selectedKeys = null, string redirectClassNameForKey = null) { if (source == null) { throw new ArgumentNullException("source"); } ClassName = source.ClassName; _where = source._where; _orderBy = source._orderBy; _skip = source._skip; _limit = source._limit; _includes = source._includes; _selectedKeys = source._selectedKeys; _redirectClassNameForKey = source._redirectClassNameForKey; if (where != null) { var newWhere = MergeWhereClauses(where); _where = new Dictionary <string, object>(newWhere); } if (replacementOrderBy != null) { _orderBy = new ReadOnlyCollection <string>(replacementOrderBy.ToList()); } if (thenBy != null) { if (_orderBy == null) { throw new ArgumentException("You must call OrderBy before calling ThenBy."); } var newOrderBy = new List <string>(_orderBy); newOrderBy.AddRange(thenBy); _orderBy = new ReadOnlyCollection <string>(newOrderBy); } // Remove duplicates. if (_orderBy != null) { var newOrderBy = new HashSet <string>(_orderBy); _orderBy = new ReadOnlyCollection <string>(newOrderBy.ToList()); } if (skip != null) { _skip = (_skip ?? 0) + skip; } if (limit != null) { _limit = limit; } if (includes != null) { var newIncludes = MergeIncludes(includes); _includes = new ReadOnlyCollection <string>(newIncludes.ToList()); } if (selectedKeys != null) { var newSelectedKeys = MergeSelectedKeys(selectedKeys); _selectedKeys = new ReadOnlyCollection <string>(newSelectedKeys.ToList()); } if (redirectClassNameForKey != null) { _redirectClassNameForKey = redirectClassNameForKey; } }
/// <summary> /// Correlates the elements of two queries based on matching keys. /// </summary> /// <typeparam name="TOuter">The type of ParseObjects of the first query.</typeparam> /// <typeparam name="TInner">The type of ParseObjects of the second query.</typeparam> /// <typeparam name="TKey">The type of the keys returned by the key selector /// functions.</typeparam> /// <typeparam name="TResult">The type of the result. This must match either /// TOuter or TInner</typeparam> /// <param name="outer">The first query to join.</param> /// <param name="inner">The query to join to the first query.</param> /// <param name="outerKeySelector">A function to extract a join key from the results of /// the first query.</param> /// <param name="innerKeySelector">A function to extract a join key from the results of /// the second query.</param> /// <param name="resultSelector">A function to select either the outer or inner query /// result to determine which query is the base query.</param> /// <returns>A new ParseQuery with a WhereMatchesQuery or WhereMatchesKeyInQuery /// clause based upon the query indicated in the <paramref name="resultSelector"/>.</returns> public static ParseQuery <TResult> Join <TOuter, TInner, TKey, TResult>( this ParseQuery <TOuter> outer, ParseQuery <TInner> inner, Expression <Func <TOuter, TKey> > outerKeySelector, Expression <Func <TInner, TKey> > innerKeySelector, Expression <Func <TOuter, TInner, TResult> > resultSelector) where TOuter : ParseObject where TInner : ParseObject where TResult : ParseObject { // resultSelector must select either the inner object or the outer object. If it's the inner // object, reverse the query. if (resultSelector.Body == resultSelector.Parameters[1]) { // The inner object was selected. return(inner.Join( outer, innerKeySelector, outerKeySelector, (i, o) => i) as ParseQuery <TResult>); } if (resultSelector.Body != resultSelector.Parameters[0]) { throw new InvalidOperationException("Joins must select either the outer or inner object."); } // Normalize both selectors var outerNormalized = new ObjectNormalizer().Visit(outerKeySelector.Body); var innerNormalized = new ObjectNormalizer().Visit(innerKeySelector.Body); var outerAsGet = outerNormalized as MethodCallExpression; var innerAsGet = innerNormalized as MethodCallExpression; if (outerAsGet != null && (!IsParseObjectGet(outerAsGet) || outerAsGet.Object != outerKeySelector.Parameters[0])) { throw new InvalidOperationException( "The key for the selected object must be a field access on the ParseObject."); } var outerKey = GetValue(outerAsGet.Arguments[0]) as string; if (innerAsGet != null && (IsParseObjectGet(innerAsGet) && innerAsGet.Object == innerKeySelector.Parameters[0])) { // Both are key accesses, so treat this as a WhereMatchesKeyInQuery var innerKey = GetValue(innerAsGet.Arguments[0]) as string; return(outer.WhereMatchesKeyInQuery(outerKey, innerKey, inner) as ParseQuery <TResult>); } if (innerKeySelector.Body == innerKeySelector.Parameters[0]) { // The inner selector is on the result of the query itself, so treat this as a // WhereMatchesQuery return(outer.WhereMatchesQuery(outerKey, inner) as ParseQuery <TResult>); } throw new InvalidOperationException( "The key for the joined object must be a ParseObject or a field access " + "on the ParseObject."); // TODO (hallucinogen): If we ever support "and" queries fully and/or support a "where this object // matches some key in some other query" (as opposed to requiring a key on this query), we // can add support for even more types of joins. }
/// <summary> /// Performs a subsequent ordering of a query based upon the key selector provided. /// </summary> /// <typeparam name="TSource">The type of ParseObject being queried for.</typeparam> /// <typeparam name="TSelector">The type of key returned by keySelector.</typeparam> /// <param name="source">The query to order.</param> /// <param name="keySelector">A function to extract a key from the ParseObject.</param> /// <returns>A new ParseQuery based on source whose results will be ordered by /// the key specified in the keySelector.</returns> public static ParseQuery <TSource> ThenByDescending <TSource, TSelector>( this ParseQuery <TSource> source, Expression <Func <TSource, TSelector> > keySelector) where TSource : ParseObject { return(source.ThenByDescending(GetOrderByPath(keySelector))); }
/// <summary> /// Converts a normalized method call expression into the appropriate ParseQuery clause. /// </summary> private static ParseQuery <T> WhereMethodCall <T>( this ParseQuery <T> source, Expression <Func <T, bool> > expression, MethodCallExpression node) where T : ParseObject { if (IsParseObjectGet(node) && (node.Type == typeof(bool) || node.Type == typeof(bool?))) { // This is a raw boolean field access like 'where obj.Get<bool>("foo")' return(source.WhereEqualTo(GetValue(node.Arguments[0]) as string, true)); } MethodInfo translatedMethod; if (FunctionMappings.TryGetValue(node.Method, out translatedMethod)) { var objTransformed = new ObjectNormalizer().Visit(node.Object) as MethodCallExpression; if (objTransformed != null && !(IsParseObjectGet(objTransformed) && objTransformed.Object == expression.Parameters[0])) { throw new InvalidOperationException( "The left-hand side of a supported function call must be a ParseObject field access."); } if (objTransformed != null) { var fieldPath = GetValue(objTransformed.Arguments[0]); var containedIn = GetValue(node.Arguments[0]); var queryType = translatedMethod.DeclaringType.GetGenericTypeDefinition() .MakeGenericType(typeof(T)); translatedMethod = ReflectionHelpers.GetMethod(queryType, translatedMethod.Name, translatedMethod.GetParameters().Select(p => p.ParameterType).ToArray()); return(translatedMethod.Invoke(source, new[] { fieldPath, containedIn }) as ParseQuery <T>); } } if (node.Arguments[0] == expression.Parameters[0]) { // obj.ContainsKey("foo") --> query.WhereExists("foo") if (node.Method == ContainsKeyMethod) { return(source.WhereExists(GetValue(node.Arguments[1]) as string)); } // !obj.ContainsKey("foo") --> query.WhereDoesNotExist("foo") if (node.Method == NotContainsKeyMethod) { return(source.WhereDoesNotExist(GetValue(node.Arguments[1]) as string)); } } if (node.Method.IsGenericMethod) { if (node.Method.GetGenericMethodDefinition() == ContainsMethod) { // obj.Get<IList<T>>("path").Contains(someValue) if (IsParseObjectGet(node.Arguments[0] as MethodCallExpression)) { return(source.WhereEqualTo( GetValue(((MethodCallExpression)node.Arguments[0]).Arguments[0]) as string, GetValue(node.Arguments[1]))); } // someList.Contains(obj.Get<T>("path")) if (IsParseObjectGet(node.Arguments[1] as MethodCallExpression)) { var collection = GetValue(node.Arguments[0]) as System.Collections.IEnumerable; return(source.WhereContainedIn( GetValue(((MethodCallExpression)node.Arguments[1]).Arguments[0]) as string, collection.Cast <object>())); } } if (node.Method.GetGenericMethodDefinition() == NotContainsMethod) { // !obj.Get<IList<T>>("path").Contains(someValue) if (IsParseObjectGet(node.Arguments[0] as MethodCallExpression)) { return(source.WhereNotEqualTo( GetValue(((MethodCallExpression)node.Arguments[0]).Arguments[0]) as string, GetValue(node.Arguments[1]))); } // !someList.Contains(obj.Get<T>("path")) if (IsParseObjectGet(node.Arguments[1] as MethodCallExpression)) { var collection = GetValue(node.Arguments[0]) as System.Collections.IEnumerable; return(source.WhereNotContainedIn( GetValue(((MethodCallExpression)node.Arguments[1]).Arguments[0]) as string, collection.Cast <object>())); } } } throw new InvalidOperationException(node.Method + " is not a supported method call in a where expression."); }