Metakit / API

@doeixd/metakit/aggregates/sql

@doeixd/metakit/aggregates/sql: compile a @doeixd/metakit/aggregates aggregate to SQL for Postgres or SQLite: its value and whether evaluate refuses the rows. Kept apart from @doeixd/metakit/aggregates so a page that evaluates aggregates carries no SQL lowering.

  • sum accumulates integers exactly and is refused when the final total is outside JavaScript's safe integer range. SQLite needs bounds that keep every intermediate sum within its integer accumulator. A contribution that is not a safe integer (a fraction or an integer past the safe range in a column whose Schema rejects it) also refuses it, though evaluate answers: evaluate adds such values as doubles in the order it holds the rows, which SQL does not keep. Postgres lowers integer arithmetic over a column in integers, so a fraction read through $.a + 1 is rounded before the sum sees it.
  • min and max skip nulls; Postgres casts each to DOUBLE PRECISION. sum, min and max are refused where a value is NaN or an infinity, as evaluate is. SQLite holds no NaN: it stores one as NULL, which they skip.
  • count is COUNT(*), or a sum of CASE WHEN p THEN 1 ELSE 0 END; Postgres casts it to INTEGER.
  • every counts an unknown predicate as failing on both dialects (coalesce(p, false); Postgres's BOOL_AND alone would skip it), and any as not holding. SQLite answers 0 or 1.

SQL has no refusal: a row whose contribution refuses lowers to NULL, which an aggregate would skip where evaluate throws. So beside the value the lowering writes the test of refusal, and the value is NULL where it holds. A row whose predicate refuses refuses any only where no row holds, and every only where no row fails, as evaluate settles them. A contribution whose refusal it cannot test (a custom operation's own) is SqlUnsupportedError.

Functions

toSqlCompile aggregate to SQL aggregate expressions over the rows' columns.

Interfaces

AggregateSqlAn aggregate as two expressions for one SELECT list. Write refused after value and bind [...value.params, ...refused.params]: SQLite binds in the order of…
AggregateSqlOptions