Skip to main content

Compiled Queries

Verse has another query type called a compiled query. Compiled queries are a way to pre-compile a query and then execute it multiple times. This can be useful if you have a query that gets run many times and with different parameters.

Here's an example of a compiled query:

const artistsQuery = db.compile((from, $count: number) =>
from.artists.where(
ar => from.albums.where(al => ar.artistId === al.artistId).count() > $count
)
);

const result1 = await artistsQuery(3).toArray();
const result2 = await artistsQuery(5).toArray();

In this example, we're creating a compiled query that takes two parameters: from and $count. The from parameter is the query root (just like the from property on the Verse object), and the $count parameter is the number of albums that an artist must have to be included in the result. The compile method returns a function that we can call each time we want to execute the query.