Merge pull request #254 from realm/al-filtered

Add filtered method to List and Results
This commit is contained in:
Ari Lazier 2016-02-17 21:32:28 -08:00
commit d70de00923
12 changed files with 154 additions and 65 deletions

View File

@ -52,9 +52,10 @@ export default class TodoApp extends Component {
} }
render() { render() {
let objects = realm.objects('Todo');
let extraItems = [ let extraItems = [
{name: 'Complete', items: realm.objects('Todo', 'done = true')}, {name: 'Complete', items: objects.filtered('done = true')},
{name: 'Incomplete', items: realm.objects('Todo', 'done = false')}, {name: 'Incomplete', items: objects.filtered('Todo', 'done = false')},
]; ];
let route = { let route = {

View File

@ -135,12 +135,12 @@ class RealmTests extends Tests {
} }
async querycount() { async querycount() {
let objects = this.realm.objects('TestObject', 'int = 0 and double < ' + numBatchTestObjects / 2); let objects = this.realm.objects('TestObject').filtered('int = 0 and double < ' + numBatchTestObjects / 2);
return objects.length; return objects.length;
} }
async queryenum() { async queryenum() {
let objects = this.realm.objects('TestObject', 'int = 0 and double < ' + numBatchTestObjects / 2); let objects = this.realm.objects('TestObject').filtered('int = 0 and double < ' + numBatchTestObjects / 2);
let len = objects.length; let len = objects.length;
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
var obj = objects[i]; var obj = objects[i];

View File

@ -17,6 +17,7 @@ class List {}
// Non-mutating methods: // Non-mutating methods:
util.createMethods(List.prototype, objectTypes.LIST, [ util.createMethods(List.prototype, objectTypes.LIST, [
'filtered',
'snapshot', 'snapshot',
]); ]);

View File

@ -14,6 +14,7 @@ module.exports = {
class Results {} class Results {}
util.createMethods(Results.prototype, constants.objectTypes.RESULTS, [ util.createMethods(Results.prototype, constants.objectTypes.RESULTS, [
'filtered',
'snapshot', 'snapshot',
'sortByProperty', 'sortByProperty',
]); ]);

View File

@ -6,7 +6,10 @@
#include "js_object.hpp" #include "js_object.hpp"
#include "js_results.hpp" #include "js_results.hpp"
#include "js_util.hpp" #include "js_util.hpp"
#include "object_accessor.hpp" #include "object_accessor.hpp"
#include "parser.hpp"
#include "query_builder.hpp"
#include <assert.h> #include <assert.h>
@ -188,9 +191,23 @@ JSValueRef ListStaticResults(JSContextRef ctx, JSObjectRef function, JSObjectRef
try { try {
List *list = RJSGetInternal<List *>(thisObject); List *list = RJSGetInternal<List *>(thisObject);
RJSValidateArgumentCount(argumentCount, 0); RJSValidateArgumentCount(argumentCount, 0);
return RJSResultsCreate(ctx, list->realm(), list->get_object_schema(), std::move(list->get_query()), false);
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
Query query = list->get_query(); JSValueRef ListFiltered(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
return RJSResultsCreate(ctx, list->realm(), list->get_object_schema(), query, false); try {
List *list = RJSGetInternal<List *>(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 1);
SharedRealm sharedRealm = *RJSGetInternal<SharedRealm *>(thisObject);
return RJSResultsCreate(ctx, sharedRealm, list->get_object_schema(), std::move(list->get_query()), argumentCount, arguments);
} }
catch (std::exception &exp) { catch (std::exception &exp) {
if (jsException) { if (jsException) {
@ -210,6 +227,7 @@ static const JSStaticFunction RJSListFuncs[] = {
{"shift", ListShift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"shift", ListShift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"unshift", ListUnshift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"unshift", ListUnshift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"splice", ListSplice, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"splice", ListSplice, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"filtered", ListFiltered, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"snapshot", ListStaticResults, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"snapshot", ListStaticResults, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL}, {NULL, NULL},
}; };

View File

@ -226,21 +226,10 @@ JSValueRef RealmGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef pr
JSValueRef RealmObjects(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) { JSValueRef RealmObjects(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try { try {
RJSValidateArgumentCountIsAtLeast(argumentCount, 1); RJSValidateArgumentCount(1, argumentCount);
std::string className = RJSValidatedStringForValue(ctx, arguments[0], "objectType"); std::string className = RJSValidatedStringForValue(ctx, arguments[0], "objectType");
SharedRealm sharedRealm = *RJSGetInternal<SharedRealm *>(thisObject); SharedRealm sharedRealm = *RJSGetInternal<SharedRealm *>(thisObject);
return RJSResultsCreate(ctx, sharedRealm, className);
if (argumentCount == 1) {
return RJSResultsCreate(ctx, sharedRealm, className);
}
else {
std::string query = RJSValidatedStringForValue(ctx, arguments[1], "predicate");
std::vector<JSValueRef> args;
for (size_t i = 2; i < argumentCount; i++) {
args.push_back(arguments[i]);
}
return RJSResultsCreate(ctx, sharedRealm, className, query, args);
}
} }
catch (std::exception &exp) { catch (std::exception &exp) {
if (jsException) { if (jsException) {

View File

@ -117,6 +117,23 @@ JSValueRef ResultsSortByProperty(JSContextRef ctx, JSObjectRef function, JSObjec
return NULL; return NULL;
} }
JSValueRef ResultsFiltered(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
Results *results = RJSGetInternal<Results *>(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 1);
SharedRealm sharedRealm = *RJSGetInternal<SharedRealm *>(thisObject);
return RJSResultsCreate(ctx, sharedRealm, results->get_object_schema(), std::move(results->get_query()), argumentCount, arguments);
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSObjectRef RJSResultsCreate(JSContextRef ctx, SharedRealm realm, std::string className) { JSObjectRef RJSResultsCreate(JSContextRef ctx, SharedRealm realm, std::string className) {
TableRef table = ObjectStore::table_for_object_type(realm->read_group(), className); TableRef table = ObjectStore::table_for_object_type(realm->read_group(), className);
auto object_schema = realm->config().schema->find(className); auto object_schema = realm->config().schema->find(className);
@ -141,8 +158,22 @@ JSObjectRef RJSResultsCreate(JSContextRef ctx, SharedRealm realm, std::string cl
return RJSWrapObject<Results *>(ctx, RJSResultsClass(), new Results(realm, *object_schema, std::move(query))); return RJSWrapObject<Results *>(ctx, RJSResultsClass(), new Results(realm, *object_schema, std::move(query)));
} }
JSObjectRef RJSResultsCreate(JSContextRef ctx, SharedRealm realm, const ObjectSchema &objectSchema, const Query &query, bool live) { JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, const realm::ObjectSchema &objectSchema, realm::Query query, size_t argumentCount, const JSValueRef arguments[]) {
Results *results = new Results(realm, objectSchema, query); std::string queryString = RJSValidatedStringForValue(ctx, arguments[0], "predicate");
std::vector<JSValueRef> args(argumentCount - 1);
for (size_t i = 1; i < argumentCount; i++) {
args[i-1] = arguments[i];
}
parser::Predicate predicate = parser::parse(queryString);
query_builder::ArgumentConverter<JSValueRef, JSContextRef> queryArgs(ctx, args);
query_builder::apply_predicate(query, predicate, queryArgs, *realm->config().schema, objectSchema.name);
return RJSResultsCreate(ctx, realm, objectSchema, std::move(query));
}
JSObjectRef RJSResultsCreate(JSContextRef ctx, SharedRealm realm, const ObjectSchema &objectSchema, Query query, bool live) {
Results *results = new Results(realm, objectSchema, std::move(query));
results->set_live(live); results->set_live(live);
return RJSWrapObject<Results *>(ctx, RJSResultsClass(), results); return RJSWrapObject<Results *>(ctx, RJSResultsClass(), results);
@ -151,6 +182,7 @@ JSObjectRef RJSResultsCreate(JSContextRef ctx, SharedRealm realm, const ObjectSc
static const JSStaticFunction RJSResultsFuncs[] = { static const JSStaticFunction RJSResultsFuncs[] = {
{"snapshot", ResultsStaticCopy, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"snapshot", ResultsStaticCopy, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"sortByProperty", ResultsSortByProperty, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"sortByProperty", ResultsSortByProperty, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"filtered", ResultsFiltered, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL}, {NULL, NULL},
}; };

View File

@ -16,4 +16,6 @@ namespace realm {
JSClassRef RJSResultsClass(); JSClassRef RJSResultsClass();
JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, std::string className); JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, std::string className);
JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, std::string className, std::string query, std::vector<JSValueRef> args); JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, std::string className, std::string query, std::vector<JSValueRef> args);
JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, const realm::ObjectSchema &objectSchema, const realm::Query &query, bool live = true); JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, const realm::ObjectSchema &objectSchema, realm::Query query, size_t argumentCount, const JSValueRef arguments[]);
JSObjectRef RJSResultsCreate(JSContextRef ctx, realm::SharedRealm realm, const realm::ObjectSchema &objectSchema, realm::Query query, bool live = true);

View File

@ -443,4 +443,31 @@ module.exports = BaseTest.extend({
TestCase.assertEqual(arrayCopy[0], null); TestCase.assertEqual(arrayCopy[0], null);
}); });
}, },
testListFiltered: function() {
var personListSchema = {
name: 'PersonList',
properties: {
list: {type: 'list', objectType: 'PersonObject'}
}
};
var realm = new Realm({schema: [schemas.PersonObject, personListSchema]});
var listObject;
realm.write(function() {
listObject = realm.create('PersonList', {list: [
{name: 'Ari', age: 10},
{name: 'Tim', age: 11},
{name: 'Bjarne', age: 12},
{name: 'Alex', age: 12, married: true}
]});
realm.create('PersonObject', {name: 'NotInList', age: 10});
});
var list = listObject.list;
TestCase.assertEqual(list.filtered("truepredicate").length, 4);
TestCase.assertEqual(list.filtered('age = 11')[0].name, 'Tim');
TestCase.assertEqual(list.filtered('age = 12').length, 2);
TestCase.assertEqual(list.filtered('age > 10 && age < 13').length, 3);
TestCase.assertEqual(list.filtered('age > 10').filtered('age < 13').length, 3);
},
}); });

View File

@ -46,10 +46,9 @@ function runQuerySuite(suite) {
} }
}); });
var args;
function getArgs(startArg) { function getArgs(startArg) {
args = test.slice(startArg, startArg + 2); var args = [test[startArg]];
for (var i = startArg + 2; i < test.length; i++) { for (var i = startArg + 1; i < test.length; i++) {
var arg = test[i]; var arg = test[i];
if (Array.isArray(arg)) { if (Array.isArray(arg)) {
// aray arguments correspond to [objectAtIndex, propertyName] // aray arguments correspond to [objectAtIndex, propertyName]
@ -65,14 +64,20 @@ function runQuerySuite(suite) {
for (var index in suite.tests) { for (var index in suite.tests) {
var test = suite.tests[index]; var test = suite.tests[index];
if (test[0] == "QueryCount") { if (test[0] == "QueryCount") {
var length = realm.objects.apply(realm, getArgs(2)).length; var type = test[2];
TestCase.assertEqual(test[1], length, "Query '" + args[1] + "' on type '" + args[0] + "' expected " + test[1] + " results, got " + length); var args = getArgs(3);
var objects = realm.objects(type);
var length = objects.filtered.apply(objects, args).length;
TestCase.assertEqual(test[1], length, "Query '" + args[0] + "' on type '" + type + "' expected " + test[1] + " results, got " + length);
} }
else if (test[0] == "ObjectSet") { else if (test[0] == "ObjectSet") {
var results = realm.objects.apply(realm, getArgs(2)); var type = test[2];
TestCase.assertEqual(test[1].length, results.length, "Query '" + args[1] + "' on type '" + args[0] + "' expected " + test[1].length + " results, got " + results.length); var args = getArgs(3);
var objects = realm.objects(type);
var results = objects.filtered.apply(objects, args);
TestCase.assertEqual(test[1].length, results.length, "Query '" + args[0] + "' on type '" + type+ "' expected " + test[1].length + " results, got " + results.length);
var objSchema = suite.schema.find(function(el) { return el.name == args[0] }); var objSchema = suite.schema.find(function(el) { return el.name == type });
var primary = objSchema.primaryKey; var primary = objSchema.primaryKey;
if (!primary) { if (!primary) {
throw "Primary key required for object comparison"; throw "Primary key required for object comparison";
@ -84,7 +89,8 @@ function runQuerySuite(suite) {
} }
else if (test[0] == "QueryThrows") { else if (test[0] == "QueryThrows") {
TestCase.assertThrows(function() { TestCase.assertThrows(function() {
realm.objects.apply(realm, getArgs(1)); var args = getArgs(2);
realm.objects.apply(realm, args);
}, "Expected exception not thrown for query: " + JSON.stringify(args)); }, "Expected exception not thrown for query: " + JSON.stringify(args));
} }
else if (test[0] != "Disabled") { else if (test[0] != "Disabled") {

View File

@ -290,7 +290,7 @@ module.exports = BaseTest.extend({
TestCase.assertEqual(objects[0].doubleCol, 7, "wrong property value"); TestCase.assertEqual(objects[0].doubleCol, 7, "wrong property value");
TestCase.assertEqual(objects[1].doubleCol, 8, "wrong property value"); TestCase.assertEqual(objects[1].doubleCol, 8, "wrong property value");
var threeObjects = realm.objects('TestObject', "doubleCol < 5"); var threeObjects = realm.objects('TestObject').filtered("doubleCol < 5");
TestCase.assertEqual(threeObjects.length, 3, "wrong results count"); TestCase.assertEqual(threeObjects.length, 3, "wrong results count");
realm.delete(threeObjects); realm.delete(threeObjects);
TestCase.assertEqual(objects.length, 4, 'wrong object count'); TestCase.assertEqual(objects.length, 4, 'wrong object count');
@ -341,40 +341,8 @@ module.exports = BaseTest.extend({
realm.objects('InvalidClass'); realm.objects('InvalidClass');
}); });
TestCase.assertThrows(function() { TestCase.assertThrows(function() {
realm.objects('PersonObject', 'invalid query'); realm.objects('PersonObject', 'truepredicate');
}); });
TestCase.assertThrows(function() {
realm.objects('PersonObject', []);
});
TestCase.assertEqual(realm.objects('PersonObject', "truepredicate").length, 4);
TestCase.assertEqual(realm.objects('PersonObject').length, 4);
TestCase.assertEqual(realm.objects('PersonObject', 'age = 11').length, 1);
TestCase.assertEqual(realm.objects('PersonObject', 'age = 11')[0].name, 'Tim');
TestCase.assertEqual(realm.objects('PersonObject', 'age = 12').length, 2);
TestCase.assertEqual(realm.objects('PersonObject', 'age = 13').length, 0);
TestCase.assertEqual(realm.objects('PersonObject', 'age < 12').length, 2);
TestCase.assertEqual(realm.objects('PersonObject', 'age > 10 && age < 13').length, 3);
TestCase.assertEqual(realm.objects('PersonObject', 'age >= 11 && age < 13').length, 3);
TestCase.assertEqual(realm.objects('PersonObject', 'name = "Tim"').length, 1);
TestCase.assertEqual(realm.objects('PersonObject', 'name = \'Tim\'').length, 1);
TestCase.assertEqual(realm.objects('PersonObject', 'married == TRUE').length, 1);
TestCase.assertEqual(realm.objects('PersonObject', 'married == false').length, 3);
TestCase.assertEqual(realm.objects('PersonObject', 'name = $0', 'Tim').length, 1);
TestCase.assertEqual(realm.objects('PersonObject', 'age > $1 && age < $0', 13, 10).length, 3);
TestCase.assertThrows(function() {
realm.objects('PersonObject', 'age > $2 && age < $0', 13, 10)
});
realm.write(function() {
realm.create('DefaultValuesObject', {'dateCol': new Date(3)});
realm.create('DefaultValuesObject', {'dateCol': new Date(4)});
realm.create('DefaultValuesObject', {'dateCol': new Date(5)});
});
TestCase.assertEqual(realm.objects('DefaultValuesObject', 'dateCol > $0', new Date(4)).length, 1);
TestCase.assertEqual(realm.objects('DefaultValuesObject', 'dateCol <= $0', new Date(4)).length, 2);
}, },
testNotifications: function() { testNotifications: function() {

View File

@ -91,6 +91,50 @@ module.exports = BaseTest.extend({
TestCase.assertEqual(count, 1); TestCase.assertEqual(count, 1);
TestCase.assertEqual(keys.length, 1); TestCase.assertEqual(keys.length, 1);
}, },
testResultsFiltered: function() {
var realm = new Realm({schema: [schemas.PersonObject, schemas.DefaultValues, schemas.TestObject]});
realm.write(function() {
realm.create('PersonObject', {name: 'Ari', age: 10});
realm.create('PersonObject', {name: 'Tim', age: 11});
realm.create('PersonObject', {name: 'Bjarne', age: 12});
realm.create('PersonObject', {name: 'Alex', age: 12, married: true});
});
TestCase.assertEqual(realm.objects('PersonObject').filtered("truepredicate").length, 4);
TestCase.assertEqual(realm.objects('PersonObject').length, 4);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 11').length, 1);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 11')[0].name, 'Tim');
TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 12').length, 2);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 13').length, 0);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age < 12').length, 2);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age > 10 && age < 13').length, 3);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age > 10').filtered('age < 13').length, 3);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age >= 11 && age < 13').length, 3);
TestCase.assertEqual(realm.objects('PersonObject').filtered('name = "Tim"').length, 1);
TestCase.assertEqual(realm.objects('PersonObject').filtered('name = \'Tim\'').length, 1);
TestCase.assertEqual(realm.objects('PersonObject').filtered('married == TRUE').length, 1);
TestCase.assertEqual(realm.objects('PersonObject').filtered('married == false').length, 3);
TestCase.assertEqual(realm.objects('PersonObject').filtered('name = $0', 'Tim').length, 1);
TestCase.assertEqual(realm.objects('PersonObject').filtered('age > $1 && age < $0', 13, 10).length, 3);
TestCase.assertThrows(function() {
realm.objects('PersonObject').filtered('age > $2 && age < $0', 13, 10)
});
realm.write(function() {
realm.create('DefaultValuesObject', {'dateCol': new Date(3)});
realm.create('DefaultValuesObject', {'dateCol': new Date(4)});
realm.create('DefaultValuesObject', {'dateCol': new Date(5)});
});
TestCase.assertEqual(realm.objects('DefaultValuesObject').filtered('dateCol > $0', new Date(4)).length, 1);
TestCase.assertEqual(realm.objects('DefaultValuesObject').filtered('dateCol <= $0', new Date(4)).length, 2);
TestCase.assertThrows(function() {
realm.objects('PersonObject').filtered("invalidQuery");
});
},
testSort: function() { testSort: function() {
var realm = new Realm({schema: [schemas.TestObject]}); var realm = new Realm({schema: [schemas.TestObject]});
var objects = realm.objects('TestObject'); var objects = realm.objects('TestObject');