Skip to main content

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 @query annotation before the function's declaration.
  • The second change is providing the type of the threshold parameter. Since threshold is a number, we declare threshold to have the type Number.
Note
Note
  • Return type annotations are also allowed on @query declarations, but are optional. For more information, see Return Type Annotations.