TinyBase

setQueryDefinition

The setQueryDefinition method lets you set the definition of a query.

setQueryDefinition(
  queryId: string,
  tableId: string,
  query: (keywords: {
    select: Select;
    join: Join;
    where: Where;
    group: Group;
    having: Having;
  }) => void,
): Queries
TypeDescription
queryIdstring

The Id of the query to define.

tableIdstring

The Id of the main Table the query will be based on.

query(keywords: { select: Select; join: Join; where: Where; group: Group; having: Having; }) => void

A callback which can take a keywords object and which uses the functions it contains to define the query.

returnsQueries

A reference to the Queries object.

Every query definition is identified by a unique Id, and if you re-use an existing Id with this method, the previous definition is overwritten.

A query provides a tabular result formed from each Row within a main Table. The definition must specify this 'main' Table (by its Id) to be aggregated. Other Tables can be joined to that using Join clauses.

The third query parameter is a callback that you provide to define the query. That callback is provided with a keywords object that contains the functions you use to define the query, like select, join, and so on. You can see how that is used in the simple example below. The following five clause types are supported:

  • The Select type describes a function that lets you specify a Cell or calculated value for including into the query's result.
  • The Join type describes a function that lets you specify a Cell or calculated value to join the main query Table to others, by Row Id.
  • The Where type describes a function that lets you specify conditions to filter results, based on the underlying Cells of the main or joined Tables.
  • The Group type describes a function that lets you specify that the values of a Cell in multiple result Rows should be aggregated together.
  • The Having type describes a function that lets you specify conditions to filter results, based on the grouped Cells resulting from a Group clause.

Full documentation and examples are provided in the sections for each of those clause types.

Additionally, you can use the getResultSortedRowIds method and addResultSortedRowIdsListener method to sort and paginate the results.

Example

This example creates a Store, creates a Queries object, and defines a simple query to select just one column from the Table, for each Row where the species Cell matches as certain value.

const store = createStore().setTable('pets', {
  fido: {species: 'dog', color: 'brown'},
  felix: {species: 'cat', color: 'black'},
  cujo: {species: 'dog', color: 'black'},
});

const queries = createQueries(store);
queries.setQueryDefinition('dogColors', 'pets', ({select, where}) => {
  select('color');
  where('species', 'dog');
});

console.log(queries.getResultTable('dogColors'));
// -> {fido: {color: 'brown'}, cujo: {color: 'black'}}

Since

v2.0.0