Query interface with callback functions
* Added public Query interface * Added filter function callback support * Added "script" function callback support Queries are generated via Compile(), which then may be run via Execute() as many times as needed. Much like compiling a regex, this is done to elide the need to re-parse and build the funciton tree for each execution. The distinction between 'filter' and 'script' is borrowed from their syntactic equivalents in jsonpath. Right now, these accept no arguments in the query, and instead merely pass the current node to the callback. Filters return a bool and determine if the node is kept or culled out. 'Scripts' return a string or an in64, which is in turn used in an index or key filter (respectively) on the current node's data. A few callbacks are provided by default, with the ability to add additional callbacks before calling Execute() on a compiled query.
This commit is contained in:
+37
-8
@@ -12,14 +12,8 @@ func assertQuery(t *testing.T, toml, query string, ref []interface{}) {
|
||||
t.Errorf("Non-nil toml parse error: %v", err)
|
||||
return
|
||||
}
|
||||
_, flow := lex(query)
|
||||
if err != nil {
|
||||
t.Errorf("Non-nil query lex error: %v", err)
|
||||
return
|
||||
}
|
||||
path := parse(flow)
|
||||
result := path.Call(tree)
|
||||
assertValue(t, result, ref, "((" + query + ")) -> ")
|
||||
results := Compile(query).Execute(tree)
|
||||
assertValue(t, results, ref, "((" + query + ")) -> ")
|
||||
}
|
||||
|
||||
func assertValue(t *testing.T, result, ref interface{}, location string) {
|
||||
@@ -233,3 +227,38 @@ func TestQueryRecursionUnionSimple(t *testing.T) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestQueryScriptFnLast(t *testing.T) {
|
||||
assertQuery(t,
|
||||
"[foo]\na = [0,1,2,3,4,5,6,7,8,9]",
|
||||
"$.foo.a[(last)]",
|
||||
[]interface{}{
|
||||
int64(9),
|
||||
})
|
||||
}
|
||||
|
||||
func TestQueryFilterFnOdd(t *testing.T) {
|
||||
assertQuery(t,
|
||||
"[foo]\na = [0,1,2,3,4,5,6,7,8,9]",
|
||||
"$.foo.a[?(odd)]",
|
||||
[]interface{}{
|
||||
int64(1),
|
||||
int64(3),
|
||||
int64(5),
|
||||
int64(7),
|
||||
int64(9),
|
||||
})
|
||||
}
|
||||
|
||||
func TestQueryFilterFnEven(t *testing.T) {
|
||||
assertQuery(t,
|
||||
"[foo]\na = [0,1,2,3,4,5,6,7,8,9]",
|
||||
"$.foo.a[?(even)]",
|
||||
[]interface{}{
|
||||
int64(0),
|
||||
int64(2),
|
||||
int64(4),
|
||||
int64(6),
|
||||
int64(8),
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user