Skip to content

Update the documentation with Relational Queries and Count Objects #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 6, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -106,6 +106,54 @@ The features available are:-
* Ascending
* Descending
* Plenty more!

## Relational queries
If you want to retrieve objects where a field contains an object that matches another query, you can use the
__whereMatchesQuery__ condition.
For example, imagine you vave Post class and a Comment class, where each Comment has a pointer to its parent Post.
You can find comments on posts with images by doing:

```dart
QueryBuilder<ParseObject> queryPost =
QueryBuilder<ParseObject>(ParseObject('Post'))
..whereValueExists('image', true);
QueryBuilder<ParseObject> queryComment =
QueryBuilder<ParseObject>(ParseObject('Comment'))
..whereMatchesQuery('post', queryPost);
var apiResponse = await queryComment.query();
```

If you want to retrieve objects where a field contains an object that does not match another query, you can use the
__whereDoesNotMatchQuery__ condition.
Imagine you have Post class and a Comment class, where each Comment has a pointer to its parent Post.
You can find comments on posts without images by doing:

```dart
QueryBuilder<ParseObject> queryPost =
QueryBuilder<ParseObject>(ParseObject('Post'))
..whereValueExists('image', true);
QueryBuilder<ParseObject> queryComment =
QueryBuilder<ParseObject>(ParseObject('Comment'))
..whereDoesNotMatchQuery('post', queryPost);
var apiResponse = await queryComment.query();
```

## Counting Objects
If you only care about the number of games played by a particular player:

```dart
QueryBuilder<ParseObject> queryPlayers =
QueryBuilder<ParseObject>(ParseObject('GameScore'))
..whereEqualTo('playerName', 'Jonathan Walsh');
var apiResponse = await queryPlayers.count();
if (apiResponse.success && apiResponse.result != null) {
int countGames = apiResponse.count;
}
```

## Objects

62 changes: 56 additions & 6 deletions lib/src/network/parse_query.dart
Original file line number Diff line number Diff line change
@@ -237,19 +237,52 @@ class QueryBuilder<T extends ParseObject> {
'\"$column\":{\"\$within\":{\"\$box\": [{\"__type\": \"GeoPoint\",\"latitude\":$latitudeS,\"longitude\":$longitudeS},{\"__type\": \"GeoPoint\",\"latitude\":$latitudeN,\"longitude\":$longitudeN}]}}'));
}

// Add a constraint to the query that requires a particular key's value match another QueryBuilder
void whereMatchesQuery(String column, QueryBuilder query) {
String inQuery = query._buildQueryRelational(query.object.className);

queries.add(MapEntry<String, dynamic>(
_SINGLE_QUERY, '\"$column\":{\"\$inQuery\":$inQuery}'));
}

//Add a constraint to the query that requires a particular key's value does not match another QueryBuilder
void whereDoesNotMatchQuery(String column, QueryBuilder query) {
String inQuery = query._buildQueryRelational(query.object.className);

queries.add(MapEntry<String, dynamic>(
_SINGLE_QUERY, '\"$column\":{\"\$notInQuery\":$inQuery}'));
}

/// Finishes the query and calls the server
///
/// Make sure to call this after defining your queries
Future<ParseResponse> query() async {
return object.query(_buildQuery());
}

///Counts the number of objects that match this query
Future<ParseResponse> count() async {
return object.query(_buildQueryCount());
}

/// Builds the query for Parse
String _buildQuery() {
queries = _checkForMultipleColumnInstances(queries);
return 'where={${buildQueries(queries)}}${getLimiters(limiters)}';
}

/// Builds the query relational for Parse
String _buildQueryRelational(String className) {
queries = _checkForMultipleColumnInstances(queries);
return '{\"where\":{${buildQueries(queries)}},\"className\":\"$className\"${getLimitersRelational(limiters)}}';
}

/// Builds the query for Parse
String _buildQueryCount() {
queries = _checkForMultipleColumnInstances(queries);
return 'where={${buildQueries(queries)}}&count=1';
}

/// Runs through all queries and adds them to a query string
String buildQueries(List<MapEntry<String, dynamic>> queries) {
String queryBuilder = '';
@@ -284,17 +317,20 @@ class QueryBuilder<T extends ParseObject> {
/// that the column and value are being queried against
MapEntry<String, dynamic> _buildQueryWithColumnValueAndOperator(
MapEntry columnAndValue, String queryOperator) {

final String key = columnAndValue.key;
final dynamic value = convertValueToCorrectType(parseEncode(columnAndValue.value));
final dynamic value =
convertValueToCorrectType(parseEncode(columnAndValue.value));

if (queryOperator == _NO_OPERATOR_NEEDED) {
return MapEntry<String, dynamic>(_NO_OPERATOR_NEEDED, '\"$key\": ${jsonEncode(value)}');
return MapEntry<String, dynamic>(
_NO_OPERATOR_NEEDED, '\"$key\": ${jsonEncode(value)}');
} else {
String queryString = '\"$key\":';
final Map<String, dynamic> queryOperatorAndValueMap = Map<String, dynamic>();
final Map<String, dynamic> queryOperatorAndValueMap =
Map<String, dynamic>();
queryOperatorAndValueMap[queryOperator] = parseEncode(value);
final String formattedQueryOperatorAndValue = jsonEncode(queryOperatorAndValueMap);
final String formattedQueryOperatorAndValue =
jsonEncode(queryOperatorAndValueMap);
queryString += '$formattedQueryOperatorAndValue';
return MapEntry<String, dynamic>(key, queryString);
}
@@ -336,7 +372,8 @@ class QueryBuilder<T extends ParseObject> {
for (MapEntry<String, dynamic> queryToCompact in listOfQueriesCompact) {
var queryToCompactValue = queryToCompact.value.toString();
queryToCompactValue = queryToCompactValue.replaceFirst("{", "");
queryToCompactValue = queryToCompactValue.replaceRange(queryToCompactValue.length - 1, queryToCompactValue.length, "");
queryToCompactValue = queryToCompactValue.replaceRange(
queryToCompactValue.length - 1, queryToCompactValue.length, "");
if (listOfQueriesCompact.first == queryToCompact) {
queryEnd += queryToCompactValue.replaceAll(queryStart, ' ');
} else {
@@ -364,4 +401,17 @@ class QueryBuilder<T extends ParseObject> {
});
return result;
}

/// Adds the limiters to the query relational, i.e. skip=10, limit=10
String getLimitersRelational(Map<String, dynamic> map) {
String result = '';
map.forEach((String key, dynamic value) {
if (result != null) {
result = result + ',\"$key":$value';
} else {
result = '\"$key\":$value';
}
});
return result;
}
}
5 changes: 5 additions & 0 deletions lib/src/objects/response/parse_response_builder.dart
Original file line number Diff line number Diff line change
@@ -71,6 +71,11 @@ class _ParseResponseBuilder {
response.results = items;
response.result = items;
response.count = items.length;
} else if (map != null && map.length == 2 && map.containsKey('count')) {
final List<int> results = [map['count']];
response.results = results;
response.result = results;
response.count = map['count'];
} else {
final T item = _handleSingleResult<T>(object, map, false);
response.count = 1;