Parameterized Queries
Instead of a main query, you can instead mark a function or variable declaration with an annotation that declares that function as the file's main query.
Variable Query Declarations
For example, before your main query may have been:
foreach device in network.devices
select { name : device.name }
Now you can instead write:
@query
deviceNames =
foreach device in network.devices
select { name: device.name };
This query can now be run in the same way as a main expression.
Parameterized Queries
Query declarations may also be given parameters. For example, we might have a function that finds all device interfaces that have too many subinterfaces:
findBadInterfaces(threshold) =
foreach device in network.devices
foreach iface in device.interfaces
where length(iface.subinterfaces) > threshold
select { name : device.name, ifaceName : iface.name };
We can expose this function as a query that can be run with two changes to the declaration:
@query
findBadInterfaces(threshold : Number) =
foreach device in network.devices
foreach iface in device.interfaces
where length(iface.subinterfaces) > threshold
select { name : device.name, ifaceName : iface.name };
- The first change is adding an
@queryannotation before the function's declaration. - The second change is providing the type of the
thresholdparameter. Sincethresholdis a number, we declarethresholdto have the typeNumber.
Note
- All query parameters must have a type annotation. For more information, see Parameter Type Annotations.
Note
- Return type annotations are also allowed on
@querydeclarations, but are optional. For more information, see Return Type Annotations.